1 \input texinfo @c -*-texinfo-*-
3 @setfilename gnat_ugn.info
4 @documentencoding UTF-8
6 @*Generated by Sphinx 1.3b2.@*
8 @settitle GNAT User's Guide for Native Platforms
13 @dircategory GNU Ada Tools
15 * gnat_ugn: (gnat_ugn.info). gnat_ugn
18 @definfoenclose strong,`,'
19 @definfoenclose emph,`,'
24 GNAT User's Guide for Native Platforms , May 12, 2015
28 Copyright @copyright{} 2008-2015, Free Software Foundation
34 @title GNAT User's Guide for Native Platforms
39 @c %** start of user preamble
41 @c %** end of user preamble
45 @top GNAT User's Guide for Native Platforms
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}@*
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}.
68 * Getting Started with GNAT::
69 * The GNAT Compilation Model::
70 * Building Executable Programs with GNAT::
71 * GNAT Project Manager::
72 * Tools Supporting Project Files::
73 * GNAT Utility Programs::
74 * GNAT and Program Execution::
75 * Platform-Specific Information::
76 * Example of Binder Output File::
77 * Elaboration Order Handling in GNAT::
79 * GNU Free Documentation License::
83 --- The Detailed Node Listing ---
87 * What This Guide Contains::
88 * What You Should Know before Reading This Guide::
89 * Related Information::
90 * A Note to Readers of Previous Versions of the Manual::
93 Getting Started with GNAT
96 * Running a Simple Ada Program::
97 * Running a Program with Multiple Units::
98 * Using the gnatmake Utility::
100 The GNAT Compilation Model
102 * Source Representation::
103 * Foreign Language Representation::
104 * File Naming Topics and Utilities::
105 * Configuration Pragmas::
106 * Generating Object Files::
107 * Source Dependencies::
108 * The Ada Library Information Files::
109 * Binding an Ada Program::
110 * GNAT and Libraries::
111 * Conditional Compilation::
112 * Mixed Language Programming::
113 * GNAT and Other Compilation Models::
114 * Using GNAT Files with External Tools::
116 Foreign Language Representation
119 * Other 8-Bit Codes::
120 * Wide_Character Encodings::
121 * Wide_Wide_Character Encodings::
123 File Naming Topics and Utilities
125 * File Naming Rules::
126 * Using Other File Names::
127 * Alternative File Naming Schemes::
128 * Handling Arbitrary File Naming Conventions with gnatname::
129 * File Name Krunching with gnatkr::
130 * Renaming Files with gnatchop::
132 Handling Arbitrary File Naming Conventions with gnatname
134 * Arbitrary File Naming Conventions::
136 * Switches for gnatname::
137 * Examples of gnatname Usage::
139 File Name Krunching with gnatkr
144 * Examples of gnatkr Usage::
146 Renaming Files with gnatchop
148 * Handling Files with Multiple Units::
149 * Operating gnatchop in Compilation Mode::
150 * Command Line for gnatchop::
151 * Switches for gnatchop::
152 * Examples of gnatchop Usage::
154 Configuration Pragmas
156 * Handling of Configuration Pragmas::
157 * The Configuration Pragmas Files::
161 * Introduction to Libraries in GNAT::
162 * General Ada Libraries::
163 * Stand-alone Ada Libraries::
164 * Rebuilding the GNAT Run-Time Library::
166 General Ada Libraries
168 * Building a library::
169 * Installing a library::
172 Stand-alone Ada Libraries
174 * Introduction to Stand-alone Libraries::
175 * Building a Stand-alone Library::
176 * Creating a Stand-alone Library to be used in a non-Ada context::
177 * Restrictions in Stand-alone Libraries::
179 Conditional Compilation
181 * Modeling Conditional Compilation in Ada::
182 * Preprocessing with gnatprep::
183 * Integrated Preprocessing::
185 Modeling Conditional Compilation in Ada
187 * Use of Boolean Constants::
188 * Debugging - A Special Case::
189 * Conditionalizing Declarations::
190 * Use of Alternative Implementations::
193 Preprocessing with gnatprep
195 * Preprocessing Symbols::
197 * Switches for gnatprep::
198 * Form of Definitions File::
199 * Form of Input Text for gnatprep::
201 Mixed Language Programming
204 * Calling Conventions::
205 * Building Mixed Ada and C++ Programs::
206 * Generating Ada Bindings for C and C++ headers::
208 Building Mixed Ada and C++ Programs
210 * Interfacing to C++::
211 * Linking a Mixed C++ & Ada Program::
213 * Interfacing with C++ constructors::
214 * Interfacing with C++ at the Class Level::
216 Generating Ada Bindings for C and C++ headers
218 * Running the binding generator::
219 * Generating bindings for C++ headers::
222 GNAT and Other Compilation Models
224 * Comparison between GNAT and C/C++ Compilation Models::
225 * Comparison between GNAT and Conventional Ada Library Models::
227 Using GNAT Files with External Tools
229 * Using Other Utility Programs with GNAT::
230 * The External Symbol Naming Scheme of GNAT::
232 Building Executable Programs with GNAT
234 * Building with gnatmake::
235 * Compiling with gcc::
236 * Compiler Switches::
237 * Binding with gnatbind::
238 * Linking with gnatlink::
239 * Using the GNU make Utility::
241 Building with gnatmake
244 * Switches for gnatmake::
245 * Mode Switches for gnatmake::
246 * Notes on the Command Line::
247 * How gnatmake Works::
248 * Examples of gnatmake Usage::
252 * Compiling Programs::
253 * Search Paths and the Run-Time Library (RTL): Search Paths and the Run-Time Library RTL.
254 * Order of Compilation Issues::
259 * Alphabetical List of All Switches::
260 * Output and Error Message Control::
261 * Warning Message Control::
262 * Debugging and Assertion Control::
263 * Validity Checking::
266 * Using gcc for Syntax Checking::
267 * Using gcc for Semantic Checking::
268 * Compiling Different Versions of Ada::
269 * Character Set Control::
270 * File Naming Control::
271 * Subprogram Inlining Control::
272 * Auxiliary Output Control::
273 * Debugging Control::
274 * Exception Handling Control::
275 * Units to Sources Mapping Files::
276 * Code Generation Control::
278 Binding with gnatbind
281 * Switches for gnatbind::
282 * Command-Line Access::
283 * Search Paths for gnatbind::
284 * Examples of gnatbind Usage::
286 Switches for gnatbind
288 * Consistency-Checking Modes::
289 * Binder Error Message Control::
290 * Elaboration Control::
292 * Dynamic Allocation Control::
293 * Binding with Non-Ada Main Programs::
294 * Binding Programs with No Main Subprogram::
296 Linking with gnatlink
299 * Switches for gnatlink::
301 Using the GNU make Utility
303 * Using gnatmake in a Makefile::
304 * Automatically Creating a List of Directories::
305 * Generating the Command Line Switches::
306 * Overcoming Command Line Length Limits::
311 * Building With Projects::
312 * Organizing Projects into Subsystems::
313 * Scenarios in Projects::
315 * Project Extension::
316 * Aggregate Projects::
317 * Aggregate Library Projects::
318 * Project File Reference::
320 Building With Projects
322 * Source Files and Directories::
323 * Duplicate Sources in Projects::
324 * Object and Exec Directory::
326 * Tools Options in Project Files::
327 * Compiling with Project Files::
328 * Executable File Names::
329 * Avoid Duplication With Variables::
332 * Distributed support::
334 Organizing Projects into Subsystems
336 * Project Dependencies::
337 * Cyclic Project Dependencies::
338 * Sharing Between Projects::
339 * Global Attributes::
343 * Building Libraries::
344 * Using Library Projects::
345 * Stand-alone Library Projects::
346 * Installing a library with project files::
350 * Project Hierarchy Extension::
354 * Building all main programs from a single project tree::
355 * Building a set of projects with a single command::
356 * Define a build environment::
357 * Performance improvements in builder::
358 * Syntax of aggregate projects::
359 * package Builder in aggregate projects::
361 Aggregate Library Projects
363 * Building aggregate library projects::
364 * Syntax of aggregate library projects::
366 Project File Reference
368 * Project Declaration::
369 * Qualified Projects::
374 * Typed String Declaration::
376 * Case Constructions::
381 * Project Level Attributes::
382 * Package Binder Attributes::
383 * Package Builder Attributes::
384 * Package Clean Attributes::
385 * Package Compiler Attributes::
386 * Package Cross_Reference Attributes::
387 * Package Finder Attributes::
388 * Package gnatls Attributes::
389 * Package IDE Attributes::
390 * Package Install Attributes::
391 * Package Linker Attributes::
392 * Package Naming Attributes::
393 * Package Remote Attributes::
394 * Package Stack Attributes::
395 * Package Synchronize Attributes::
397 Tools Supporting Project Files
399 * gnatmake and Project Files::
400 * The GNAT Driver and Project Files::
402 gnatmake and Project Files
404 * Switches Related to Project Files::
405 * Switches and Project Files::
406 * Specifying Configuration Pragmas::
407 * Project Files and Main Subprograms::
408 * Library Project Files::
410 GNAT Utility Programs
412 * The File Cleanup Utility gnatclean::
413 * The GNAT Library Browser gnatls::
414 * The Cross-Referencing Tools gnatxref and gnatfind::
415 * The Ada to HTML Converter gnathtml::
417 The File Cleanup Utility gnatclean
419 * Running gnatclean::
420 * Switches for gnatclean::
422 The GNAT Library Browser gnatls
425 * Switches for gnatls::
426 * Example of gnatls Usage::
428 The Cross-Referencing Tools gnatxref and gnatfind
430 * gnatxref Switches::
431 * gnatfind Switches::
432 * Project Files for gnatxref and gnatfind::
433 * Regular Expressions in gnatfind and gnatxref::
434 * Examples of gnatxref Usage::
435 * Examples of gnatfind Usage::
437 Examples of gnatxref Usage
440 * Using gnatxref with vi::
442 The Ada to HTML Converter gnathtml
444 * Invoking gnathtml::
445 * Installing gnathtml::
447 GNAT and Program Execution
449 * Running and Debugging Ada Programs::
450 * Code Coverage and Profiling::
451 * Improving Performance::
452 * Overflow Check Handling in GNAT::
453 * Performing Dimensionality Analysis in GNAT::
454 * Stack Related Facilities::
455 * Memory Management Issues::
457 Running and Debugging Ada Programs
459 * The GNAT Debugger GDB::
461 * Introduction to GDB Commands::
462 * Using Ada Expressions::
463 * Calling User-Defined Subprograms::
464 * Using the next Command in a Function::
465 * Stopping When Ada Exceptions Are Raised::
467 * Debugging Generic Units::
468 * Remote Debugging with gdbserver::
469 * GNAT Abnormal Termination or Failure to Terminate::
470 * Naming Conventions for GNAT Source Files::
471 * Getting Internal Debugging Information::
476 * Non-Symbolic Traceback::
477 * Symbolic Traceback::
479 Code Coverage and Profiling
481 * Code Coverage of Ada Programs with gcov::
482 * Profiling an Ada Program with gprof::
484 Code Coverage of Ada Programs with gcov
486 * Quick startup guide::
489 Profiling an Ada Program with gprof
491 * Compilation for profiling::
492 * Program execution::
494 * Interpretation of profiling results::
496 Improving Performance
498 * Performance Considerations::
499 * Text_IO Suggestions::
500 * Reducing Size of Executables with Unused Subprogram/Data Elimination::
502 Performance Considerations
504 * Controlling Run-Time Checks::
505 * Use of Restrictions::
506 * Optimization Levels::
507 * Debugging Optimized Code::
508 * Inlining of Subprograms::
509 * Floating_Point_Operations::
510 * Vectorization of loops::
511 * Other Optimization Switches::
512 * Optimization and Strict Aliasing::
513 * Aliased Variables and Optimization::
514 * Atomic Variables and Optimization::
515 * Passive Task Optimization::
517 Reducing Size of Executables with Unused Subprogram/Data Elimination
519 * About unused subprogram/data elimination::
520 * Compilation options::
521 * Example of unused subprogram/data elimination::
523 Overflow Check Handling in GNAT
526 * Overflow Checking Modes in GNAT::
527 * Specifying the Desired Mode::
529 * Implementation Notes::
531 Stack Related Facilities
533 * Stack Overflow Checking::
534 * Static Stack Usage Analysis::
535 * Dynamic Stack Usage Analysis::
537 Memory Management Issues
539 * Some Useful Memory Pools::
540 * The GNAT Debug Pool Facility::
542 Platform-Specific Information
544 * Run-Time Libraries::
545 * Specifying a Run-Time Library::
546 * Microsoft Windows Topics::
551 * Summary of Run-Time Configurations::
553 Specifying a Run-Time Library
555 * Choosing the Scheduling Policy::
556 * Solaris-Specific Considerations::
557 * Solaris Threads Issues::
558 * AIX-Specific Considerations::
560 Microsoft Windows Topics
562 * Using GNAT on Windows::
563 * Using a network installation of GNAT::
564 * CONSOLE and WINDOWS subsystems::
566 * Mixed-Language Programming on Windows::
568 Mixed-Language Programming on Windows
570 * Windows Calling Conventions::
571 * Introduction to Dynamic Link Libraries (DLLs): Introduction to Dynamic Link Libraries DLLs.
572 * Using DLLs with GNAT::
573 * Building DLLs with GNAT Project files::
574 * Building DLLs with GNAT::
575 * Building DLLs with gnatdll::
576 * Ada DLLs and Finalization::
577 * Creating a Spec for Ada DLLs::
578 * GNAT and Windows Resources::
580 * Setting Stack Size from gnatlink::
581 * Setting Heap Size from gnatlink::
583 Windows Calling Conventions
585 * C Calling Convention::
586 * Stdcall Calling Convention::
587 * Win32 Calling Convention::
588 * DLL Calling Convention::
592 * Creating an Ada Spec for the DLL Services::
593 * Creating an Import Library::
595 Building DLLs with gnatdll
597 * Limitations When Using Ada DLLs from Ada::
598 * Exporting Ada Entities::
599 * Ada DLLs and Elaboration::
601 Creating a Spec for Ada DLLs
603 * Creating the Definition File::
606 GNAT and Windows Resources
608 * Building Resources::
609 * Compiling Resources::
614 * Program and DLL Both Built with GCC/GNAT::
615 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
619 * Codesigning the Debugger::
621 Elaboration Order Handling in GNAT
624 * Checking the Elaboration Order::
625 * Controlling the Elaboration Order::
626 * Controlling Elaboration in GNAT - Internal Calls::
627 * Controlling Elaboration in GNAT - External Calls::
628 * Default Behavior in GNAT - Ensuring Safety::
629 * Treatment of Pragma Elaborate::
630 * Elaboration Issues for Library Tasks::
631 * Mixing Elaboration Models::
632 * What to Do If the Default Elaboration Behavior Fails::
633 * Elaboration for Indirect Calls::
634 * Summary of Procedures for Elaboration Control::
635 * Other Elaboration Order Considerations::
636 * Determining the Chosen Elaboration Order::
640 * Basic Assembler Syntax::
641 * A Simple Example of Inline Assembler::
642 * Output Variables in Inline Assembler::
643 * Input Variables in Inline Assembler::
644 * Inlining Inline Assembler Code::
645 * Other Asm Functionality::
647 Other Asm Functionality
649 * The Clobber Parameter::
650 * The Volatile Parameter::
655 @node About This Guide,Getting Started with GNAT,Top,Top
656 @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}
657 @chapter About This Guide
661 This guide describes the use of GNAT,
662 a compiler and software development
663 toolset for the full Ada programming language.
664 It documents the features of the compiler and tools, and explains
665 how to use them to build Ada applications.
667 GNAT implements Ada 95, Ada 2005 and Ada 2012, and it may also be
668 invoked in Ada 83 compatibility mode.
669 By default, GNAT assumes Ada 2012, but you can override with a
670 compiler switch (@ref{6,,Compiling Different Versions of Ada})
671 to explicitly specify the language version.
672 Throughout this manual, references to 'Ada' without a year suffix
673 apply to all Ada 95/2005/2012 versions of the language.
676 * What This Guide Contains::
677 * What You Should Know before Reading This Guide::
678 * Related Information::
679 * A Note to Readers of Previous Versions of the Manual::
684 @node What This Guide Contains,What You Should Know before Reading This Guide,,About This Guide
685 @anchor{gnat_ugn/about_this_guide what-this-guide-contains}@anchor{7}
686 @section What This Guide Contains
689 This guide contains the following chapters:
695 @ref{8,,Getting Started with GNAT} describes how to get started compiling
696 and running Ada programs with the GNAT Ada programming environment.
699 @ref{9,,The GNAT Compilation Model} describes the compilation model used
703 @ref{a,,Building Executable Programs with GNAT} describes how to use the
704 main GNAT tools to build executable programs, and it also gives examples of
705 using the GNU make utility with GNAT.
708 @ref{b,,GNAT Project Manager} describes how to use project files
709 to organize large projects.
712 @ref{c,,Tools Supporting Project Files} described how to use the project
713 facility in conjunction with various GNAT tools.
716 @ref{d,,GNAT Utility Programs} explains the various utility programs that
717 are included in the GNAT environment
720 @ref{e,,GNAT and Program Execution} covers a number of topics related to
721 running, debugging, and tuning the performace of programs developed
725 Appendices cover several additional topics:
731 @ref{f,,Platform-Specific Information} describes the different run-time
732 library implementations and also presents information on how to use
733 GNAT on several specific platforms
736 @ref{10,,Example of Binder Output File} shows the source code for the binder
737 output file for a sample program.
740 @ref{11,,Elaboration Order Handling in GNAT} describes how GNAT helps
741 you deal with elaboration order issues.
744 @ref{12,,Inline Assembler} shows how to use the inline assembly facility
748 @node What You Should Know before Reading This Guide,Related Information,What This Guide Contains,About This Guide
749 @anchor{gnat_ugn/about_this_guide what-you-should-know-before-reading-this-guide}@anchor{13}
750 @section What You Should Know before Reading This Guide
753 @geindex Ada 95 Language Reference Manual
755 @geindex Ada 2005 Language Reference Manual
757 This guide assumes a basic familiarity with the Ada 95 language, as
758 described in the International Standard ANSI/ISO/IEC-8652:1995, January
760 It does not require knowledge of the features introduced by Ada 2005
762 Reference manuals for Ada 95, Ada 2005, and Ada 2012 are included in
763 the GNAT documentation package.
765 @node Related Information,A Note to Readers of Previous Versions of the Manual,What You Should Know before Reading This Guide,About This Guide
766 @anchor{gnat_ugn/about_this_guide related-information}@anchor{14}
767 @section Related Information
770 For further information about Ada and related tools, please refer to the
777 @cite{Ada 95 Reference Manual}, @cite{Ada 2005 Reference Manual}, and
778 @cite{Ada 2012 Reference Manual}, which contain reference
779 material for the several revisions of the Ada language standard.
782 @cite{GNAT Reference_Manual}, which contains all reference material for the GNAT
783 implementation of Ada.
786 @cite{Using the GNAT Programming Studio}, which describes the GPS
787 Integrated Development Environment.
790 @cite{GNAT Programming Studio Tutorial}, which introduces the
791 main GPS features through examples.
794 @cite{Debugging with GDB},
795 for all details on the use of the GNU source-level debugger.
798 @cite{GNU Emacs Manual},
799 for full information on the extensible editor and programming
803 @node A Note to Readers of Previous Versions of the Manual,Conventions,Related Information,About This Guide
804 @anchor{gnat_ugn/about_this_guide a-note-to-readers-of-previous-versions-of-the-manual}@anchor{15}
805 @section A Note to Readers of Previous Versions of the Manual
808 In early 2015 the GNAT manuals were transitioned to the
809 reStructuredText (rst) / Sphinx documentation generator technology.
810 During that process the @cite{GNAT User's Guide} was reorganized
811 so that related topics would be described together in the same chapter
812 or appendix. Here's a summary of the major changes realized in
813 the new document structure.
819 @ref{9,,The GNAT Compilation Model} has been extended so that it now covers
820 the following material:
826 The @cite{gnatname}, @cite{gnatkr}, and @cite{gnatchop} tools
829 @ref{16,,Configuration Pragmas}
832 @ref{17,,GNAT and Libraries}
835 @ref{18,,Conditional Compilation} including @ref{19,,Preprocessing with gnatprep}
836 and @ref{1a,,Integrated Preprocessing}
839 @ref{1b,,Generating Ada Bindings for C and C++ headers}
842 @ref{1c,,Using GNAT Files with External Tools}
846 @ref{a,,Building Executable Programs with GNAT} is a new chapter consolidating
847 the following content:
853 @ref{1d,,Building with gnatmake}
856 @ref{1e,,Compiling with gcc}
859 @ref{1f,,Binding with gnatbind}
862 @ref{20,,Linking with gnatlink}
865 @ref{21,,Using the GNU make Utility}
869 @ref{d,,GNAT Utility Programs} is a new chapter consolidating the information about several
877 @ref{22,,The File Cleanup Utility gnatclean}
880 @ref{23,,The GNAT Library Browser gnatls}
883 @ref{24,,The Cross-Referencing Tools gnatxref and gnatfind}
886 @ref{25,,The Ada to HTML Converter gnathtml}
890 @ref{e,,GNAT and Program Execution} is a new chapter consolidating the following:
896 @ref{26,,Running and Debugging Ada Programs}
899 @ref{27,,Code Coverage and Profiling}
902 @ref{28,,Improving Performance}
905 @ref{29,,Overflow Check Handling in GNAT}
908 @ref{2a,,Performing Dimensionality Analysis in GNAT}
911 @ref{2b,,Stack Related Facilities}
914 @ref{2c,,Memory Management Issues}
918 @ref{f,,Platform-Specific Information} is a new appendix consolidating the following:
924 @ref{2d,,Run-Time Libraries}
927 @ref{2e,,Microsoft Windows Topics}
930 @ref{2f,,Mac OS Topics}
934 The @cite{Compatibility and Porting Guide} appendix has been moved to the
935 @cite{GNAT Reference Manual}. It now includes a section
936 @cite{Writing Portable Fixed-Point Declarations} which was previously
937 a separate chapter in the @cite{GNAT User's Guide}.
940 @node Conventions,,A Note to Readers of Previous Versions of the Manual,About This Guide
941 @anchor{gnat_ugn/about_this_guide conventions}@anchor{30}
946 @geindex typographical
948 @geindex Typographical conventions
950 Following are examples of the typographical and graphic conventions used
957 @cite{Functions}, @cite{utility program names}, @cite{standard names},
973 [optional information or parameters]
976 Examples are described by text
979 and then shown this way.
983 Commands that are entered by the user are shown as preceded by a prompt string
984 comprising the @code{$} character followed by a space.
987 Full file names are shown with the '/' character
988 as the directory separator; e.g., @code{parent-dir/subdir/myfile.adb}.
989 If you are using GNAT on a Windows platform, please note that
990 the '\' character should be used instead.
993 @node Getting Started with GNAT,The GNAT Compilation Model,About This Guide,Top
994 @anchor{gnat_ugn/getting_started_with_gnat getting-started-with-gnat}@anchor{8}@anchor{gnat_ugn/getting_started_with_gnat doc}@anchor{31}@anchor{gnat_ugn/getting_started_with_gnat id1}@anchor{32}
995 @chapter Getting Started with GNAT
998 This chapter describes how to use GNAT's command line interface to build
999 executable Ada programs.
1000 On most platforms a visually oriented Integrated Development Environment
1001 is also available, the GNAT Programming Studio (GPS).
1002 GPS offers a graphical "look and feel", support for development in
1003 other programming languages, comprehensive browsing features, and
1004 many other capabilities.
1005 For information on GPS please refer to
1006 @cite{Using the GNAT Programming Studio}.
1010 * Running a Simple Ada Program::
1011 * Running a Program with Multiple Units::
1012 * Using the gnatmake Utility::
1016 @node Running GNAT,Running a Simple Ada Program,,Getting Started with GNAT
1017 @anchor{gnat_ugn/getting_started_with_gnat running-gnat}@anchor{33}@anchor{gnat_ugn/getting_started_with_gnat id2}@anchor{34}
1018 @section Running GNAT
1021 Three steps are needed to create an executable file from an Ada source
1028 The source file(s) must be compiled.
1031 The file(s) must be bound using the GNAT binder.
1034 All appropriate object files must be linked to produce an executable.
1037 All three steps are most commonly handled by using the @emph{gnatmake}
1038 utility program that, given the name of the main program, automatically
1039 performs the necessary compilation, binding and linking steps.
1041 @node Running a Simple Ada Program,Running a Program with Multiple Units,Running GNAT,Getting Started with GNAT
1042 @anchor{gnat_ugn/getting_started_with_gnat running-a-simple-ada-program}@anchor{35}@anchor{gnat_ugn/getting_started_with_gnat id3}@anchor{36}
1043 @section Running a Simple Ada Program
1046 Any text editor may be used to prepare an Ada program.
1047 (If Emacs is used, the optional Ada mode may be helpful in laying out the
1049 The program text is a normal text file. We will assume in our initial
1050 example that you have used your editor to prepare the following
1051 standard format text file:
1054 with Ada.Text_IO; use Ada.Text_IO;
1057 Put_Line ("Hello WORLD!");
1061 This file should be named @code{hello.adb}.
1062 With the normal default file naming conventions, GNAT requires
1064 contain a single compilation unit whose file name is the
1066 with periods replaced by hyphens; the
1067 extension is @code{ads} for a
1068 spec and @code{adb} for a body.
1069 You can override this default file naming convention by use of the
1070 special pragma @cite{Source_File_Name} (for further information please
1071 see @ref{37,,Using Other File Names}).
1072 Alternatively, if you want to rename your files according to this default
1073 convention, which is probably more convenient if you will be using GNAT
1074 for all your compilations, then the @cite{gnatchop} utility
1075 can be used to generate correctly-named source files
1076 (see @ref{38,,Renaming Files with gnatchop}).
1078 You can compile the program using the following command (@cite{$} is used
1079 as the command prompt in the examples in this document):
1085 @emph{gcc} is the command used to run the compiler. This compiler is
1086 capable of compiling programs in several languages, including Ada and
1087 C. It assumes that you have given it an Ada program if the file extension is
1088 either @code{.ads} or @code{.adb}, and it will then call
1089 the GNAT compiler to compile the specified file.
1091 The @code{-c} switch is required. It tells @emph{gcc} to only do a
1092 compilation. (For C programs, @emph{gcc} can also do linking, but this
1093 capability is not used directly for Ada programs, so the @code{-c}
1094 switch must always be present.)
1096 This compile command generates a file
1097 @code{hello.o}, which is the object
1098 file corresponding to your Ada program. It also generates
1099 an 'Ada Library Information' file @code{hello.ali},
1100 which contains additional information used to check
1101 that an Ada program is consistent.
1102 To build an executable file,
1103 use @cite{gnatbind} to bind the program
1104 and @emph{gnatlink} to link it. The
1105 argument to both @cite{gnatbind} and @emph{gnatlink} is the name of the
1106 @code{ALI} file, but the default extension of @code{.ali} can
1107 be omitted. This means that in the most common case, the argument
1108 is simply the name of the main program:
1115 A simpler method of carrying out these steps is to use @emph{gnatmake},
1116 a master program that invokes all the required
1117 compilation, binding and linking tools in the correct order. In particular,
1118 @emph{gnatmake} automatically recompiles any sources that have been
1119 modified since they were last compiled, or sources that depend
1120 on such modified sources, so that 'version skew' is avoided.
1122 @geindex Version skew (avoided by *gnatmake*)
1125 $ gnatmake hello.adb
1128 The result is an executable program called @code{hello}, which can be
1135 assuming that the current directory is on the search path
1136 for executable programs.
1138 and, if all has gone well, you will see:
1144 appear in response to this command.
1146 @node Running a Program with Multiple Units,Using the gnatmake Utility,Running a Simple Ada Program,Getting Started with GNAT
1147 @anchor{gnat_ugn/getting_started_with_gnat id4}@anchor{39}@anchor{gnat_ugn/getting_started_with_gnat running-a-program-with-multiple-units}@anchor{3a}
1148 @section Running a Program with Multiple Units
1151 Consider a slightly more complicated example that has three files: a
1152 main program, and the spec and body of a package:
1155 package Greetings is
1160 with Ada.Text_IO; use Ada.Text_IO;
1161 package body Greetings is
1164 Put_Line ("Hello WORLD!");
1167 procedure Goodbye is
1169 Put_Line ("Goodbye WORLD!");
1181 Following the one-unit-per-file rule, place this program in the
1182 following three separate files:
1187 @item @emph{greetings.ads}
1189 spec of package @cite{Greetings}
1191 @item @emph{greetings.adb}
1193 body of package @cite{Greetings}
1195 @item @emph{gmain.adb}
1197 body of main program
1200 To build an executable version of
1201 this program, we could use four separate steps to compile, bind, and link
1202 the program, as follows:
1206 $ gcc -c greetings.adb
1211 Note that there is no required order of compilation when using GNAT.
1212 In particular it is perfectly fine to compile the main program first.
1213 Also, it is not necessary to compile package specs in the case where
1214 there is an accompanying body; you only need to compile the body. If you want
1215 to submit these files to the compiler for semantic checking and not code
1216 generation, then use the @code{-gnatc} switch:
1219 $ gcc -c greetings.ads -gnatc
1222 Although the compilation can be done in separate steps as in the
1223 above example, in practice it is almost always more convenient
1224 to use the @emph{gnatmake} tool. All you need to know in this case
1225 is the name of the main program's source file. The effect of the above four
1226 commands can be achieved with a single one:
1229 $ gnatmake gmain.adb
1232 In the next section we discuss the advantages of using @emph{gnatmake} in
1235 @node Using the gnatmake Utility,,Running a Program with Multiple Units,Getting Started with GNAT
1236 @anchor{gnat_ugn/getting_started_with_gnat using-the-gnatmake-utility}@anchor{3b}@anchor{gnat_ugn/getting_started_with_gnat id5}@anchor{3c}
1237 @section Using the @emph{gnatmake} Utility
1240 If you work on a program by compiling single components at a time using
1241 @emph{gcc}, you typically keep track of the units you modify. In order to
1242 build a consistent system, you compile not only these units, but also any
1243 units that depend on the units you have modified.
1244 For example, in the preceding case,
1245 if you edit @code{gmain.adb}, you only need to recompile that file. But if
1246 you edit @code{greetings.ads}, you must recompile both
1247 @code{greetings.adb} and @code{gmain.adb}, because both files contain
1248 units that depend on @code{greetings.ads}.
1250 @emph{gnatbind} will warn you if you forget one of these compilation
1251 steps, so that it is impossible to generate an inconsistent program as a
1252 result of forgetting to do a compilation. Nevertheless it is tedious and
1253 error-prone to keep track of dependencies among units.
1254 One approach to handle the dependency-bookkeeping is to use a
1255 makefile. However, makefiles present maintenance problems of their own:
1256 if the dependencies change as you change the program, you must make
1257 sure that the makefile is kept up-to-date manually, which is also an
1258 error-prone process.
1260 The @emph{gnatmake} utility takes care of these details automatically.
1261 Invoke it using either one of the following forms:
1264 $ gnatmake gmain.adb
1268 The argument is the name of the file containing the main program;
1269 you may omit the extension. @emph{gnatmake}
1270 examines the environment, automatically recompiles any files that need
1271 recompiling, and binds and links the resulting set of object files,
1272 generating the executable file, @code{gmain}.
1273 In a large program, it
1274 can be extremely helpful to use @emph{gnatmake}, because working out by hand
1275 what needs to be recompiled can be difficult.
1277 Note that @emph{gnatmake} takes into account all the Ada rules that
1278 establish dependencies among units. These include dependencies that result
1279 from inlining subprogram bodies, and from
1280 generic instantiation. Unlike some other
1281 Ada make tools, @emph{gnatmake} does not rely on the dependencies that were
1282 found by the compiler on a previous compilation, which may possibly
1283 be wrong when sources change. @emph{gnatmake} determines the exact set of
1284 dependencies from scratch each time it is run.
1286 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
1288 @node The GNAT Compilation Model,Building Executable Programs with GNAT,Getting Started with GNAT,Top
1289 @anchor{gnat_ugn/the_gnat_compilation_model doc}@anchor{3d}@anchor{gnat_ugn/the_gnat_compilation_model the-gnat-compilation-model}@anchor{9}@anchor{gnat_ugn/the_gnat_compilation_model id1}@anchor{3e}
1290 @chapter The GNAT Compilation Model
1293 @geindex GNAT compilation model
1295 @geindex Compilation model
1297 This chapter describes the compilation model used by GNAT. Although
1298 similar to that used by other languages such as C and C++, this model
1299 is substantially different from the traditional Ada compilation models,
1300 which are based on a centralized program library. The chapter covers
1301 the following material:
1307 Topics related to source file makeup and naming
1313 @ref{3f,,Source Representation}
1316 @ref{40,,Foreign Language Representation}
1319 @ref{41,,File Naming Topics and Utilities}
1323 @ref{16,,Configuration Pragmas}
1326 @ref{42,,Generating Object Files}
1329 @ref{43,,Source Dependencies}
1332 @ref{44,,The Ada Library Information Files}
1335 @ref{45,,Binding an Ada Program}
1338 @ref{17,,GNAT and Libraries}
1341 @ref{18,,Conditional Compilation}
1344 @ref{46,,Mixed Language Programming}
1347 @ref{47,,GNAT and Other Compilation Models}
1350 @ref{1c,,Using GNAT Files with External Tools}
1354 * Source Representation::
1355 * Foreign Language Representation::
1356 * File Naming Topics and Utilities::
1357 * Configuration Pragmas::
1358 * Generating Object Files::
1359 * Source Dependencies::
1360 * The Ada Library Information Files::
1361 * Binding an Ada Program::
1362 * GNAT and Libraries::
1363 * Conditional Compilation::
1364 * Mixed Language Programming::
1365 * GNAT and Other Compilation Models::
1366 * Using GNAT Files with External Tools::
1370 @node Source Representation,Foreign Language Representation,,The GNAT Compilation Model
1371 @anchor{gnat_ugn/the_gnat_compilation_model source-representation}@anchor{3f}@anchor{gnat_ugn/the_gnat_compilation_model id2}@anchor{48}
1372 @section Source Representation
1383 Ada source programs are represented in standard text files, using
1384 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1385 7-bit ASCII set, plus additional characters used for
1386 representing foreign languages (see @ref{40,,Foreign Language Representation}
1387 for support of non-USA character sets). The format effector characters
1388 are represented using their standard ASCII encodings, as follows:
1393 @multitable {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxx}
1470 Source files are in standard text file format. In addition, GNAT will
1471 recognize a wide variety of stream formats, in which the end of
1472 physical lines is marked by any of the following sequences:
1473 @cite{LF}, @cite{CR}, @cite{CR-LF}, or @cite{LF-CR}. This is useful
1474 in accommodating files that are imported from other operating systems.
1476 @geindex End of source file; Source file@comma{} end
1478 @geindex SUB (control character)
1480 The end of a source file is normally represented by the physical end of
1481 file. However, the control character @cite{16#1A#} (@code{SUB}) is also
1482 recognized as signalling the end of the source file. Again, this is
1483 provided for compatibility with other operating systems where this
1484 code is used to represent the end of file.
1486 @geindex spec (definition)
1487 @geindex compilation (definition)
1489 Each file contains a single Ada compilation unit, including any pragmas
1490 associated with the unit. For example, this means you must place a
1491 package declaration (a package @cite{spec}) and the corresponding body in
1492 separate files. An Ada @cite{compilation} (which is a sequence of
1493 compilation units) is represented using a sequence of files. Similarly,
1494 you will place each subunit or child unit in a separate file.
1496 @node Foreign Language Representation,File Naming Topics and Utilities,Source Representation,The GNAT Compilation Model
1497 @anchor{gnat_ugn/the_gnat_compilation_model foreign-language-representation}@anchor{40}@anchor{gnat_ugn/the_gnat_compilation_model id3}@anchor{49}
1498 @section Foreign Language Representation
1501 GNAT supports the standard character sets defined in Ada as well as
1502 several other non-standard character sets for use in localized versions
1503 of the compiler (@ref{4a,,Character Set Control}).
1507 * Other 8-Bit Codes::
1508 * Wide_Character Encodings::
1509 * Wide_Wide_Character Encodings::
1513 @node Latin-1,Other 8-Bit Codes,,Foreign Language Representation
1514 @anchor{gnat_ugn/the_gnat_compilation_model id4}@anchor{4b}@anchor{gnat_ugn/the_gnat_compilation_model latin-1}@anchor{4c}
1520 The basic character set is Latin-1. This character set is defined by ISO
1521 standard 8859, part 1. The lower half (character codes @cite{16#00#}
1522 ... @cite{16#7F#)} is identical to standard ASCII coding, but the upper
1523 half is used to represent additional characters. These include extended letters
1524 used by European languages, such as French accents, the vowels with umlauts
1525 used in German, and the extra letter A-ring used in Swedish.
1527 @geindex Ada.Characters.Latin_1
1529 For a complete list of Latin-1 codes and their encodings, see the source
1530 file of library unit @cite{Ada.Characters.Latin_1} in file
1531 @code{a-chlat1.ads}.
1532 You may use any of these extended characters freely in character or
1533 string literals. In addition, the extended characters that represent
1534 letters can be used in identifiers.
1536 @node Other 8-Bit Codes,Wide_Character Encodings,Latin-1,Foreign Language Representation
1537 @anchor{gnat_ugn/the_gnat_compilation_model other-8-bit-codes}@anchor{4d}@anchor{gnat_ugn/the_gnat_compilation_model id5}@anchor{4e}
1538 @subsection Other 8-Bit Codes
1541 GNAT also supports several other 8-bit coding schemes:
1550 @item @emph{ISO 8859-2 (Latin-2)}
1552 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1563 @item @emph{ISO 8859-3 (Latin-3)}
1565 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1576 @item @emph{ISO 8859-4 (Latin-4)}
1578 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1589 @item @emph{ISO 8859-5 (Cyrillic)}
1591 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1592 lowercase equivalence.
1595 @geindex ISO 8859-15
1602 @item @emph{ISO 8859-15 (Latin-9)}
1604 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1605 lowercase equivalence
1608 @geindex code page 437 (IBM PC)
1613 @item @emph{IBM PC (code page 437)}
1615 This code page is the normal default for PCs in the U.S. It corresponds
1616 to the original IBM PC character set. This set has some, but not all, of
1617 the extended Latin-1 letters, but these letters do not have the same
1618 encoding as Latin-1. In this mode, these letters are allowed in
1619 identifiers with uppercase and lowercase equivalence.
1622 @geindex code page 850 (IBM PC)
1627 @item @emph{IBM PC (code page 850)}
1629 This code page is a modification of 437 extended to include all the
1630 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1631 mode, all these letters are allowed in identifiers with uppercase and
1632 lowercase equivalence.
1634 @item @emph{Full Upper 8-bit}
1636 Any character in the range 80-FF allowed in identifiers, and all are
1637 considered distinct. In other words, there are no uppercase and lowercase
1638 equivalences in this range. This is useful in conjunction with
1639 certain encoding schemes used for some foreign character sets (e.g.,
1640 the typical method of representing Chinese characters on the PC).
1642 @item @emph{No Upper-Half}
1644 No upper-half characters in the range 80-FF are allowed in identifiers.
1645 This gives Ada 83 compatibility for identifier names.
1648 For precise data on the encodings permitted, and the uppercase and lowercase
1649 equivalences that are recognized, see the file @code{csets.adb} in
1650 the GNAT compiler sources. You will need to obtain a full source release
1651 of GNAT to obtain this file.
1653 @node Wide_Character Encodings,Wide_Wide_Character Encodings,Other 8-Bit Codes,Foreign Language Representation
1654 @anchor{gnat_ugn/the_gnat_compilation_model id6}@anchor{4f}@anchor{gnat_ugn/the_gnat_compilation_model wide-character-encodings}@anchor{50}
1655 @subsection Wide_Character Encodings
1658 GNAT allows wide character codes to appear in character and string
1659 literals, and also optionally in identifiers, by means of the following
1660 possible encoding schemes:
1665 @item @emph{Hex Coding}
1667 In this encoding, a wide character is represented by the following five
1674 where @cite{a}, @cite{b}, @cite{c}, @cite{d} are the four hexadecimal
1675 characters (using uppercase letters) of the wide character code. For
1676 example, ESC A345 is used to represent the wide character with code
1678 This scheme is compatible with use of the full Wide_Character set.
1680 @item @emph{Upper-Half Coding}
1682 @geindex Upper-Half Coding
1684 The wide character with encoding @cite{16#abcd#} where the upper bit is on
1685 (in other words, 'a' is in the range 8-F) is represented as two bytes,
1686 @cite{16#ab#} and @cite{16#cd#}. The second byte cannot be a format control
1687 character, but is not required to be in the upper half. This method can
1688 be also used for shift-JIS or EUC, where the internal coding matches the
1691 @item @emph{Shift JIS Coding}
1693 @geindex Shift JIS Coding
1695 A wide character is represented by a two-character sequence,
1697 @cite{16#cd#}, with the restrictions described for upper-half encoding as
1698 described above. The internal character code is the corresponding JIS
1699 character according to the standard algorithm for Shift-JIS
1700 conversion. Only characters defined in the JIS code set table can be
1701 used with this encoding method.
1703 @item @emph{EUC Coding}
1707 A wide character is represented by a two-character sequence
1709 @cite{16#cd#}, with both characters being in the upper half. The internal
1710 character code is the corresponding JIS character according to the EUC
1711 encoding algorithm. Only characters defined in the JIS code set table
1712 can be used with this encoding method.
1714 @item @emph{UTF-8 Coding}
1716 A wide character is represented using
1717 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1718 10646-1/Am.2. Depending on the character value, the representation
1719 is a one, two, or three byte sequence:
1722 16#0000#-16#007f#: 2#0`xxxxxxx`#
1723 16#0080#-16#07ff#: 2#110`xxxxx`# 2#10`xxxxxx`#
1724 16#0800#-16#ffff#: 2#1110`xxxx`# 2#10`xxxxxx`# 2#10`xxxxxx`#
1727 where the @cite{xxx} bits correspond to the left-padded bits of the
1728 16-bit character value. Note that all lower half ASCII characters
1729 are represented as ASCII bytes and all upper half characters and
1730 other wide characters are represented as sequences of upper-half
1731 (The full UTF-8 scheme allows for encoding 31-bit characters as
1732 6-byte sequences, and in the following section on wide wide
1733 characters, the use of these sequences is documented).
1735 @item @emph{Brackets Coding}
1737 In this encoding, a wide character is represented by the following eight
1744 where @cite{a}, @cite{b}, @cite{c}, @cite{d} are the four hexadecimal
1745 characters (using uppercase letters) of the wide character code. For
1746 example, ['A345'] is used to represent the wide character with code
1747 @cite{16#A345#}. It is also possible (though not required) to use the
1748 Brackets coding for upper half characters. For example, the code
1749 @cite{16#A3#} can be represented as @cite{['A3']}.
1751 This scheme is compatible with use of the full Wide_Character set,
1752 and is also the method used for wide character encoding in some standard
1753 ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
1758 Some of these coding schemes do not permit the full use of the
1759 Ada character set. For example, neither Shift JIS nor EUC allow the
1760 use of the upper half of the Latin-1 set.
1764 @node Wide_Wide_Character Encodings,,Wide_Character Encodings,Foreign Language Representation
1765 @anchor{gnat_ugn/the_gnat_compilation_model id7}@anchor{51}@anchor{gnat_ugn/the_gnat_compilation_model wide-wide-character-encodings}@anchor{52}
1766 @subsection Wide_Wide_Character Encodings
1769 GNAT allows wide wide character codes to appear in character and string
1770 literals, and also optionally in identifiers, by means of the following
1771 possible encoding schemes:
1776 @item @emph{UTF-8 Coding}
1778 A wide character is represented using
1779 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1780 10646-1/Am.2. Depending on the character value, the representation
1781 of character codes with values greater than 16#FFFF# is a
1782 is a four, five, or six byte sequence:
1785 16#01_0000#-16#10_FFFF#: 11110xxx 10xxxxxx 10xxxxxx
1787 16#0020_0000#-16#03FF_FFFF#: 111110xx 10xxxxxx 10xxxxxx
1789 16#0400_0000#-16#7FFF_FFFF#: 1111110x 10xxxxxx 10xxxxxx
1790 10xxxxxx 10xxxxxx 10xxxxxx
1793 where the @cite{xxx} bits correspond to the left-padded bits of the
1794 32-bit character value.
1796 @item @emph{Brackets Coding}
1798 In this encoding, a wide wide character is represented by the following ten or
1799 twelve byte character sequence:
1803 [ " a b c d e f g h " ]
1806 where @cite{a-h} are the six or eight hexadecimal
1807 characters (using uppercase letters) of the wide wide character code. For
1808 example, ["1F4567"] is used to represent the wide wide character with code
1809 @cite{16#001F_4567#}.
1811 This scheme is compatible with use of the full Wide_Wide_Character set,
1812 and is also the method used for wide wide character encoding in some standard
1813 ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
1816 @node File Naming Topics and Utilities,Configuration Pragmas,Foreign Language Representation,The GNAT Compilation Model
1817 @anchor{gnat_ugn/the_gnat_compilation_model id8}@anchor{53}@anchor{gnat_ugn/the_gnat_compilation_model file-naming-topics-and-utilities}@anchor{41}
1818 @section File Naming Topics and Utilities
1821 GNAT has a default file naming scheme and also provides the user with
1822 a high degree of control over how the names and extensions of the
1823 source files correspond to the Ada compilation units that they contain.
1826 * File Naming Rules::
1827 * Using Other File Names::
1828 * Alternative File Naming Schemes::
1829 * Handling Arbitrary File Naming Conventions with gnatname::
1830 * File Name Krunching with gnatkr::
1831 * Renaming Files with gnatchop::
1835 @node File Naming Rules,Using Other File Names,,File Naming Topics and Utilities
1836 @anchor{gnat_ugn/the_gnat_compilation_model file-naming-rules}@anchor{54}@anchor{gnat_ugn/the_gnat_compilation_model id9}@anchor{55}
1837 @subsection File Naming Rules
1840 The default file name is determined by the name of the unit that the
1841 file contains. The name is formed by taking the full expanded name of
1842 the unit and replacing the separating dots with hyphens and using
1843 lowercase for all letters.
1845 An exception arises if the file name generated by the above rules starts
1846 with one of the characters
1847 @cite{a}, @cite{g}, @cite{i}, or @cite{s}, and the second character is a
1848 minus. In this case, the character tilde is used in place
1849 of the minus. The reason for this special rule is to avoid clashes with
1850 the standard names for child units of the packages System, Ada,
1851 Interfaces, and GNAT, which use the prefixes
1852 @cite{s-}, @cite{a-}, @cite{i-}, and @cite{g-},
1855 The file extension is @code{.ads} for a spec and
1856 @code{.adb} for a body. The following table shows some
1857 examples of these rules.
1862 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
1869 Ada Compilation Unit
1889 @code{arith_functions.ads}
1893 Arith_Functions (package spec)
1897 @code{arith_functions.adb}
1901 Arith_Functions (package body)
1905 @code{func-spec.ads}
1909 Func.Spec (child package spec)
1913 @code{func-spec.adb}
1917 Func.Spec (child package body)
1925 Sub (subunit of Main)
1933 A.Bad (child package body)
1939 Following these rules can result in excessively long
1940 file names if corresponding
1941 unit names are long (for example, if child units or subunits are
1942 heavily nested). An option is available to shorten such long file names
1943 (called file name 'krunching'). This may be particularly useful when
1944 programs being developed with GNAT are to be used on operating systems
1945 with limited file name lengths. @ref{56,,Using gnatkr}.
1947 Of course, no file shortening algorithm can guarantee uniqueness over
1948 all possible unit names; if file name krunching is used, it is your
1949 responsibility to ensure no name clashes occur. Alternatively you
1950 can specify the exact file names that you want used, as described
1951 in the next section. Finally, if your Ada programs are migrating from a
1952 compiler with a different naming convention, you can use the gnatchop
1953 utility to produce source files that follow the GNAT naming conventions.
1954 (For details see @ref{38,,Renaming Files with gnatchop}.)
1956 Note: in the case of Windows or Mac OS operating systems, case is not
1957 significant. So for example on @cite{Windows} if the canonical name is
1958 @cite{main-sub.adb}, you can use the file name @code{Main-Sub.adb} instead.
1959 However, case is significant for other operating systems, so for example,
1960 if you want to use other than canonically cased file names on a Unix system,
1961 you need to follow the procedures described in the next section.
1963 @node Using Other File Names,Alternative File Naming Schemes,File Naming Rules,File Naming Topics and Utilities
1964 @anchor{gnat_ugn/the_gnat_compilation_model id10}@anchor{57}@anchor{gnat_ugn/the_gnat_compilation_model using-other-file-names}@anchor{37}
1965 @subsection Using Other File Names
1970 In the previous section, we have described the default rules used by
1971 GNAT to determine the file name in which a given unit resides. It is
1972 often convenient to follow these default rules, and if you follow them,
1973 the compiler knows without being explicitly told where to find all
1976 @geindex Source_File_Name pragma
1978 However, in some cases, particularly when a program is imported from
1979 another Ada compiler environment, it may be more convenient for the
1980 programmer to specify which file names contain which units. GNAT allows
1981 arbitrary file names to be used by means of the Source_File_Name pragma.
1982 The form of this pragma is as shown in the following examples:
1985 pragma Source_File_Name (My_Utilities.Stacks,
1986 Spec_File_Name => "myutilst_a.ada");
1987 pragma Source_File_name (My_Utilities.Stacks,
1988 Body_File_Name => "myutilst.ada");
1991 As shown in this example, the first argument for the pragma is the unit
1992 name (in this example a child unit). The second argument has the form
1993 of a named association. The identifier
1994 indicates whether the file name is for a spec or a body;
1995 the file name itself is given by a string literal.
1997 The source file name pragma is a configuration pragma, which means that
1998 normally it will be placed in the @code{gnat.adc}
1999 file used to hold configuration
2000 pragmas that apply to a complete compilation environment.
2001 For more details on how the @code{gnat.adc} file is created and used
2002 see @ref{58,,Handling of Configuration Pragmas}.
2006 GNAT allows completely arbitrary file names to be specified using the
2007 source file name pragma. However, if the file name specified has an
2008 extension other than @code{.ads} or @code{.adb} it is necessary to use
2009 a special syntax when compiling the file. The name in this case must be
2010 preceded by the special sequence @emph{-x} followed by a space and the name
2011 of the language, here @cite{ada}, as in:
2014 $ gcc -c -x ada peculiar_file_name.sim
2017 @cite{gnatmake} handles non-standard file names in the usual manner (the
2018 non-standard file name for the main program is simply used as the
2019 argument to gnatmake). Note that if the extension is also non-standard,
2020 then it must be included in the @cite{gnatmake} command, it may not
2023 @node Alternative File Naming Schemes,Handling Arbitrary File Naming Conventions with gnatname,Using Other File Names,File Naming Topics and Utilities
2024 @anchor{gnat_ugn/the_gnat_compilation_model id11}@anchor{59}@anchor{gnat_ugn/the_gnat_compilation_model alternative-file-naming-schemes}@anchor{5a}
2025 @subsection Alternative File Naming Schemes
2028 @geindex File naming schemes
2029 @geindex alternative
2033 The previous section described the use of the @cite{Source_File_Name}
2034 pragma to allow arbitrary names to be assigned to individual source files.
2035 However, this approach requires one pragma for each file, and especially in
2036 large systems can result in very long @code{gnat.adc} files, and also create
2037 a maintenance problem.
2039 @geindex Source_File_Name pragma
2041 GNAT also provides a facility for specifying systematic file naming schemes
2042 other than the standard default naming scheme previously described. An
2043 alternative scheme for naming is specified by the use of
2044 @cite{Source_File_Name} pragmas having the following format:
2047 pragma Source_File_Name (
2048 Spec_File_Name => FILE_NAME_PATTERN
2049 [ , Casing => CASING_SPEC]
2050 [ , Dot_Replacement => STRING_LITERAL ] );
2052 pragma Source_File_Name (
2053 Body_File_Name => FILE_NAME_PATTERN
2054 [ , Casing => CASING_SPEC ]
2055 [ , Dot_Replacement => STRING_LITERAL ] ) ;
2057 pragma Source_File_Name (
2058 Subunit_File_Name => FILE_NAME_PATTERN
2059 [ , Casing => CASING_SPEC ]
2060 [ , Dot_Replacement => STRING_LITERAL ] ) ;
2062 FILE_NAME_PATTERN ::= STRING_LITERAL
2063 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2066 The @cite{FILE_NAME_PATTERN} string shows how the file name is constructed.
2067 It contains a single asterisk character, and the unit name is substituted
2068 systematically for this asterisk. The optional parameter
2069 @cite{Casing} indicates
2070 whether the unit name is to be all upper-case letters, all lower-case letters,
2071 or mixed-case. If no
2072 @cite{Casing} parameter is used, then the default is all
2075 The optional @cite{Dot_Replacement} string is used to replace any periods
2076 that occur in subunit or child unit names. If no @cite{Dot_Replacement}
2077 argument is used then separating dots appear unchanged in the resulting
2079 Although the above syntax indicates that the
2080 @cite{Casing} argument must appear
2081 before the @cite{Dot_Replacement} argument, but it
2082 is also permissible to write these arguments in the opposite order.
2084 As indicated, it is possible to specify different naming schemes for
2085 bodies, specs, and subunits. Quite often the rule for subunits is the
2086 same as the rule for bodies, in which case, there is no need to give
2087 a separate @cite{Subunit_File_Name} rule, and in this case the
2088 @cite{Body_File_name} rule is used for subunits as well.
2090 The separate rule for subunits can also be used to implement the rather
2091 unusual case of a compilation environment (e.g., a single directory) which
2092 contains a subunit and a child unit with the same unit name. Although
2093 both units cannot appear in the same partition, the Ada Reference Manual
2094 allows (but does not require) the possibility of the two units coexisting
2095 in the same environment.
2097 The file name translation works in the following steps:
2103 If there is a specific @cite{Source_File_Name} pragma for the given unit,
2104 then this is always used, and any general pattern rules are ignored.
2107 If there is a pattern type @cite{Source_File_Name} pragma that applies to
2108 the unit, then the resulting file name will be used if the file exists. If
2109 more than one pattern matches, the latest one will be tried first, and the
2110 first attempt resulting in a reference to a file that exists will be used.
2113 If no pattern type @cite{Source_File_Name} pragma that applies to the unit
2114 for which the corresponding file exists, then the standard GNAT default
2115 naming rules are used.
2118 As an example of the use of this mechanism, consider a commonly used scheme
2119 in which file names are all lower case, with separating periods copied
2120 unchanged to the resulting file name, and specs end with @code{.1.ada}, and
2121 bodies end with @code{.2.ada}. GNAT will follow this scheme if the following
2125 pragma Source_File_Name
2126 (Spec_File_Name => ".1.ada");
2127 pragma Source_File_Name
2128 (Body_File_Name => ".2.ada");
2131 The default GNAT scheme is actually implemented by providing the following
2132 default pragmas internally:
2135 pragma Source_File_Name
2136 (Spec_File_Name => ".ads", Dot_Replacement => "-");
2137 pragma Source_File_Name
2138 (Body_File_Name => ".adb", Dot_Replacement => "-");
2141 Our final example implements a scheme typically used with one of the
2142 Ada 83 compilers, where the separator character for subunits was '__'
2143 (two underscores), specs were identified by adding @code{_.ADA}, bodies
2144 by adding @code{.ADA}, and subunits by
2145 adding @code{.SEP}. All file names were
2146 upper case. Child units were not present of course since this was an
2147 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2148 the same double underscore separator for child units.
2151 pragma Source_File_Name
2152 (Spec_File_Name => "_.ADA",
2153 Dot_Replacement => "__",
2154 Casing = Uppercase);
2155 pragma Source_File_Name
2156 (Body_File_Name => ".ADA",
2157 Dot_Replacement => "__",
2158 Casing = Uppercase);
2159 pragma Source_File_Name
2160 (Subunit_File_Name => ".SEP",
2161 Dot_Replacement => "__",
2162 Casing = Uppercase);
2167 @node Handling Arbitrary File Naming Conventions with gnatname,File Name Krunching with gnatkr,Alternative File Naming Schemes,File Naming Topics and Utilities
2168 @anchor{gnat_ugn/the_gnat_compilation_model handling-arbitrary-file-naming-conventions-with-gnatname}@anchor{5b}@anchor{gnat_ugn/the_gnat_compilation_model id12}@anchor{5c}
2169 @subsection Handling Arbitrary File Naming Conventions with @cite{gnatname}
2172 @geindex File Naming Conventions
2175 * Arbitrary File Naming Conventions::
2176 * Running gnatname::
2177 * Switches for gnatname::
2178 * Examples of gnatname Usage::
2182 @node Arbitrary File Naming Conventions,Running gnatname,,Handling Arbitrary File Naming Conventions with gnatname
2183 @anchor{gnat_ugn/the_gnat_compilation_model arbitrary-file-naming-conventions}@anchor{5d}@anchor{gnat_ugn/the_gnat_compilation_model id13}@anchor{5e}
2184 @subsubsection Arbitrary File Naming Conventions
2187 The GNAT compiler must be able to know the source file name of a compilation
2188 unit. When using the standard GNAT default file naming conventions
2189 (@cite{.ads} for specs, @cite{.adb} for bodies), the GNAT compiler
2190 does not need additional information.
2192 When the source file names do not follow the standard GNAT default file naming
2193 conventions, the GNAT compiler must be given additional information through
2194 a configuration pragmas file (@ref{16,,Configuration Pragmas})
2196 When the non-standard file naming conventions are well-defined,
2197 a small number of pragmas @cite{Source_File_Name} specifying a naming pattern
2198 (@ref{5a,,Alternative File Naming Schemes}) may be sufficient. However,
2199 if the file naming conventions are irregular or arbitrary, a number
2200 of pragma @cite{Source_File_Name} for individual compilation units
2202 To help maintain the correspondence between compilation unit names and
2203 source file names within the compiler,
2204 GNAT provides a tool @cite{gnatname} to generate the required pragmas for a
2207 @node Running gnatname,Switches for gnatname,Arbitrary File Naming Conventions,Handling Arbitrary File Naming Conventions with gnatname
2208 @anchor{gnat_ugn/the_gnat_compilation_model running-gnatname}@anchor{5f}@anchor{gnat_ugn/the_gnat_compilation_model id14}@anchor{60}
2209 @subsubsection Running @cite{gnatname}
2212 The usual form of the @cite{gnatname} command is:
2215 $ gnatname [`switches`] `naming_pattern` [`naming_patterns`]
2216 [--and [`switches`] `naming_pattern` [`naming_patterns`]]
2219 All of the arguments are optional. If invoked without any argument,
2220 @cite{gnatname} will display its usage.
2222 When used with at least one naming pattern, @cite{gnatname} will attempt to
2223 find all the compilation units in files that follow at least one of the
2224 naming patterns. To find these compilation units,
2225 @cite{gnatname} will use the GNAT compiler in syntax-check-only mode on all
2228 One or several Naming Patterns may be given as arguments to @cite{gnatname}.
2229 Each Naming Pattern is enclosed between double quotes (or single
2231 A Naming Pattern is a regular expression similar to the wildcard patterns
2232 used in file names by the Unix shells or the DOS prompt.
2234 @cite{gnatname} may be called with several sections of directories/patterns.
2235 Sections are separated by switch @cite{--and}. In each section, there must be
2236 at least one pattern. If no directory is specified in a section, the current
2237 directory (or the project directory is @cite{-P} is used) is implied.
2238 The options other that the directory switches and the patterns apply globally
2239 even if they are in different sections.
2241 Examples of Naming Patterns are:
2249 For a more complete description of the syntax of Naming Patterns,
2250 see the second kind of regular expressions described in @code{g-regexp.ads}
2251 (the 'Glob' regular expressions).
2253 When invoked with no switch @cite{-P}, @cite{gnatname} will create a
2254 configuration pragmas file @code{gnat.adc} in the current working directory,
2255 with pragmas @cite{Source_File_Name} for each file that contains a valid Ada
2258 @node Switches for gnatname,Examples of gnatname Usage,Running gnatname,Handling Arbitrary File Naming Conventions with gnatname
2259 @anchor{gnat_ugn/the_gnat_compilation_model id15}@anchor{61}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatname}@anchor{62}
2260 @subsubsection Switches for @cite{gnatname}
2263 Switches for @cite{gnatname} must precede any specified Naming Pattern.
2265 You may specify any of the following switches to @cite{gnatname}:
2267 @geindex --version (gnatname)
2272 @item @code{--version}
2274 Display Copyright and version, then exit disregarding all other options.
2277 @geindex --help (gnatname)
2284 If @emph{--version} was not used, display usage, then exit disregarding
2287 @item @code{--subdirs=@emph{dir}}
2289 Real object, library or exec directories are subdirectories <dir> of the
2292 @item @code{--no-backup}
2294 Do not create a backup copy of an existing project file.
2298 Start another section of directories/patterns.
2301 @geindex -c (gnatname)
2306 @item @code{-c@emph{filename}}
2308 Create a configuration pragmas file @code{filename} (instead of the default
2310 There may be zero, one or more space between @emph{-c} and
2312 @code{filename} may include directory information. @code{filename} must be
2313 writable. There may be only one switch @emph{-c}.
2314 When a switch @emph{-c} is
2315 specified, no switch @emph{-P} may be specified (see below).
2318 @geindex -d (gnatname)
2323 @item @code{-d@emph{dir}}
2325 Look for source files in directory @code{dir}. There may be zero, one or more
2326 spaces between @emph{-d} and @code{dir}.
2327 @code{dir} may end with @cite{/**}, that is it may be of the form
2328 @cite{root_dir/**}. In this case, the directory @cite{root_dir} and all of its
2329 subdirectories, recursively, have to be searched for sources.
2330 When a switch @emph{-d}
2331 is specified, the current working directory will not be searched for source
2332 files, unless it is explicitly specified with a @emph{-d}
2333 or @emph{-D} switch.
2334 Several switches @emph{-d} may be specified.
2335 If @code{dir} is a relative path, it is relative to the directory of
2336 the configuration pragmas file specified with switch
2338 or to the directory of the project file specified with switch
2340 if neither switch @emph{-c}
2341 nor switch @emph{-P} are specified, it is relative to the
2342 current working directory. The directory
2343 specified with switch @emph{-d} must exist and be readable.
2346 @geindex -D (gnatname)
2351 @item @code{-D@emph{filename}}
2353 Look for source files in all directories listed in text file @code{filename}.
2354 There may be zero, one or more spaces between @emph{-D}
2355 and @code{filename}.
2356 @code{filename} must be an existing, readable text file.
2357 Each nonempty line in @code{filename} must be a directory.
2358 Specifying switch @emph{-D} is equivalent to specifying as many
2359 switches @emph{-d} as there are nonempty lines in
2364 Follow symbolic links when processing project files.
2366 @geindex -f (gnatname)
2368 @item @code{-f@emph{pattern}}
2370 Foreign patterns. Using this switch, it is possible to add sources of languages
2371 other than Ada to the list of sources of a project file.
2372 It is only useful if a -P switch is used.
2376 gnatname -Pprj -f"*.c" "*.ada"
2379 will look for Ada units in all files with the @code{.ada} extension,
2380 and will add to the list of file for project @code{prj.gpr} the C files
2381 with extension @code{.c}.
2383 @geindex -h (gnatname)
2387 Output usage (help) information. The output is written to @code{stdout}.
2389 @geindex -P (gnatname)
2391 @item @code{-P@emph{proj}}
2393 Create or update project file @code{proj}. There may be zero, one or more space
2394 between @emph{-P} and @code{proj}. @code{proj} may include directory
2395 information. @code{proj} must be writable.
2396 There may be only one switch @emph{-P}.
2397 When a switch @emph{-P} is specified,
2398 no switch @emph{-c} may be specified.
2399 On all platforms, except on VMS, when @cite{gnatname} is invoked for an
2400 existing project file <proj>.gpr, a backup copy of the project file is created
2401 in the project directory with file name <proj>.gpr.saved_x. 'x' is the first
2402 non negative number that makes this backup copy a new file.
2404 @geindex -v (gnatname)
2408 Verbose mode. Output detailed explanation of behavior to @code{stdout}.
2409 This includes name of the file written, the name of the directories to search
2410 and, for each file in those directories whose name matches at least one of
2411 the Naming Patterns, an indication of whether the file contains a unit,
2412 and if so the name of the unit.
2415 @geindex -v -v (gnatname)
2422 Very Verbose mode. In addition to the output produced in verbose mode,
2423 for each file in the searched directories whose name matches none of
2424 the Naming Patterns, an indication is given that there is no match.
2426 @geindex -x (gnatname)
2428 @item @code{-x@emph{pattern}}
2430 Excluded patterns. Using this switch, it is possible to exclude some files
2431 that would match the name patterns. For example,
2434 gnatname -x "*_nt.ada" "*.ada"
2437 will look for Ada units in all files with the @code{.ada} extension,
2438 except those whose names end with @code{_nt.ada}.
2441 @node Examples of gnatname Usage,,Switches for gnatname,Handling Arbitrary File Naming Conventions with gnatname
2442 @anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatname-usage}@anchor{63}@anchor{gnat_ugn/the_gnat_compilation_model id16}@anchor{64}
2443 @subsubsection Examples of @cite{gnatname} Usage
2447 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
2450 In this example, the directory @code{/home/me} must already exist
2451 and be writable. In addition, the directory
2452 @code{/home/me/sources} (specified by
2453 @emph{-d sources}) must exist and be readable.
2455 Note the optional spaces after @emph{-c} and @emph{-d}.
2458 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
2459 -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
2462 Note that several switches @emph{-d} may be used,
2463 even in conjunction with one or several switches
2464 @emph{-D}. Several Naming Patterns and one excluded pattern
2465 are used in this example.
2467 @node File Name Krunching with gnatkr,Renaming Files with gnatchop,Handling Arbitrary File Naming Conventions with gnatname,File Naming Topics and Utilities
2468 @anchor{gnat_ugn/the_gnat_compilation_model file-name-krunching-with-gnatkr}@anchor{65}@anchor{gnat_ugn/the_gnat_compilation_model id17}@anchor{66}
2469 @subsection File Name Krunching with @cite{gnatkr}
2474 This chapter discusses the method used by the compiler to shorten
2475 the default file names chosen for Ada units so that they do not
2476 exceed the maximum length permitted. It also describes the
2477 @cite{gnatkr} utility that can be used to determine the result of
2478 applying this shortening.
2483 * Krunching Method::
2484 * Examples of gnatkr Usage::
2488 @node About gnatkr,Using gnatkr,,File Name Krunching with gnatkr
2489 @anchor{gnat_ugn/the_gnat_compilation_model id18}@anchor{67}@anchor{gnat_ugn/the_gnat_compilation_model about-gnatkr}@anchor{68}
2490 @subsubsection About @cite{gnatkr}
2493 The default file naming rule in GNAT
2494 is that the file name must be derived from
2495 the unit name. The exact default rule is as follows:
2501 Take the unit name and replace all dots by hyphens.
2504 If such a replacement occurs in the
2505 second character position of a name, and the first character is
2506 @code{a}, @code{g}, @code{s}, or @code{i},
2507 then replace the dot by the character
2511 The reason for this exception is to avoid clashes
2512 with the standard names for children of System, Ada, Interfaces,
2513 and GNAT, which use the prefixes
2514 @code{s-}, @code{a-}, @code{i-}, and @code{g-},
2518 The @code{-gnatk@emph{nn}}
2519 switch of the compiler activates a 'krunching'
2520 circuit that limits file names to nn characters (where nn is a decimal
2523 The @cite{gnatkr} utility can be used to determine the krunched name for
2524 a given file, when krunched to a specified maximum length.
2526 @node Using gnatkr,Krunching Method,About gnatkr,File Name Krunching with gnatkr
2527 @anchor{gnat_ugn/the_gnat_compilation_model id19}@anchor{69}@anchor{gnat_ugn/the_gnat_compilation_model using-gnatkr}@anchor{56}
2528 @subsubsection Using @cite{gnatkr}
2531 The @cite{gnatkr} command has the form:
2534 $ gnatkr `name` [`length`]
2537 @cite{name} is the uncrunched file name, derived from the name of the unit
2538 in the standard manner described in the previous section (i.e., in particular
2539 all dots are replaced by hyphens). The file name may or may not have an
2540 extension (defined as a suffix of the form period followed by arbitrary
2541 characters other than period). If an extension is present then it will
2542 be preserved in the output. For example, when krunching @code{hellofile.ads}
2543 to eight characters, the result will be hellofil.ads.
2545 Note: for compatibility with previous versions of @cite{gnatkr} dots may
2546 appear in the name instead of hyphens, but the last dot will always be
2547 taken as the start of an extension. So if @cite{gnatkr} is given an argument
2548 such as @code{Hello.World.adb} it will be treated exactly as if the first
2549 period had been a hyphen, and for example krunching to eight characters
2550 gives the result @code{hellworl.adb}.
2552 Note that the result is always all lower case.
2553 Characters of the other case are folded as required.
2555 @cite{length} represents the length of the krunched name. The default
2556 when no argument is given is 8 characters. A length of zero stands for
2557 unlimited, in other words do not chop except for system files where the
2558 implied crunching length is always eight characters.
2560 The output is the krunched name. The output has an extension only if the
2561 original argument was a file name with an extension.
2563 @node Krunching Method,Examples of gnatkr Usage,Using gnatkr,File Name Krunching with gnatkr
2564 @anchor{gnat_ugn/the_gnat_compilation_model id20}@anchor{6a}@anchor{gnat_ugn/the_gnat_compilation_model krunching-method}@anchor{6b}
2565 @subsubsection Krunching Method
2568 The initial file name is determined by the name of the unit that the file
2569 contains. The name is formed by taking the full expanded name of the
2570 unit and replacing the separating dots with hyphens and
2572 for all letters, except that a hyphen in the second character position is
2573 replaced by a tilde if the first character is
2574 @code{a}, @code{i}, @code{g}, or @code{s}.
2575 The extension is @cite{.ads} for a
2576 spec and @cite{.adb} for a body.
2577 Krunching does not affect the extension, but the file name is shortened to
2578 the specified length by following these rules:
2584 The name is divided into segments separated by hyphens, tildes or
2585 underscores and all hyphens, tildes, and underscores are
2586 eliminated. If this leaves the name short enough, we are done.
2589 If the name is too long, the longest segment is located (left-most
2590 if there are two of equal length), and shortened by dropping
2591 its last character. This is repeated until the name is short enough.
2593 As an example, consider the krunching of @code{our-strings-wide_fixed.adb}
2594 to fit the name into 8 characters as required by some operating systems:
2597 our-strings-wide_fixed 22
2598 our strings wide fixed 19
2599 our string wide fixed 18
2600 our strin wide fixed 17
2601 our stri wide fixed 16
2602 our stri wide fixe 15
2603 our str wide fixe 14
2610 Final file name: oustwifi.adb
2614 The file names for all predefined units are always krunched to eight
2615 characters. The krunching of these predefined units uses the following
2616 special prefix replacements:
2619 @multitable {xxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx}
2663 These system files have a hyphen in the second character position. That
2664 is why normal user files replace such a character with a
2665 tilde, to avoid confusion with system file names.
2667 As an example of this special rule, consider
2668 @code{ada-strings-wide_fixed.adb}, which gets krunched as follows:
2671 ada-strings-wide_fixed 22
2672 a- strings wide fixed 18
2673 a- string wide fixed 17
2674 a- strin wide fixed 16
2675 a- stri wide fixed 15
2676 a- stri wide fixe 14
2683 Final file name: a-stwifi.adb
2687 Of course no file shortening algorithm can guarantee uniqueness over all
2688 possible unit names, and if file name krunching is used then it is your
2689 responsibility to ensure that no name clashes occur. The utility
2690 program @cite{gnatkr} is supplied for conveniently determining the
2691 krunched name of a file.
2693 @node Examples of gnatkr Usage,,Krunching Method,File Name Krunching with gnatkr
2694 @anchor{gnat_ugn/the_gnat_compilation_model id21}@anchor{6c}@anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatkr-usage}@anchor{6d}
2695 @subsubsection Examples of @cite{gnatkr} Usage
2699 $ gnatkr very_long_unit_name.ads --> velounna.ads
2700 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
2701 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
2702 $ gnatkr grandparent-parent-child --> grparchi
2703 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
2704 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
2707 @node Renaming Files with gnatchop,,File Name Krunching with gnatkr,File Naming Topics and Utilities
2708 @anchor{gnat_ugn/the_gnat_compilation_model id22}@anchor{6e}@anchor{gnat_ugn/the_gnat_compilation_model renaming-files-with-gnatchop}@anchor{38}
2709 @subsection Renaming Files with @cite{gnatchop}
2714 This chapter discusses how to handle files with multiple units by using
2715 the @cite{gnatchop} utility. This utility is also useful in renaming
2716 files to meet the standard GNAT default file naming conventions.
2719 * Handling Files with Multiple Units::
2720 * Operating gnatchop in Compilation Mode::
2721 * Command Line for gnatchop::
2722 * Switches for gnatchop::
2723 * Examples of gnatchop Usage::
2727 @node Handling Files with Multiple Units,Operating gnatchop in Compilation Mode,,Renaming Files with gnatchop
2728 @anchor{gnat_ugn/the_gnat_compilation_model id23}@anchor{6f}@anchor{gnat_ugn/the_gnat_compilation_model handling-files-with-multiple-units}@anchor{70}
2729 @subsubsection Handling Files with Multiple Units
2732 The basic compilation model of GNAT requires that a file submitted to the
2733 compiler have only one unit and there be a strict correspondence
2734 between the file name and the unit name.
2736 The @cite{gnatchop} utility allows both of these rules to be relaxed,
2737 allowing GNAT to process files which contain multiple compilation units
2738 and files with arbitrary file names. @cite{gnatchop}
2739 reads the specified file and generates one or more output files,
2740 containing one unit per file. The unit and the file name correspond,
2741 as required by GNAT.
2743 If you want to permanently restructure a set of 'foreign' files so that
2744 they match the GNAT rules, and do the remaining development using the
2745 GNAT structure, you can simply use @emph{gnatchop} once, generate the
2746 new set of files and work with them from that point on.
2748 Alternatively, if you want to keep your files in the 'foreign' format,
2749 perhaps to maintain compatibility with some other Ada compilation
2750 system, you can set up a procedure where you use @emph{gnatchop} each
2751 time you compile, regarding the source files that it writes as temporary
2752 files that you throw away.
2754 Note that if your file containing multiple units starts with a byte order
2755 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
2756 will each start with a copy of this BOM, meaning that they can be compiled
2757 automatically in UTF-8 mode without needing to specify an explicit encoding.
2759 @node Operating gnatchop in Compilation Mode,Command Line for gnatchop,Handling Files with Multiple Units,Renaming Files with gnatchop
2760 @anchor{gnat_ugn/the_gnat_compilation_model operating-gnatchop-in-compilation-mode}@anchor{71}@anchor{gnat_ugn/the_gnat_compilation_model id24}@anchor{72}
2761 @subsubsection Operating gnatchop in Compilation Mode
2764 The basic function of @cite{gnatchop} is to take a file with multiple units
2765 and split it into separate files. The boundary between files is reasonably
2766 clear, except for the issue of comments and pragmas. In default mode, the
2767 rule is that any pragmas between units belong to the previous unit, except
2768 that configuration pragmas always belong to the following unit. Any comments
2769 belong to the following unit. These rules
2770 almost always result in the right choice of
2771 the split point without needing to mark it explicitly and most users will
2772 find this default to be what they want. In this default mode it is incorrect to
2773 submit a file containing only configuration pragmas, or one that ends in
2774 configuration pragmas, to @cite{gnatchop}.
2776 However, using a special option to activate 'compilation mode',
2778 can perform another function, which is to provide exactly the semantics
2779 required by the RM for handling of configuration pragmas in a compilation.
2780 In the absence of configuration pragmas (at the main file level), this
2781 option has no effect, but it causes such configuration pragmas to be handled
2782 in a quite different manner.
2784 First, in compilation mode, if @cite{gnatchop} is given a file that consists of
2785 only configuration pragmas, then this file is appended to the
2786 @code{gnat.adc} file in the current directory. This behavior provides
2787 the required behavior described in the RM for the actions to be taken
2788 on submitting such a file to the compiler, namely that these pragmas
2789 should apply to all subsequent compilations in the same compilation
2790 environment. Using GNAT, the current directory, possibly containing a
2791 @code{gnat.adc} file is the representation
2792 of a compilation environment. For more information on the
2793 @code{gnat.adc} file, see @ref{58,,Handling of Configuration Pragmas}.
2795 Second, in compilation mode, if @cite{gnatchop}
2796 is given a file that starts with
2797 configuration pragmas, and contains one or more units, then these
2798 configuration pragmas are prepended to each of the chopped files. This
2799 behavior provides the required behavior described in the RM for the
2800 actions to be taken on compiling such a file, namely that the pragmas
2801 apply to all units in the compilation, but not to subsequently compiled
2804 Finally, if configuration pragmas appear between units, they are appended
2805 to the previous unit. This results in the previous unit being illegal,
2806 since the compiler does not accept configuration pragmas that follow
2807 a unit. This provides the required RM behavior that forbids configuration
2808 pragmas other than those preceding the first compilation unit of a
2811 For most purposes, @cite{gnatchop} will be used in default mode. The
2812 compilation mode described above is used only if you need exactly
2813 accurate behavior with respect to compilations, and you have files
2814 that contain multiple units and configuration pragmas. In this
2815 circumstance the use of @cite{gnatchop} with the compilation mode
2816 switch provides the required behavior, and is for example the mode
2817 in which GNAT processes the ACVC tests.
2819 @node Command Line for gnatchop,Switches for gnatchop,Operating gnatchop in Compilation Mode,Renaming Files with gnatchop
2820 @anchor{gnat_ugn/the_gnat_compilation_model id25}@anchor{73}@anchor{gnat_ugn/the_gnat_compilation_model command-line-for-gnatchop}@anchor{74}
2821 @subsubsection Command Line for @cite{gnatchop}
2824 The @cite{gnatchop} command has the form:
2827 $ gnatchop switches file_name [file_name ...]
2831 The only required argument is the file name of the file to be chopped.
2832 There are no restrictions on the form of this file name. The file itself
2833 contains one or more Ada units, in normal GNAT format, concatenated
2834 together. As shown, more than one file may be presented to be chopped.
2836 When run in default mode, @cite{gnatchop} generates one output file in
2837 the current directory for each unit in each of the files.
2839 @cite{directory}, if specified, gives the name of the directory to which
2840 the output files will be written. If it is not specified, all files are
2841 written to the current directory.
2843 For example, given a
2844 file called @code{hellofiles} containing
2849 with Ada.Text_IO; use Ada.Text_IO;
2859 $ gnatchop hellofiles
2862 generates two files in the current directory, one called
2863 @code{hello.ads} containing the single line that is the procedure spec,
2864 and the other called @code{hello.adb} containing the remaining text. The
2865 original file is not affected. The generated files can be compiled in
2868 When gnatchop is invoked on a file that is empty or that contains only empty
2869 lines and/or comments, gnatchop will not fail, but will not produce any
2872 For example, given a
2873 file called @code{toto.txt} containing
2885 will not produce any new file and will result in the following warnings:
2888 toto.txt:1:01: warning: empty file, contains no compilation units
2889 no compilation units found
2890 no source files written
2893 @node Switches for gnatchop,Examples of gnatchop Usage,Command Line for gnatchop,Renaming Files with gnatchop
2894 @anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatchop}@anchor{75}@anchor{gnat_ugn/the_gnat_compilation_model id26}@anchor{76}
2895 @subsubsection Switches for @cite{gnatchop}
2898 @emph{gnatchop} recognizes the following switches:
2900 @geindex --version (gnatchop)
2905 @item @code{--version}
2907 Display Copyright and version, then exit disregarding all other options.
2910 @geindex --help (gnatchop)
2917 If @emph{--version} was not used, display usage, then exit disregarding
2921 @geindex -c (gnatchop)
2928 Causes @cite{gnatchop} to operate in compilation mode, in which
2929 configuration pragmas are handled according to strict RM rules. See
2930 previous section for a full description of this mode.
2932 @item @code{-gnat@emph{xxx}}
2934 This passes the given @emph{-gnat`xxx*` switch to `gnat` which is
2935 used to parse the given file. Not all `xxx` options make sense,
2936 but for example, the use of *-gnati2} allows @cite{gnatchop} to
2937 process a source file that uses Latin-2 coding for identifiers.
2941 Causes @cite{gnatchop} to generate a brief help summary to the standard
2942 output file showing usage information.
2945 @geindex -k (gnatchop)
2950 @item @code{-k@emph{mm}}
2952 Limit generated file names to the specified number @cite{mm}
2954 This is useful if the
2955 resulting set of files is required to be interoperable with systems
2956 which limit the length of file names.
2957 No space is allowed between the @emph{-k} and the numeric value. The numeric
2958 value may be omitted in which case a default of @emph{-k8},
2960 with DOS-like file systems, is used. If no @emph{-k} switch
2962 there is no limit on the length of file names.
2965 @geindex -p (gnatchop)
2972 Causes the file modification time stamp of the input file to be
2973 preserved and used for the time stamp of the output file(s). This may be
2974 useful for preserving coherency of time stamps in an environment where
2975 @cite{gnatchop} is used as part of a standard build process.
2978 @geindex -q (gnatchop)
2985 Causes output of informational messages indicating the set of generated
2986 files to be suppressed. Warnings and error messages are unaffected.
2989 @geindex -r (gnatchop)
2991 @geindex Source_Reference pragmas
2998 Generate @cite{Source_Reference} pragmas. Use this switch if the output
2999 files are regarded as temporary and development is to be done in terms
3000 of the original unchopped file. This switch causes
3001 @cite{Source_Reference} pragmas to be inserted into each of the
3002 generated files to refers back to the original file name and line number.
3003 The result is that all error messages refer back to the original
3005 In addition, the debugging information placed into the object file (when
3006 the @emph{-g} switch of @emph{gcc} or @emph{gnatmake} is
3008 also refers back to this original file so that tools like profilers and
3009 debuggers will give information in terms of the original unchopped file.
3011 If the original file to be chopped itself contains
3012 a @cite{Source_Reference}
3013 pragma referencing a third file, then gnatchop respects
3014 this pragma, and the generated @cite{Source_Reference} pragmas
3015 in the chopped file refer to the original file, with appropriate
3016 line numbers. This is particularly useful when @cite{gnatchop}
3017 is used in conjunction with @cite{gnatprep} to compile files that
3018 contain preprocessing statements and multiple units.
3021 @geindex -v (gnatchop)
3028 Causes @cite{gnatchop} to operate in verbose mode. The version
3029 number and copyright notice are output, as well as exact copies of
3030 the gnat1 commands spawned to obtain the chop control information.
3033 @geindex -w (gnatchop)
3040 Overwrite existing file names. Normally @cite{gnatchop} regards it as a
3041 fatal error if there is already a file with the same name as a
3042 file it would otherwise output, in other words if the files to be
3043 chopped contain duplicated units. This switch bypasses this
3044 check, and causes all but the last instance of such duplicated
3045 units to be skipped.
3048 @geindex --GCC= (gnatchop)
3053 @item @code{--GCC=@emph{xxxx}}
3055 Specify the path of the GNAT parser to be used. When this switch is used,
3056 no attempt is made to add the prefix to the GNAT parser executable.
3059 @node Examples of gnatchop Usage,,Switches for gnatchop,Renaming Files with gnatchop
3060 @anchor{gnat_ugn/the_gnat_compilation_model id27}@anchor{77}@anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatchop-usage}@anchor{78}
3061 @subsubsection Examples of @cite{gnatchop} Usage
3065 $ gnatchop -w hello_s.ada prerelease/files
3068 Chops the source file @code{hello_s.ada}. The output files will be
3069 placed in the directory @code{prerelease/files},
3071 files with matching names in that directory (no files in the current
3072 directory are modified).
3078 Chops the source file @code{archive}
3079 into the current directory. One
3080 useful application of @cite{gnatchop} is in sending sets of sources
3081 around, for example in email messages. The required sources are simply
3082 concatenated (for example, using a Unix @cite{cat}
3084 @emph{gnatchop} is used at the other end to reconstitute the original
3088 $ gnatchop file1 file2 file3 direc
3091 Chops all units in files @code{file1}, @code{file2}, @code{file3}, placing
3092 the resulting files in the directory @code{direc}. Note that if any units
3093 occur more than once anywhere within this set of files, an error message
3094 is generated, and no files are written. To override this check, use the
3096 in which case the last occurrence in the last file will
3097 be the one that is output, and earlier duplicate occurrences for a given
3098 unit will be skipped.
3100 @node Configuration Pragmas,Generating Object Files,File Naming Topics and Utilities,The GNAT Compilation Model
3101 @anchor{gnat_ugn/the_gnat_compilation_model id28}@anchor{79}@anchor{gnat_ugn/the_gnat_compilation_model configuration-pragmas}@anchor{16}
3102 @section Configuration Pragmas
3105 @geindex Configuration pragmas
3108 @geindex configuration
3110 Configuration pragmas include those pragmas described as
3111 such in the Ada Reference Manual, as well as
3112 implementation-dependent pragmas that are configuration pragmas.
3113 See the @cite{Implementation_Defined_Pragmas} chapter in the
3114 @cite{GNAT_Reference_Manual} for details on these
3115 additional GNAT-specific configuration pragmas.
3116 Most notably, the pragma @cite{Source_File_Name}, which allows
3117 specifying non-default names for source files, is a configuration
3118 pragma. The following is a complete list of configuration pragmas
3128 Allow_Integer_Address
3131 Assume_No_Invalid_Values
3136 Compile_Time_Warning
3139 Convention_Identifier
3142 Default_Storage_Pool
3148 External_Name_Casing
3151 Float_Representation
3164 Priority_Specific_Dispatching
3167 Propagate_Exceptions
3172 Restrictions_Warnings
3174 Short_Circuit_And_Or
3176 Source_File_Name_Project
3180 Suppress_Exception_Locations
3181 Task_Dispatching_Policy
3187 Wide_Character_Encoding
3191 * Handling of Configuration Pragmas::
3192 * The Configuration Pragmas Files::
3196 @node Handling of Configuration Pragmas,The Configuration Pragmas Files,,Configuration Pragmas
3197 @anchor{gnat_ugn/the_gnat_compilation_model id29}@anchor{7a}@anchor{gnat_ugn/the_gnat_compilation_model handling-of-configuration-pragmas}@anchor{58}
3198 @subsection Handling of Configuration Pragmas
3201 Configuration pragmas may either appear at the start of a compilation
3202 unit, or they can appear in a configuration pragma file to apply to
3203 all compilations performed in a given compilation environment.
3205 GNAT also provides the @cite{gnatchop} utility to provide an automatic
3206 way to handle configuration pragmas following the semantics for
3207 compilations (that is, files with multiple units), described in the RM.
3208 See @ref{71,,Operating gnatchop in Compilation Mode} for details.
3209 However, for most purposes, it will be more convenient to edit the
3210 @code{gnat.adc} file that contains configuration pragmas directly,
3211 as described in the following section.
3213 In the case of @cite{Restrictions} pragmas appearing as configuration
3214 pragmas in individual compilation units, the exact handling depends on
3215 the type of restriction.
3217 Restrictions that require partition-wide consistency (like
3218 @cite{No_Tasking}) are
3219 recognized wherever they appear
3220 and can be freely inherited, e.g. from a @emph{with}ed unit to the @emph{with}ing
3221 unit. This makes sense since the binder will in any case insist on seeing
3222 consistent use, so any unit not conforming to any restrictions that are
3223 anywhere in the partition will be rejected, and you might as well find
3224 that out at compile time rather than at bind time.
3226 For restrictions that do not require partition-wide consistency, e.g.
3227 SPARK or No_Implementation_Attributes, in general the restriction applies
3228 only to the unit in which the pragma appears, and not to any other units.
3230 The exception is No_Elaboration_Code which always applies to the entire
3231 object file from a compilation, i.e. to the body, spec, and all subunits.
3232 This restriction can be specified in a configuration pragma file, or it
3233 can be on the body and/or the spec (in eithe case it applies to all the
3234 relevant units). It can appear on a subunit only if it has previously
3235 appeared in the body of spec.
3237 @node The Configuration Pragmas Files,,Handling of Configuration Pragmas,Configuration Pragmas
3238 @anchor{gnat_ugn/the_gnat_compilation_model the-configuration-pragmas-files}@anchor{7b}@anchor{gnat_ugn/the_gnat_compilation_model id30}@anchor{7c}
3239 @subsection The Configuration Pragmas Files
3244 In GNAT a compilation environment is defined by the current
3245 directory at the time that a compile command is given. This current
3246 directory is searched for a file whose name is @code{gnat.adc}. If
3247 this file is present, it is expected to contain one or more
3248 configuration pragmas that will be applied to the current compilation.
3249 However, if the switch @emph{-gnatA} is used, @code{gnat.adc} is not
3250 considered. When taken into account, @code{gnat.adc} is added to the
3251 dependencies, so that if @code{gnat.adc} is modified later, an invocation of
3252 @emph{gnatmake} will recompile the source.
3254 Configuration pragmas may be entered into the @code{gnat.adc} file
3255 either by running @cite{gnatchop} on a source file that consists only of
3256 configuration pragmas, or more conveniently by direct editing of the
3257 @code{gnat.adc} file, which is a standard format source file.
3259 Besides @code{gnat.adc}, additional files containing configuration
3260 pragmas may be applied to the current compilation using the switch
3261 @code{-gnatec=@emph{path}} where @cite{path} must designate an existing file that
3262 contains only configuration pragmas. These configuration pragmas are
3263 in addition to those found in @code{gnat.adc} (provided @code{gnat.adc}
3264 is present and switch @emph{-gnatA} is not used).
3266 It is allowable to specify several switches @emph{-gnatec=}, all of which
3267 will be taken into account.
3269 Files containing configuration pragmas specified with switches
3270 @emph{-gnatec=} are added to the dependencies, unless they are
3271 temporary files. A file is considered temporary if its name ends in
3272 @code{.tmp} or @code{.TMP}. Certain tools follow this naming
3273 convention because they pass information to @emph{gcc} via
3274 temporary files that are immediately deleted; it doesn't make sense to
3275 depend on a file that no longer exists. Such tools include
3276 @emph{gprbuild}, @emph{gnatmake}, and @emph{gnatcheck}.
3278 If you are using project file, a separate mechanism is provided using
3279 project attributes, see @ref{7d,,Specifying Configuration Pragmas} for more
3282 @node Generating Object Files,Source Dependencies,Configuration Pragmas,The GNAT Compilation Model
3283 @anchor{gnat_ugn/the_gnat_compilation_model generating-object-files}@anchor{42}@anchor{gnat_ugn/the_gnat_compilation_model id31}@anchor{7e}
3284 @section Generating Object Files
3287 An Ada program consists of a set of source files, and the first step in
3288 compiling the program is to generate the corresponding object files.
3289 These are generated by compiling a subset of these source files.
3290 The files you need to compile are the following:
3296 If a package spec has no body, compile the package spec to produce the
3297 object file for the package.
3300 If a package has both a spec and a body, compile the body to produce the
3301 object file for the package. The source file for the package spec need
3302 not be compiled in this case because there is only one object file, which
3303 contains the code for both the spec and body of the package.
3306 For a subprogram, compile the subprogram body to produce the object file
3307 for the subprogram. The spec, if one is present, is as usual in a
3308 separate file, and need not be compiled.
3317 In the case of subunits, only compile the parent unit. A single object
3318 file is generated for the entire subunit tree, which includes all the
3322 Compile child units independently of their parent units
3323 (though, of course, the spec of all the ancestor unit must be present in order
3324 to compile a child unit).
3329 Compile generic units in the same manner as any other units. The object
3330 files in this case are small dummy files that contain at most the
3331 flag used for elaboration checking. This is because GNAT always handles generic
3332 instantiation by means of macro expansion. However, it is still necessary to
3333 compile generic units, for dependency checking and elaboration purposes.
3336 The preceding rules describe the set of files that must be compiled to
3337 generate the object files for a program. Each object file has the same
3338 name as the corresponding source file, except that the extension is
3341 You may wish to compile other files for the purpose of checking their
3342 syntactic and semantic correctness. For example, in the case where a
3343 package has a separate spec and body, you would not normally compile the
3344 spec. However, it is convenient in practice to compile the spec to make
3345 sure it is error-free before compiling clients of this spec, because such
3346 compilations will fail if there is an error in the spec.
3348 GNAT provides an option for compiling such files purely for the
3349 purposes of checking correctness; such compilations are not required as
3350 part of the process of building a program. To compile a file in this
3351 checking mode, use the @emph{-gnatc} switch.
3353 @node Source Dependencies,The Ada Library Information Files,Generating Object Files,The GNAT Compilation Model
3354 @anchor{gnat_ugn/the_gnat_compilation_model id32}@anchor{7f}@anchor{gnat_ugn/the_gnat_compilation_model source-dependencies}@anchor{43}
3355 @section Source Dependencies
3358 A given object file clearly depends on the source file which is compiled
3359 to produce it. Here we are using "depends" in the sense of a typical
3360 @cite{make} utility; in other words, an object file depends on a source
3361 file if changes to the source file require the object file to be
3363 In addition to this basic dependency, a given object may depend on
3364 additional source files as follows:
3370 If a file being compiled @emph{with}s a unit @cite{X}, the object file
3371 depends on the file containing the spec of unit @cite{X}. This includes
3372 files that are @emph{with}ed implicitly either because they are parents
3373 of @emph{with}ed child units or they are run-time units required by the
3374 language constructs used in a particular unit.
3377 If a file being compiled instantiates a library level generic unit, the
3378 object file depends on both the spec and body files for this generic
3382 If a file being compiled instantiates a generic unit defined within a
3383 package, the object file depends on the body file for the package as
3384 well as the spec file.
3389 @geindex -gnatn switch
3395 If a file being compiled contains a call to a subprogram for which
3396 pragma @cite{Inline} applies and inlining is activated with the
3397 @emph{-gnatn} switch, the object file depends on the file containing the
3398 body of this subprogram as well as on the file containing the spec. Note
3399 that for inlining to actually occur as a result of the use of this switch,
3400 it is necessary to compile in optimizing mode.
3402 @geindex -gnatN switch
3404 The use of @emph{-gnatN} activates inlining optimization
3405 that is performed by the front end of the compiler. This inlining does
3406 not require that the code generation be optimized. Like @emph{-gnatn},
3407 the use of this switch generates additional dependencies.
3409 When using a gcc-based back end (in practice this means using any version
3410 of GNAT other than for the JVM, .NET or GNAAMP platforms), then the use of
3411 @emph{-gnatN} is deprecated, and the use of @emph{-gnatn} is preferred.
3412 Historically front end inlining was more extensive than the gcc back end
3413 inlining, but that is no longer the case.
3416 If an object file @code{O} depends on the proper body of a subunit through
3417 inlining or instantiation, it depends on the parent unit of the subunit.
3418 This means that any modification of the parent unit or one of its subunits
3419 affects the compilation of @code{O}.
3422 The object file for a parent unit depends on all its subunit body files.
3425 The previous two rules meant that for purposes of computing dependencies and
3426 recompilation, a body and all its subunits are treated as an indivisible whole.
3428 These rules are applied transitively: if unit @cite{A} @emph{with}s
3429 unit @cite{B}, whose elaboration calls an inlined procedure in package
3430 @cite{C}, the object file for unit @cite{A} will depend on the body of
3431 @cite{C}, in file @code{c.adb}.
3433 The set of dependent files described by these rules includes all the
3434 files on which the unit is semantically dependent, as dictated by the
3435 Ada language standard. However, it is a superset of what the
3436 standard describes, because it includes generic, inline, and subunit
3439 An object file must be recreated by recompiling the corresponding source
3440 file if any of the source files on which it depends are modified. For
3441 example, if the @cite{make} utility is used to control compilation,
3442 the rule for an Ada object file must mention all the source files on
3443 which the object file depends, according to the above definition.
3444 The determination of the necessary
3445 recompilations is done automatically when one uses @emph{gnatmake}.
3448 @node The Ada Library Information Files,Binding an Ada Program,Source Dependencies,The GNAT Compilation Model
3449 @anchor{gnat_ugn/the_gnat_compilation_model id33}@anchor{80}@anchor{gnat_ugn/the_gnat_compilation_model the-ada-library-information-files}@anchor{44}
3450 @section The Ada Library Information Files
3453 @geindex Ada Library Information files
3457 Each compilation actually generates two output files. The first of these
3458 is the normal object file that has a @code{.o} extension. The second is a
3459 text file containing full dependency information. It has the same
3460 name as the source file, but an @code{.ali} extension.
3461 This file is known as the Ada Library Information (@code{ALI}) file.
3462 The following information is contained in the @code{ALI} file.
3468 Version information (indicates which version of GNAT was used to compile
3469 the unit(s) in question)
3472 Main program information (including priority and time slice settings,
3473 as well as the wide character encoding used during compilation).
3476 List of arguments used in the @emph{gcc} command for the compilation
3479 Attributes of the unit, including configuration pragmas used, an indication
3480 of whether the compilation was successful, exception model used etc.
3483 A list of relevant restrictions applying to the unit (used for consistency)
3487 Categorization information (e.g., use of pragma @cite{Pure}).
3490 Information on all @emph{with}ed units, including presence of
3491 Elaborate` or @cite{Elaborate_All} pragmas.
3494 Information from any @cite{Linker_Options} pragmas used in the unit
3497 Information on the use of @cite{Body_Version} or @cite{Version}
3498 attributes in the unit.
3501 Dependency information. This is a list of files, together with
3502 time stamp and checksum information. These are files on which
3503 the unit depends in the sense that recompilation is required
3504 if any of these units are modified.
3507 Cross-reference data. Contains information on all entities referenced
3508 in the unit. Used by tools like @cite{gnatxref} and @cite{gnatfind} to
3509 provide cross-reference information.
3512 For a full detailed description of the format of the @code{ALI} file,
3513 see the source of the body of unit @cite{Lib.Writ}, contained in file
3514 @code{lib-writ.adb} in the GNAT compiler sources.
3516 @node Binding an Ada Program,GNAT and Libraries,The Ada Library Information Files,The GNAT Compilation Model
3517 @anchor{gnat_ugn/the_gnat_compilation_model id34}@anchor{81}@anchor{gnat_ugn/the_gnat_compilation_model binding-an-ada-program}@anchor{45}
3518 @section Binding an Ada Program
3521 When using languages such as C and C++, once the source files have been
3522 compiled the only remaining step in building an executable program
3523 is linking the object modules together. This means that it is possible to
3524 link an inconsistent version of a program, in which two units have
3525 included different versions of the same header.
3527 The rules of Ada do not permit such an inconsistent program to be built.
3528 For example, if two clients have different versions of the same package,
3529 it is illegal to build a program containing these two clients.
3530 These rules are enforced by the GNAT binder, which also determines an
3531 elaboration order consistent with the Ada rules.
3533 The GNAT binder is run after all the object files for a program have
3534 been created. It is given the name of the main program unit, and from
3535 this it determines the set of units required by the program, by reading the
3536 corresponding ALI files. It generates error messages if the program is
3537 inconsistent or if no valid order of elaboration exists.
3539 If no errors are detected, the binder produces a main program, in Ada by
3540 default, that contains calls to the elaboration procedures of those
3541 compilation unit that require them, followed by
3542 a call to the main program. This Ada program is compiled to generate the
3543 object file for the main program. The name of
3544 the Ada file is @code{b~xxx}.adb` (with the corresponding spec
3545 @code{b~xxx}.ads`) where @cite{xxx} is the name of the
3548 Finally, the linker is used to build the resulting executable program,
3549 using the object from the main program from the bind step as well as the
3550 object files for the Ada units of the program.
3552 @node GNAT and Libraries,Conditional Compilation,Binding an Ada Program,The GNAT Compilation Model
3553 @anchor{gnat_ugn/the_gnat_compilation_model gnat-and-libraries}@anchor{17}@anchor{gnat_ugn/the_gnat_compilation_model id35}@anchor{82}
3554 @section GNAT and Libraries
3557 @geindex Library building and using
3559 This chapter describes how to build and use libraries with GNAT, and also shows
3560 how to recompile the GNAT run-time library. You should be familiar with the
3561 Project Manager facility (@ref{b,,GNAT Project Manager}) before reading this
3565 * Introduction to Libraries in GNAT::
3566 * General Ada Libraries::
3567 * Stand-alone Ada Libraries::
3568 * Rebuilding the GNAT Run-Time Library::
3572 @node Introduction to Libraries in GNAT,General Ada Libraries,,GNAT and Libraries
3573 @anchor{gnat_ugn/the_gnat_compilation_model introduction-to-libraries-in-gnat}@anchor{83}@anchor{gnat_ugn/the_gnat_compilation_model id36}@anchor{84}
3574 @subsection Introduction to Libraries in GNAT
3577 A library is, conceptually, a collection of objects which does not have its
3578 own main thread of execution, but rather provides certain services to the
3579 applications that use it. A library can be either statically linked with the
3580 application, in which case its code is directly included in the application,
3581 or, on platforms that support it, be dynamically linked, in which case
3582 its code is shared by all applications making use of this library.
3584 GNAT supports both types of libraries.
3585 In the static case, the compiled code can be provided in different ways. The
3586 simplest approach is to provide directly the set of objects resulting from
3587 compilation of the library source files. Alternatively, you can group the
3588 objects into an archive using whatever commands are provided by the operating
3589 system. For the latter case, the objects are grouped into a shared library.
3591 In the GNAT environment, a library has three types of components:
3600 @code{ALI} files (see @ref{44,,The Ada Library Information Files}), and
3603 Object files, an archive or a shared library.
3606 A GNAT library may expose all its source files, which is useful for
3607 documentation purposes. Alternatively, it may expose only the units needed by
3608 an external user to make use of the library. That is to say, the specs
3609 reflecting the library services along with all the units needed to compile
3610 those specs, which can include generic bodies or any body implementing an
3611 inlined routine. In the case of @emph{stand-alone libraries} those exposed
3612 units are called @emph{interface units} (@ref{85,,Stand-alone Ada Libraries}).
3614 All compilation units comprising an application, including those in a library,
3615 need to be elaborated in an order partially defined by Ada's semantics. GNAT
3616 computes the elaboration order from the @code{ALI} files and this is why they
3617 constitute a mandatory part of GNAT libraries.
3618 @emph{Stand-alone libraries} are the exception to this rule because a specific
3619 library elaboration routine is produced independently of the application(s)
3622 @node General Ada Libraries,Stand-alone Ada Libraries,Introduction to Libraries in GNAT,GNAT and Libraries
3623 @anchor{gnat_ugn/the_gnat_compilation_model general-ada-libraries}@anchor{86}@anchor{gnat_ugn/the_gnat_compilation_model id37}@anchor{87}
3624 @subsection General Ada Libraries
3628 * Building a library::
3629 * Installing a library::
3634 @node Building a library,Installing a library,,General Ada Libraries
3635 @anchor{gnat_ugn/the_gnat_compilation_model building-a-library}@anchor{88}@anchor{gnat_ugn/the_gnat_compilation_model id38}@anchor{89}
3636 @subsubsection Building a library
3639 The easiest way to build a library is to use the Project Manager,
3640 which supports a special type of project called a @emph{Library Project}
3641 (see @ref{8a,,Library Projects}).
3643 A project is considered a library project, when two project-level attributes
3644 are defined in it: @cite{Library_Name} and @cite{Library_Dir}. In order to
3645 control different aspects of library configuration, additional optional
3646 project-level attributes can be specified:
3655 @item @emph{Library_Kind}
3657 This attribute controls whether the library is to be static or dynamic
3664 @item @emph{Library_Version}
3666 This attribute specifies the library version; this value is used
3667 during dynamic linking of shared libraries to determine if the currently
3668 installed versions of the binaries are compatible.
3672 @emph{Library_Options}
3678 @item @emph{Library_GCC}
3680 These attributes specify additional low-level options to be used during
3681 library generation, and redefine the actual application used to generate
3686 The GNAT Project Manager takes full care of the library maintenance task,
3687 including recompilation of the source files for which objects do not exist
3688 or are not up to date, assembly of the library archive, and installation of
3689 the library (i.e., copying associated source, object and @code{ALI} files
3690 to the specified location).
3692 Here is a simple library project file:
3696 for Source_Dirs use ("src1", "src2");
3697 for Object_Dir use "obj";
3698 for Library_Name use "mylib";
3699 for Library_Dir use "lib";
3700 for Library_Kind use "dynamic";
3704 and the compilation command to build and install the library:
3710 It is not entirely trivial to perform manually all the steps required to
3711 produce a library. We recommend that you use the GNAT Project Manager
3712 for this task. In special cases where this is not desired, the necessary
3713 steps are discussed below.
3715 There are various possibilities for compiling the units that make up the
3716 library: for example with a Makefile (@ref{21,,Using the GNU make Utility}) or
3717 with a conventional script. For simple libraries, it is also possible to create
3718 a dummy main program which depends upon all the packages that comprise the
3719 interface of the library. This dummy main program can then be given to
3720 @emph{gnatmake}, which will ensure that all necessary objects are built.
3722 After this task is accomplished, you should follow the standard procedure
3723 of the underlying operating system to produce the static or shared library.
3725 Here is an example of such a dummy program:
3728 with My_Lib.Service1;
3729 with My_Lib.Service2;
3730 with My_Lib.Service3;
3731 procedure My_Lib_Dummy is
3737 Here are the generic commands that will build an archive or a shared library.
3740 # compiling the library
3741 $ gnatmake -c my_lib_dummy.adb
3743 # we don't need the dummy object itself
3744 $ rm my_lib_dummy.o my_lib_dummy.ali
3746 # create an archive with the remaining objects
3747 $ ar rc libmy_lib.a *.o
3748 # some systems may require "ranlib" to be run as well
3750 # or create a shared library
3751 $ gcc -shared -o libmy_lib.so *.o
3752 # some systems may require the code to have been compiled with -fPIC
3754 # remove the object files that are now in the library
3757 # Make the ALI files read-only so that gnatmake will not try to
3758 # regenerate the objects that are in the library
3762 Please note that the library must have a name of the form @code{lib@emph{xxx}.a}
3763 or @code{lib@emph{xxx}.so} (or @code{lib@emph{xxx}.dll} on Windows) in order to
3764 be accessed by the directive @code{-l@emph{xxx}} at link time.
3766 @node Installing a library,Using a library,Building a library,General Ada Libraries
3767 @anchor{gnat_ugn/the_gnat_compilation_model installing-a-library}@anchor{8b}@anchor{gnat_ugn/the_gnat_compilation_model id39}@anchor{8c}
3768 @subsubsection Installing a library
3771 @geindex ADA_PROJECT_PATH
3773 @geindex GPR_PROJECT_PATH
3775 If you use project files, library installation is part of the library build
3776 process (@ref{8d,,Installing a library with project files}).
3778 When project files are not an option, it is also possible, but not recommended,
3779 to install the library so that the sources needed to use the library are on the
3780 Ada source path and the ALI files & libraries be on the Ada Object path (see
3781 @ref{8e,,Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
3782 administrator can place general-purpose libraries in the default compiler
3783 paths, by specifying the libraries' location in the configuration files
3784 @code{ada_source_path} and @code{ada_object_path}. These configuration files
3785 must be located in the GNAT installation tree at the same place as the gcc spec
3786 file. The location of the gcc spec file can be determined as follows:
3792 The configuration files mentioned above have a simple format: each line
3793 must contain one unique directory name.
3794 Those names are added to the corresponding path
3795 in their order of appearance in the file. The names can be either absolute
3796 or relative; in the latter case, they are relative to where theses files
3799 The files @code{ada_source_path} and @code{ada_object_path} might not be
3801 GNAT installation, in which case, GNAT will look for its run-time library in
3802 the directories @code{adainclude} (for the sources) and @code{adalib} (for the
3803 objects and @code{ALI} files). When the files exist, the compiler does not
3804 look in @code{adainclude} and @code{adalib}, and thus the
3805 @code{ada_source_path} file
3806 must contain the location for the GNAT run-time sources (which can simply
3807 be @code{adainclude}). In the same way, the @code{ada_object_path} file must
3808 contain the location for the GNAT run-time objects (which can simply
3811 You can also specify a new default path to the run-time library at compilation
3812 time with the switch @emph{--RTS=rts-path}. You can thus choose / change
3813 the run-time library you want your program to be compiled with. This switch is
3814 recognized by @emph{gcc}, @emph{gnatmake}, @emph{gnatbind},
3815 @emph{gnatls}, @emph{gnatfind} and @emph{gnatxref}.
3817 It is possible to install a library before or after the standard GNAT
3818 library, by reordering the lines in the configuration files. In general, a
3819 library must be installed before the GNAT library if it redefines
3822 @node Using a library,,Installing a library,General Ada Libraries
3823 @anchor{gnat_ugn/the_gnat_compilation_model using-a-library}@anchor{8f}@anchor{gnat_ugn/the_gnat_compilation_model id40}@anchor{90}
3824 @subsubsection Using a library
3827 Once again, the project facility greatly simplifies the use of
3828 libraries. In this context, using a library is just a matter of adding a
3829 @emph{with} clause in the user project. For instance, to make use of the
3830 library @cite{My_Lib} shown in examples in earlier sections, you can
3840 Even if you have a third-party, non-Ada library, you can still use GNAT's
3841 Project Manager facility to provide a wrapper for it. For example, the
3842 following project, when @emph{with}ed by your main project, will link with the
3843 third-party library @code{liba.a}:
3847 for Externally_Built use "true";
3848 for Source_Files use ();
3849 for Library_Dir use "lib";
3850 for Library_Name use "a";
3851 for Library_Kind use "static";
3855 This is an alternative to the use of @cite{pragma Linker_Options}. It is
3856 especially interesting in the context of systems with several interdependent
3857 static libraries where finding a proper linker order is not easy and best be
3858 left to the tools having visibility over project dependence information.
3860 In order to use an Ada library manually, you need to make sure that this
3861 library is on both your source and object path
3862 (see @ref{8e,,Search Paths and the Run-Time Library (RTL)}
3863 and @ref{91,,Search Paths for gnatbind}). Furthermore, when the objects are grouped
3864 in an archive or a shared library, you need to specify the desired
3865 library at link time.
3867 For example, you can use the library @code{mylib} installed in
3868 @code{/dir/my_lib_src} and @code{/dir/my_lib_obj} with the following commands:
3871 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \\
3875 This can be expressed more simply:
3881 when the following conditions are met:
3887 @code{/dir/my_lib_src} has been added by the user to the environment
3889 @geindex ADA_INCLUDE_PATH
3890 @geindex environment variable; ADA_INCLUDE_PATH
3891 @code{ADA_INCLUDE_PATH}, or by the administrator to the file
3892 @code{ada_source_path}
3895 @code{/dir/my_lib_obj} has been added by the user to the environment
3897 @geindex ADA_OBJECTS_PATH
3898 @geindex environment variable; ADA_OBJECTS_PATH
3899 @code{ADA_OBJECTS_PATH}, or by the administrator to the file
3900 @code{ada_object_path}
3903 a pragma @cite{Linker_Options} has been added to one of the sources.
3907 pragma Linker_Options ("-lmy_lib");
3911 Note that you may also load a library dynamically at
3912 run time given its filename, as illustrated in the GNAT @code{plugins} example
3913 in the directory @code{share/examples/gnat/plugins} within the GNAT
3916 @node Stand-alone Ada Libraries,Rebuilding the GNAT Run-Time Library,General Ada Libraries,GNAT and Libraries
3917 @anchor{gnat_ugn/the_gnat_compilation_model stand-alone-ada-libraries}@anchor{85}@anchor{gnat_ugn/the_gnat_compilation_model id41}@anchor{92}
3918 @subsection Stand-alone Ada Libraries
3921 @geindex Stand-alone libraries
3924 * Introduction to Stand-alone Libraries::
3925 * Building a Stand-alone Library::
3926 * Creating a Stand-alone Library to be used in a non-Ada context::
3927 * Restrictions in Stand-alone Libraries::
3931 @node Introduction to Stand-alone Libraries,Building a Stand-alone Library,,Stand-alone Ada Libraries
3932 @anchor{gnat_ugn/the_gnat_compilation_model introduction-to-stand-alone-libraries}@anchor{93}@anchor{gnat_ugn/the_gnat_compilation_model id42}@anchor{94}
3933 @subsubsection Introduction to Stand-alone Libraries
3936 A Stand-alone Library (abbreviated 'SAL') is a library that contains the
3938 elaborate the Ada units that are included in the library. In contrast with
3939 an ordinary library, which consists of all sources, objects and @code{ALI}
3941 library, a SAL may specify a restricted subset of compilation units
3942 to serve as a library interface. In this case, the fully
3943 self-sufficient set of files will normally consist of an objects
3944 archive, the sources of interface units' specs, and the @code{ALI}
3945 files of interface units.
3946 If an interface spec contains a generic unit or an inlined subprogram,
3948 source must also be provided; if the units that must be provided in the source
3949 form depend on other units, the source and @code{ALI} files of those must
3952 The main purpose of a SAL is to minimize the recompilation overhead of client
3953 applications when a new version of the library is installed. Specifically,
3954 if the interface sources have not changed, client applications do not need to
3955 be recompiled. If, furthermore, a SAL is provided in the shared form and its
3956 version, controlled by @cite{Library_Version} attribute, is not changed,
3957 then the clients do not need to be relinked.
3959 SALs also allow the library providers to minimize the amount of library source
3960 text exposed to the clients. Such 'information hiding' might be useful or
3961 necessary for various reasons.
3963 Stand-alone libraries are also well suited to be used in an executable whose
3964 main routine is not written in Ada.
3966 @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
3967 @anchor{gnat_ugn/the_gnat_compilation_model id43}@anchor{95}@anchor{gnat_ugn/the_gnat_compilation_model building-a-stand-alone-library}@anchor{96}
3968 @subsubsection Building a Stand-alone Library
3971 GNAT's Project facility provides a simple way of building and installing
3972 stand-alone libraries; see @ref{97,,Stand-alone Library Projects}.
3973 To be a Stand-alone Library Project, in addition to the two attributes
3974 that make a project a Library Project (@cite{Library_Name} and
3975 @cite{Library_Dir}; see @ref{8a,,Library Projects}), the attribute
3976 @cite{Library_Interface} must be defined. For example:
3979 for Library_Dir use "lib_dir";
3980 for Library_Name use "dummy";
3981 for Library_Interface use ("int1", "int1.child");
3984 Attribute @cite{Library_Interface} has a non-empty string list value,
3985 each string in the list designating a unit contained in an immediate source
3986 of the project file.
3988 When a Stand-alone Library is built, first the binder is invoked to build
3989 a package whose name depends on the library name
3990 (@code{b~dummy.ads/b} in the example above).
3991 This binder-generated package includes initialization and
3992 finalization procedures whose
3993 names depend on the library name (@cite{dummyinit} and @cite{dummyfinal}
3995 above). The object corresponding to this package is included in the library.
3997 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
3998 calling of these procedures if a static SAL is built, or if a shared SAL
4000 with the project-level attribute @cite{Library_Auto_Init} set to
4003 For a Stand-Alone Library, only the @code{ALI} files of the Interface Units
4004 (those that are listed in attribute @cite{Library_Interface}) are copied to
4005 the Library Directory. As a consequence, only the Interface Units may be
4006 imported from Ada units outside of the library. If other units are imported,
4007 the binding phase will fail.
4009 It is also possible to build an encapsulated library where not only
4010 the code to elaborate and finalize the library is embedded but also
4011 ensuring that the library is linked only against static
4012 libraries. So an encapsulated library only depends on system
4013 libraries, all other code, including the GNAT runtime, is embedded. To
4014 build an encapsulated library the attribute
4015 @cite{Library_Standalone} must be set to @cite{encapsulated}:
4018 for Library_Dir use "lib_dir";
4019 for Library_Name use "dummy";
4020 for Library_Kind use "dynamic";
4021 for Library_Interface use ("int1", "int1.child");
4022 for Library_Standalone use "encapsulated";
4025 The default value for this attribute is @cite{standard} in which case
4026 a stand-alone library is built.
4028 The attribute @cite{Library_Src_Dir} may be specified for a
4029 Stand-Alone Library. @cite{Library_Src_Dir} is a simple attribute that has a
4030 single string value. Its value must be the path (absolute or relative to the
4031 project directory) of an existing directory. This directory cannot be the
4032 object directory or one of the source directories, but it can be the same as
4033 the library directory. The sources of the Interface
4034 Units of the library that are needed by an Ada client of the library will be
4035 copied to the designated directory, called the Interface Copy directory.
4036 These sources include the specs of the Interface Units, but they may also
4037 include bodies and subunits, when pragmas @cite{Inline} or @cite{Inline_Always}
4038 are used, or when there is a generic unit in the spec. Before the sources
4039 are copied to the Interface Copy directory, an attempt is made to delete all
4040 files in the Interface Copy directory.
4042 Building stand-alone libraries by hand is somewhat tedious, but for those
4043 occasions when it is necessary here are the steps that you need to perform:
4049 Compile all library sources.
4052 Invoke the binder with the switch @emph{-n} (No Ada main program),
4053 with all the @code{ALI} files of the interfaces, and
4054 with the switch @emph{-L} to give specific names to the @cite{init}
4055 and @cite{final} procedures. For example:
4058 $ gnatbind -n int1.ali int2.ali -Lsal1
4062 Compile the binder generated file:
4069 Link the dynamic library with all the necessary object files,
4070 indicating to the linker the names of the @cite{init} (and possibly
4071 @cite{final}) procedures for automatic initialization (and finalization).
4072 The built library should be placed in a directory different from
4073 the object directory.
4076 Copy the @cite{ALI} files of the interface to the library directory,
4077 add in this copy an indication that it is an interface to a SAL
4078 (i.e., add a word @emph{SL} on the line in the @code{ALI} file that starts
4079 with letter 'P') and make the modified copy of the @code{ALI} file
4083 Using SALs is not different from using other libraries
4084 (see @ref{8f,,Using a library}).
4086 @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
4087 @anchor{gnat_ugn/the_gnat_compilation_model creating-a-stand-alone-library-to-be-used-in-a-non-ada-context}@anchor{98}@anchor{gnat_ugn/the_gnat_compilation_model id44}@anchor{99}
4088 @subsubsection Creating a Stand-alone Library to be used in a non-Ada context
4091 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
4094 The only extra step required is to ensure that library interface subprograms
4095 are compatible with the main program, by means of @cite{pragma Export}
4096 or @cite{pragma Convention}.
4098 Here is an example of simple library interface for use with C main program:
4101 package My_Package is
4103 procedure Do_Something;
4104 pragma Export (C, Do_Something, "do_something");
4106 procedure Do_Something_Else;
4107 pragma Export (C, Do_Something_Else, "do_something_else");
4112 On the foreign language side, you must provide a 'foreign' view of the
4113 library interface; remember that it should contain elaboration routines in
4114 addition to interface subprograms.
4116 The example below shows the content of @cite{mylib_interface.h} (note
4117 that there is no rule for the naming of this file, any name can be used)
4120 /* the library elaboration procedure */
4121 extern void mylibinit (void);
4123 /* the library finalization procedure */
4124 extern void mylibfinal (void);
4126 /* the interface exported by the library */
4127 extern void do_something (void);
4128 extern void do_something_else (void);
4131 Libraries built as explained above can be used from any program, provided
4132 that the elaboration procedures (named @cite{mylibinit} in the previous
4133 example) are called before the library services are used. Any number of
4134 libraries can be used simultaneously, as long as the elaboration
4135 procedure of each library is called.
4137 Below is an example of a C program that uses the @cite{mylib} library.
4140 #include "mylib_interface.h"
4145 /* First, elaborate the library before using it */
4148 /* Main program, using the library exported entities */
4150 do_something_else ();
4152 /* Library finalization at the end of the program */
4158 Note that invoking any library finalization procedure generated by
4159 @cite{gnatbind} shuts down the Ada run-time environment.
4161 finalization of all Ada libraries must be performed at the end of the program.
4162 No call to these libraries or to the Ada run-time library should be made
4163 after the finalization phase.
4165 Note also that special care must be taken with multi-tasks
4166 applications. The initialization and finalization routines are not
4167 protected against concurrent access. If such requirement is needed it
4168 must be ensured at the application level using a specific operating
4169 system services like a mutex or a critical-section.
4171 @node Restrictions in Stand-alone Libraries,,Creating a Stand-alone Library to be used in a non-Ada context,Stand-alone Ada Libraries
4172 @anchor{gnat_ugn/the_gnat_compilation_model id45}@anchor{9a}@anchor{gnat_ugn/the_gnat_compilation_model restrictions-in-stand-alone-libraries}@anchor{9b}
4173 @subsubsection Restrictions in Stand-alone Libraries
4176 The pragmas listed below should be used with caution inside libraries,
4177 as they can create incompatibilities with other Ada libraries:
4183 pragma @cite{Locking_Policy}
4186 pragma @cite{Partition_Elaboration_Policy}
4189 pragma @cite{Queuing_Policy}
4192 pragma @cite{Task_Dispatching_Policy}
4195 pragma @cite{Unreserve_All_Interrupts}
4198 When using a library that contains such pragmas, the user must make sure
4199 that all libraries use the same pragmas with the same values. Otherwise,
4200 @cite{Program_Error} will
4201 be raised during the elaboration of the conflicting
4202 libraries. The usage of these pragmas and its consequences for the user
4203 should therefore be well documented.
4205 Similarly, the traceback in the exception occurrence mechanism should be
4206 enabled or disabled in a consistent manner across all libraries.
4207 Otherwise, Program_Error will be raised during the elaboration of the
4208 conflicting libraries.
4210 If the @cite{Version} or @cite{Body_Version}
4211 attributes are used inside a library, then you need to
4212 perform a @cite{gnatbind} step that specifies all @code{ALI} files in all
4213 libraries, so that version identifiers can be properly computed.
4214 In practice these attributes are rarely used, so this is unlikely
4215 to be a consideration.
4217 @node Rebuilding the GNAT Run-Time Library,,Stand-alone Ada Libraries,GNAT and Libraries
4218 @anchor{gnat_ugn/the_gnat_compilation_model id46}@anchor{9c}@anchor{gnat_ugn/the_gnat_compilation_model rebuilding-the-gnat-run-time-library}@anchor{9d}
4219 @subsection Rebuilding the GNAT Run-Time Library
4222 @geindex GNAT Run-Time Library
4225 @geindex Building the GNAT Run-Time Library
4227 @geindex Rebuilding the GNAT Run-Time Library
4229 @geindex Run-Time Library
4232 It may be useful to recompile the GNAT library in various contexts, the
4233 most important one being the use of partition-wide configuration pragmas
4234 such as @cite{Normalize_Scalars}. A special Makefile called
4235 @cite{Makefile.adalib} is provided to that effect and can be found in
4236 the directory containing the GNAT library. The location of this
4237 directory depends on the way the GNAT environment has been installed and can
4238 be determined by means of the command:
4244 The last entry in the object search path usually contains the
4245 gnat library. This Makefile contains its own documentation and in
4246 particular the set of instructions needed to rebuild a new library and
4249 @geindex Conditional compilation
4251 @node Conditional Compilation,Mixed Language Programming,GNAT and Libraries,The GNAT Compilation Model
4252 @anchor{gnat_ugn/the_gnat_compilation_model id47}@anchor{9e}@anchor{gnat_ugn/the_gnat_compilation_model conditional-compilation}@anchor{18}
4253 @section Conditional Compilation
4256 This section presents some guidelines for modeling conditional compilation in Ada and describes the
4257 gnatprep preprocessor utility.
4259 @geindex Conditional compilation
4262 * Modeling Conditional Compilation in Ada::
4263 * Preprocessing with gnatprep::
4264 * Integrated Preprocessing::
4268 @node Modeling Conditional Compilation in Ada,Preprocessing with gnatprep,,Conditional Compilation
4269 @anchor{gnat_ugn/the_gnat_compilation_model modeling-conditional-compilation-in-ada}@anchor{9f}@anchor{gnat_ugn/the_gnat_compilation_model id48}@anchor{a0}
4270 @subsection Modeling Conditional Compilation in Ada
4273 It is often necessary to arrange for a single source program
4274 to serve multiple purposes, where it is compiled in different
4275 ways to achieve these different goals. Some examples of the
4276 need for this feature are
4282 Adapting a program to a different hardware environment
4285 Adapting a program to a different target architecture
4288 Turning debugging features on and off
4291 Arranging for a program to compile with different compilers
4294 In C, or C++, the typical approach would be to use the preprocessor
4295 that is defined as part of the language. The Ada language does not
4296 contain such a feature. This is not an oversight, but rather a very
4297 deliberate design decision, based on the experience that overuse of
4298 the preprocessing features in C and C++ can result in programs that
4299 are extremely difficult to maintain. For example, if we have ten
4300 switches that can be on or off, this means that there are a thousand
4301 separate programs, any one of which might not even be syntactically
4302 correct, and even if syntactically correct, the resulting program
4303 might not work correctly. Testing all combinations can quickly become
4306 Nevertheless, the need to tailor programs certainly exists, and in
4307 this section we will discuss how this can
4308 be achieved using Ada in general, and GNAT in particular.
4311 * Use of Boolean Constants::
4312 * Debugging - A Special Case::
4313 * Conditionalizing Declarations::
4314 * Use of Alternative Implementations::
4319 @node Use of Boolean Constants,Debugging - A Special Case,,Modeling Conditional Compilation in Ada
4320 @anchor{gnat_ugn/the_gnat_compilation_model id49}@anchor{a1}@anchor{gnat_ugn/the_gnat_compilation_model use-of-boolean-constants}@anchor{a2}
4321 @subsubsection Use of Boolean Constants
4324 In the case where the difference is simply which code
4325 sequence is executed, the cleanest solution is to use Boolean
4326 constants to control which code is executed.
4329 FP_Initialize_Required : constant Boolean := True;
4331 if FP_Initialize_Required then
4336 Not only will the code inside the @cite{if} statement not be executed if
4337 the constant Boolean is @cite{False}, but it will also be completely
4338 deleted from the program.
4339 However, the code is only deleted after the @cite{if} statement
4340 has been checked for syntactic and semantic correctness.
4341 (In contrast, with preprocessors the code is deleted before the
4342 compiler ever gets to see it, so it is not checked until the switch
4345 @geindex Preprocessors (contrasted with conditional compilation)
4347 Typically the Boolean constants will be in a separate package,
4352 FP_Initialize_Required : constant Boolean := True;
4353 Reset_Available : constant Boolean := False;
4358 The @cite{Config} package exists in multiple forms for the various targets,
4359 with an appropriate script selecting the version of @cite{Config} needed.
4360 Then any other unit requiring conditional compilation can do a @emph{with}
4361 of @cite{Config} to make the constants visible.
4363 @node Debugging - A Special Case,Conditionalizing Declarations,Use of Boolean Constants,Modeling Conditional Compilation in Ada
4364 @anchor{gnat_ugn/the_gnat_compilation_model debugging-a-special-case}@anchor{a3}@anchor{gnat_ugn/the_gnat_compilation_model id50}@anchor{a4}
4365 @subsubsection Debugging - A Special Case
4368 A common use of conditional code is to execute statements (for example
4369 dynamic checks, or output of intermediate results) under control of a
4370 debug switch, so that the debugging behavior can be turned on and off.
4371 This can be done using a Boolean constant to control whether the code
4376 Put_Line ("got to the first stage!");
4383 if Debugging and then Temperature > 999.0 then
4384 raise Temperature_Crazy;
4388 @geindex pragma Assert
4390 Since this is a common case, there are special features to deal with
4391 this in a convenient manner. For the case of tests, Ada 2005 has added
4392 a pragma @cite{Assert} that can be used for such tests. This pragma is modeled
4393 on the @cite{Assert} pragma that has always been available in GNAT, so this
4394 feature may be used with GNAT even if you are not using Ada 2005 features.
4395 The use of pragma @cite{Assert} is described in the
4396 @cite{GNAT_Reference_Manual}, but as an
4397 example, the last test could be written:
4400 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
4406 pragma Assert (Temperature <= 999.0);
4409 In both cases, if assertions are active and the temperature is excessive,
4410 the exception @cite{Assert_Failure} will be raised, with the given string in
4411 the first case or a string indicating the location of the pragma in the second
4412 case used as the exception message.
4414 @geindex pragma Assertion_Policy
4416 You can turn assertions on and off by using the @cite{Assertion_Policy}
4419 @geindex -gnata switch
4421 This is an Ada 2005 pragma which is implemented in all modes by
4422 GNAT. Alternatively, you can use the @emph{-gnata} switch
4423 to enable assertions from the command line, which applies to
4424 all versions of Ada.
4426 @geindex pragma Debug
4428 For the example above with the @cite{Put_Line}, the GNAT-specific pragma
4429 @cite{Debug} can be used:
4432 pragma Debug (Put_Line ("got to the first stage!"));
4435 If debug pragmas are enabled, the argument, which must be of the form of
4436 a procedure call, is executed (in this case, @cite{Put_Line} will be called).
4437 Only one call can be present, but of course a special debugging procedure
4438 containing any code you like can be included in the program and then
4439 called in a pragma @cite{Debug} argument as needed.
4441 One advantage of pragma @cite{Debug} over the @cite{if Debugging then}
4442 construct is that pragma @cite{Debug} can appear in declarative contexts,
4443 such as at the very beginning of a procedure, before local declarations have
4446 @geindex pragma Debug_Policy
4448 Debug pragmas are enabled using either the @emph{-gnata} switch that also
4449 controls assertions, or with a separate Debug_Policy pragma.
4451 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
4452 in Ada 95 and Ada 83 programs as well), and is analogous to
4453 pragma @cite{Assertion_Policy} to control assertions.
4455 @cite{Assertion_Policy} and @cite{Debug_Policy} are configuration pragmas,
4456 and thus they can appear in @code{gnat.adc} if you are not using a
4457 project file, or in the file designated to contain configuration pragmas
4459 They then apply to all subsequent compilations. In practice the use of
4460 the @emph{-gnata} switch is often the most convenient method of controlling
4461 the status of these pragmas.
4463 Note that a pragma is not a statement, so in contexts where a statement
4464 sequence is required, you can't just write a pragma on its own. You have
4465 to add a @cite{null} statement.
4469 ... -- some statements
4471 pragma Assert (Num_Cases < 10);
4476 @node Conditionalizing Declarations,Use of Alternative Implementations,Debugging - A Special Case,Modeling Conditional Compilation in Ada
4477 @anchor{gnat_ugn/the_gnat_compilation_model conditionalizing-declarations}@anchor{a5}@anchor{gnat_ugn/the_gnat_compilation_model id51}@anchor{a6}
4478 @subsubsection Conditionalizing Declarations
4481 In some cases it may be necessary to conditionalize declarations to meet
4482 different requirements. For example we might want a bit string whose length
4483 is set to meet some hardware message requirement.
4485 This may be possible using declare blocks controlled
4486 by conditional constants:
4489 if Small_Machine then
4491 X : Bit_String (1 .. 10);
4497 X : Large_Bit_String (1 .. 1000);
4504 Note that in this approach, both declarations are analyzed by the
4505 compiler so this can only be used where both declarations are legal,
4506 even though one of them will not be used.
4508 Another approach is to define integer constants, e.g., @cite{Bits_Per_Word},
4509 or Boolean constants, e.g., @cite{Little_Endian}, and then write declarations
4510 that are parameterized by these constants. For example
4514 Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
4518 If @cite{Bits_Per_Word} is set to 32, this generates either
4522 Field1 at 0 range 0 .. 32;
4526 for the big endian case, or
4530 Field1 at 0 range 10 .. 32;
4534 for the little endian case. Since a powerful subset of Ada expression
4535 notation is usable for creating static constants, clever use of this
4536 feature can often solve quite difficult problems in conditionalizing
4537 compilation (note incidentally that in Ada 95, the little endian
4538 constant was introduced as @cite{System.Default_Bit_Order}, so you do not
4539 need to define this one yourself).
4541 @node Use of Alternative Implementations,Preprocessing,Conditionalizing Declarations,Modeling Conditional Compilation in Ada
4542 @anchor{gnat_ugn/the_gnat_compilation_model use-of-alternative-implementations}@anchor{a7}@anchor{gnat_ugn/the_gnat_compilation_model id52}@anchor{a8}
4543 @subsubsection Use of Alternative Implementations
4546 In some cases, none of the approaches described above are adequate. This
4547 can occur for example if the set of declarations required is radically
4548 different for two different configurations.
4550 In this situation, the official Ada way of dealing with conditionalizing
4551 such code is to write separate units for the different cases. As long as
4552 this does not result in excessive duplication of code, this can be done
4553 without creating maintenance problems. The approach is to share common
4554 code as far as possible, and then isolate the code and declarations
4555 that are different. Subunits are often a convenient method for breaking
4556 out a piece of a unit that is to be conditionalized, with separate files
4557 for different versions of the subunit for different targets, where the
4558 build script selects the right one to give to the compiler.
4560 @geindex Subunits (and conditional compilation)
4562 As an example, consider a situation where a new feature in Ada 2005
4563 allows something to be done in a really nice way. But your code must be able
4564 to compile with an Ada 95 compiler. Conceptually you want to say:
4568 ... neat Ada 2005 code
4570 ... not quite as neat Ada 95 code
4574 where @cite{Ada_2005} is a Boolean constant.
4576 But this won't work when @cite{Ada_2005} is set to @cite{False},
4577 since the @cite{then} clause will be illegal for an Ada 95 compiler.
4578 (Recall that although such unreachable code would eventually be deleted
4579 by the compiler, it still needs to be legal. If it uses features
4580 introduced in Ada 2005, it will be illegal in Ada 95.)
4585 procedure Insert is separate;
4588 Then we have two files for the subunit @cite{Insert}, with the two sets of
4590 If the package containing this is called @cite{File_Queries}, then we might
4597 @code{file_queries-insert-2005.adb}
4600 @code{file_queries-insert-95.adb}
4603 and the build script renames the appropriate file to @code{file_queries-insert.adb} and then carries out the compilation.
4605 This can also be done with project files' naming schemes. For example:
4608 for body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
4611 Note also that with project files it is desirable to use a different extension
4612 than @code{ads} / @code{adb} for alternative versions. Otherwise a naming
4613 conflict may arise through another commonly used feature: to declare as part
4614 of the project a set of directories containing all the sources obeying the
4615 default naming scheme.
4617 The use of alternative units is certainly feasible in all situations,
4618 and for example the Ada part of the GNAT run-time is conditionalized
4619 based on the target architecture using this approach. As a specific example,
4620 consider the implementation of the AST feature in VMS. There is one
4621 spec: @code{s-asthan.ads} which is the same for all architectures, and three
4631 @item @code{s-asthan.adb}
4633 used for all non-VMS operating systems
4640 @item @code{s-asthan-vms-alpha.adb}
4642 used for VMS on the Alpha
4649 @item @code{s-asthan-vms-ia64.adb}
4651 used for VMS on the ia64
4655 The dummy version @code{s-asthan.adb} simply raises exceptions noting that
4656 this operating system feature is not available, and the two remaining
4657 versions interface with the corresponding versions of VMS to provide
4658 VMS-compatible AST handling. The GNAT build script knows the architecture
4659 and operating system, and automatically selects the right version,
4660 renaming it if necessary to @code{s-asthan.adb} before the run-time build.
4662 Another style for arranging alternative implementations is through Ada's
4663 access-to-subprogram facility.
4664 In case some functionality is to be conditionally included,
4665 you can declare an access-to-procedure variable @cite{Ref} that is initialized
4666 to designate a 'do nothing' procedure, and then invoke @cite{Ref.all}
4668 In some library package, set @cite{Ref} to @cite{Proc'Access} for some
4669 procedure @cite{Proc} that performs the relevant processing.
4670 The initialization only occurs if the library package is included in the
4672 The same idea can also be implemented using tagged types and dispatching
4675 @node Preprocessing,,Use of Alternative Implementations,Modeling Conditional Compilation in Ada
4676 @anchor{gnat_ugn/the_gnat_compilation_model preprocessing}@anchor{a9}@anchor{gnat_ugn/the_gnat_compilation_model id53}@anchor{aa}
4677 @subsubsection Preprocessing
4680 @geindex Preprocessing
4682 Although it is quite possible to conditionalize code without the use of
4683 C-style preprocessing, as described earlier in this section, it is
4684 nevertheless convenient in some cases to use the C approach. Moreover,
4685 older Ada compilers have often provided some preprocessing capability,
4686 so legacy code may depend on this approach, even though it is not
4689 To accommodate such use, GNAT provides a preprocessor (modeled to a large
4690 extent on the various preprocessors that have been used
4691 with legacy code on other compilers, to enable easier transition).
4695 The preprocessor may be used in two separate modes. It can be used quite
4696 separately from the compiler, to generate a separate output source file
4697 that is then fed to the compiler as a separate step. This is the
4698 @cite{gnatprep} utility, whose use is fully described in
4699 @ref{19,,Preprocessing with gnatprep}.
4701 The preprocessing language allows such constructs as
4704 #if DEBUG or else (PRIORITY > 4) then
4705 bunch of declarations
4707 completely different bunch of declarations
4711 The values of the symbols @cite{DEBUG} and @cite{PRIORITY} can be
4712 defined either on the command line or in a separate file.
4714 The other way of running the preprocessor is even closer to the C style and
4715 often more convenient. In this approach the preprocessing is integrated into
4716 the compilation process. The compiler is fed the preprocessor input which
4717 includes @cite{#if} lines etc, and then the compiler carries out the
4718 preprocessing internally and processes the resulting output.
4719 For more details on this approach, see @ref{1a,,Integrated Preprocessing}.
4721 @node Preprocessing with gnatprep,Integrated Preprocessing,Modeling Conditional Compilation in Ada,Conditional Compilation
4722 @anchor{gnat_ugn/the_gnat_compilation_model id54}@anchor{ab}@anchor{gnat_ugn/the_gnat_compilation_model preprocessing-with-gnatprep}@anchor{19}
4723 @subsection Preprocessing with @cite{gnatprep}
4728 @geindex Preprocessing (gnatprep)
4730 This section discusses how to use GNAT's @cite{gnatprep} utility for simple
4732 Although designed for use with GNAT, @cite{gnatprep} does not depend on any
4733 special GNAT features.
4734 For further discussion of conditional compilation in general, see
4735 @ref{18,,Conditional Compilation}.
4738 * Preprocessing Symbols::
4740 * Switches for gnatprep::
4741 * Form of Definitions File::
4742 * Form of Input Text for gnatprep::
4746 @node Preprocessing Symbols,Using gnatprep,,Preprocessing with gnatprep
4747 @anchor{gnat_ugn/the_gnat_compilation_model id55}@anchor{ac}@anchor{gnat_ugn/the_gnat_compilation_model preprocessing-symbols}@anchor{ad}
4748 @subsubsection Preprocessing Symbols
4751 Preprocessing symbols are defined in definition files and referred to in
4752 sources to be preprocessed. A Preprocessing symbol is an identifier, following
4753 normal Ada (case-insensitive) rules for its syntax, with the restriction that
4754 all characters need to be in the ASCII set (no accented letters).
4756 @node Using gnatprep,Switches for gnatprep,Preprocessing Symbols,Preprocessing with gnatprep
4757 @anchor{gnat_ugn/the_gnat_compilation_model using-gnatprep}@anchor{ae}@anchor{gnat_ugn/the_gnat_compilation_model id56}@anchor{af}
4758 @subsubsection Using @cite{gnatprep}
4761 To call @cite{gnatprep} use:
4764 $ gnatprep [`switches`] `infile` `outfile` [`deffile`]
4776 @item @emph{switches}
4778 is an optional sequence of switches as described in the next section.
4787 is the full name of the input file, which is an Ada source
4788 file containing preprocessor directives.
4795 @item @emph{outfile}
4797 is the full name of the output file, which is an Ada source
4798 in standard Ada form. When used with GNAT, this file name will
4799 normally have an ads or adb suffix.
4806 @item @emph{deffile}
4808 is the full name of a text file containing definitions of
4809 preprocessing symbols to be referenced by the preprocessor. This argument is
4810 optional, and can be replaced by the use of the @emph{-D} switch.
4814 @node Switches for gnatprep,Form of Definitions File,Using gnatprep,Preprocessing with gnatprep
4815 @anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatprep}@anchor{b0}@anchor{gnat_ugn/the_gnat_compilation_model id57}@anchor{b1}
4816 @subsubsection Switches for @cite{gnatprep}
4819 @geindex -b (gnatprep)
4826 Causes both preprocessor lines and the lines deleted by
4827 preprocessing to be replaced by blank lines in the output source file,
4828 preserving line numbers in the output file.
4831 @geindex -c (gnatprep)
4838 Causes both preprocessor lines and the lines deleted
4839 by preprocessing to be retained in the output source as comments marked
4840 with the special string @cite{"--! "}. This option will result in line numbers
4841 being preserved in the output file.
4844 @geindex -C (gnatprep)
4851 Causes comments to be scanned. Normally comments are ignored by gnatprep.
4852 If this option is specified, then comments are scanned and any $symbol
4853 substitutions performed as in program text. This is particularly useful
4854 when structured comments are used (e.g., when writing programs in the
4855 SPARK dialect of Ada). Note that this switch is not available when
4856 doing integrated preprocessing (it would be useless in this context
4857 since comments are ignored by the compiler in any case).
4860 @geindex -D (gnatprep)
4865 @item @code{-D@emph{symbol}=@emph{value}}
4867 Defines a new preprocessing symbol, associated with value. If no value is given
4868 on the command line, then symbol is considered to be @cite{True}. This switch
4869 can be used in place of a definition file.
4872 @geindex -r (gnatprep)
4879 Causes a @cite{Source_Reference} pragma to be generated that
4880 references the original input file, so that error messages will use
4881 the file name of this original file. The use of this switch implies
4882 that preprocessor lines are not to be removed from the file, so its
4883 use will force @emph{-b} mode if @emph{-c}
4884 has not been specified explicitly.
4886 Note that if the file to be preprocessed contains multiple units, then
4887 it will be necessary to @cite{gnatchop} the output file from
4888 @cite{gnatprep}. If a @cite{Source_Reference} pragma is present
4889 in the preprocessed file, it will be respected by
4891 so that the final chopped files will correctly refer to the original
4892 input source file for @cite{gnatprep}.
4895 @geindex -s (gnatprep)
4902 Causes a sorted list of symbol names and values to be
4903 listed on the standard output file.
4906 @geindex -u (gnatprep)
4913 Causes undefined symbols to be treated as having the value FALSE in the context
4914 of a preprocessor test. In the absence of this option, an undefined symbol in
4915 a @cite{#if} or @cite{#elsif} test will be treated as an error.
4918 Note: if neither @emph{-b} nor @emph{-c} is present,
4919 then preprocessor lines and
4920 deleted lines are completely removed from the output, unless -r is
4921 specified, in which case -b is assumed.
4923 @node Form of Definitions File,Form of Input Text for gnatprep,Switches for gnatprep,Preprocessing with gnatprep
4924 @anchor{gnat_ugn/the_gnat_compilation_model form-of-definitions-file}@anchor{b2}@anchor{gnat_ugn/the_gnat_compilation_model id58}@anchor{b3}
4925 @subsubsection Form of Definitions File
4928 The definitions file contains lines of the form:
4934 where @cite{symbol} is a preprocessing symbol, and @cite{value} is one of the following:
4940 Empty, corresponding to a null substitution,
4943 A string literal using normal Ada syntax, or
4946 Any sequence of characters from the set @{letters, digits, period, underline@}.
4949 Comment lines may also appear in the definitions file, starting with
4950 the usual @code{--},
4951 and comments may be added to the definitions lines.
4953 @node Form of Input Text for gnatprep,,Form of Definitions File,Preprocessing with gnatprep
4954 @anchor{gnat_ugn/the_gnat_compilation_model id59}@anchor{b4}@anchor{gnat_ugn/the_gnat_compilation_model form-of-input-text-for-gnatprep}@anchor{b5}
4955 @subsubsection Form of Input Text for @cite{gnatprep}
4958 The input text may contain preprocessor conditional inclusion lines,
4959 as well as general symbol substitution sequences.
4961 The preprocessor conditional inclusion commands have the form:
4964 #if <expression> [then]
4966 #elsif <expression> [then]
4968 #elsif <expression> [then]
4976 In this example, <expression> is defined by the following grammar:
4979 <expression> ::= <symbol>
4980 <expression> ::= <symbol> = "<value>"
4981 <expression> ::= <symbol> = <symbol>
4982 <expression> ::= <symbol> = <integer>
4983 <expression> ::= <symbol> > <integer>
4984 <expression> ::= <symbol> >= <integer>
4985 <expression> ::= <symbol> < <integer>
4986 <expression> ::= <symbol> <= <integer>
4987 <expression> ::= <symbol> 'Defined
4988 <expression> ::= not <expression>
4989 <expression> ::= <expression> and <expression>
4990 <expression> ::= <expression> or <expression>
4991 <expression> ::= <expression> and then <expression>
4992 <expression> ::= <expression> or else <expression>
4993 <expression> ::= ( <expression> )
4996 Note the following restriction: it is not allowed to have "and" or "or"
4997 following "not" in the same expression without parentheses. For example, this
5004 This can be expressed instead as one of the following forms:
5011 For the first test (<expression> ::= <symbol>) the symbol must have
5012 either the value true or false, that is to say the right-hand of the
5013 symbol definition must be one of the (case-insensitive) literals
5014 @cite{True} or @cite{False}. If the value is true, then the
5015 corresponding lines are included, and if the value is false, they are
5018 When comparing a symbol to an integer, the integer is any non negative
5019 literal integer as defined in the Ada Reference Manual, such as 3, 16#FF# or
5020 2#11#. The symbol value must also be a non negative integer. Integer values
5021 in the range 0 .. 2**31-1 are supported.
5023 The test (<expression> ::= <symbol>'Defined) is true only if
5024 the symbol has been defined in the definition file or by a @emph{-D}
5025 switch on the command line. Otherwise, the test is false.
5027 The equality tests are case insensitive, as are all the preprocessor lines.
5029 If the symbol referenced is not defined in the symbol definitions file,
5030 then the effect depends on whether or not switch @emph{-u}
5031 is specified. If so, then the symbol is treated as if it had the value
5032 false and the test fails. If this switch is not specified, then
5033 it is an error to reference an undefined symbol. It is also an error to
5034 reference a symbol that is defined with a value other than @cite{True}
5037 The use of the @cite{not} operator inverts the sense of this logical test.
5038 The @cite{not} operator cannot be combined with the @cite{or} or @cite{and}
5039 operators, without parentheses. For example, "if not X or Y then" is not
5040 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
5042 The @cite{then} keyword is optional as shown
5044 The @cite{#} must be the first non-blank character on a line, but
5045 otherwise the format is free form. Spaces or tabs may appear between
5046 the @cite{#} and the keyword. The keywords and the symbols are case
5047 insensitive as in normal Ada code. Comments may be used on a
5048 preprocessor line, but other than that, no other tokens may appear on a
5049 preprocessor line. Any number of @cite{elsif} clauses can be present,
5050 including none at all. The @cite{else} is optional, as in Ada.
5052 The @cite{#} marking the start of a preprocessor line must be the first
5053 non-blank character on the line, i.e., it must be preceded only by
5054 spaces or horizontal tabs.
5056 Symbol substitution outside of preprocessor lines is obtained by using
5063 anywhere within a source line, except in a comment or within a
5064 string literal. The identifier
5065 following the @cite{$} must match one of the symbols defined in the symbol
5066 definition file, and the result is to substitute the value of the
5067 symbol in place of @cite{$symbol} in the output file.
5069 Note that although the substitution of strings within a string literal
5070 is not possible, it is possible to have a symbol whose defined value is
5071 a string literal. So instead of setting XYZ to @cite{hello} and writing:
5074 Header : String := "$XYZ";
5077 you should set XYZ to @cite{"hello"} and write:
5080 Header : String := $XYZ;
5083 and then the substitution will occur as desired.
5085 @node Integrated Preprocessing,,Preprocessing with gnatprep,Conditional Compilation
5086 @anchor{gnat_ugn/the_gnat_compilation_model id60}@anchor{b6}@anchor{gnat_ugn/the_gnat_compilation_model integrated-preprocessing}@anchor{1a}
5087 @subsection Integrated Preprocessing
5090 GNAT sources may be preprocessed immediately before compilation.
5091 In this case, the actual
5092 text of the source is not the text of the source file, but is derived from it
5093 through a process called preprocessing. Integrated preprocessing is specified
5094 through switches @emph{-gnatep} and/or @emph{-gnateD}. @emph{-gnatep}
5095 indicates, through a text file, the preprocessing data to be used.
5096 @code{-gnateD} specifies or modifies the values of preprocessing symbol.
5097 Note that integrated preprocessing applies only to Ada source files, it is
5098 not available for configuration pragma files.
5100 Note that when integrated preprocessing is used, the output from the
5101 preprocessor is not written to any external file. Instead it is passed
5102 internally to the compiler. If you need to preserve the result of
5103 preprocessing in a file, then you should use @emph{gnatprep}
5104 to perform the desired preprocessing in stand-alone mode.
5106 It is recommended that @emph{gnatmake} switch -s should be
5107 used when Integrated Preprocessing is used. The reason is that preprocessing
5108 with another Preprocessing Data file without changing the sources will
5109 not trigger recompilation without this switch.
5111 Note that @emph{gnatmake} switch -m will almost
5112 always trigger recompilation for sources that are preprocessed,
5113 because @emph{gnatmake} cannot compute the checksum of the source after
5116 The actual preprocessing function is described in detail in section
5117 @ref{19,,Preprocessing with gnatprep}. This section only describes how integrated
5118 preprocessing is triggered and parameterized.
5120 @geindex -gnatep (gcc)
5125 @item @code{-gnatep=@emph{file}}
5127 This switch indicates to the compiler the file name (without directory
5128 information) of the preprocessor data file to use. The preprocessor data file
5129 should be found in the source directories. Note that when the compiler is
5130 called by a builder such as (@emph{gnatmake} with a project
5131 file, if the object directory is not also a source directory, the builder needs
5132 to be called with @emph{-x}.
5134 A preprocessing data file is a text file with significant lines indicating
5135 how should be preprocessed either a specific source or all sources not
5136 mentioned in other lines. A significant line is a nonempty, non-comment line.
5137 Comments are similar to Ada comments.
5139 Each significant line starts with either a literal string or the character '*'.
5140 A literal string is the file name (without directory information) of the source
5141 to preprocess. A character '*' indicates the preprocessing for all the sources
5142 that are not specified explicitly on other lines (order of the lines is not
5143 significant). It is an error to have two lines with the same file name or two
5144 lines starting with the character '*'.
5146 After the file name or the character '*', another optional literal string
5147 indicating the file name of the definition file to be used for preprocessing
5148 (@ref{b2,,Form of Definitions File}). The definition files are found by the
5149 compiler in one of the source directories. In some cases, when compiling
5150 a source in a directory other than the current directory, if the definition
5151 file is in the current directory, it may be necessary to add the current
5152 directory as a source directory through switch -I., otherwise
5153 the compiler would not find the definition file.
5155 Then, optionally, switches similar to those of @cite{gnatprep} may
5156 be found. Those switches are:
5163 Causes both preprocessor lines and the lines deleted by
5164 preprocessing to be replaced by blank lines, preserving the line number.
5165 This switch is always implied; however, if specified after @emph{-c}
5166 it cancels the effect of @emph{-c}.
5170 Causes both preprocessor lines and the lines deleted
5171 by preprocessing to be retained as comments marked
5172 with the special string '@cite{--!}'.
5174 @item @code{-Dsymbol=@emph{value}}
5176 Define or redefine a symbol, associated with value. A symbol is an Ada
5177 identifier, or an Ada reserved word, with the exception of @cite{if},
5178 @cite{else}, @cite{elsif}, @cite{end}, @cite{and}, @cite{or} and @cite{then}.
5179 @cite{value} is either a literal string, an Ada identifier or any Ada reserved
5180 word. A symbol declared with this switch replaces a symbol with the
5181 same name defined in a definition file.
5185 Causes a sorted list of symbol names and values to be
5186 listed on the standard output file.
5190 Causes undefined symbols to be treated as having the value @cite{FALSE}
5192 of a preprocessor test. In the absence of this option, an undefined symbol in
5193 a @cite{#if} or @cite{#elsif} test will be treated as an error.
5196 Examples of valid lines in a preprocessor data file:
5199 "toto.adb" "prep.def" -u
5200 -- preprocess "toto.adb", using definition file "prep.def",
5201 -- undefined symbol are False.
5204 -- preprocess all other sources without a definition file;
5205 -- suppressed lined are commented; symbol VERSION has the value V101.
5207 "titi.adb" "prep2.def" -s
5208 -- preprocess "titi.adb", using definition file "prep2.def";
5209 -- list all symbols with their values.
5213 @geindex -gnateD (gcc)
5218 @item @code{-gnateDsymbol[=value]}
5220 Define or redefine a preprocessing symbol, associated with value. If no value
5221 is given on the command line, then the value of the symbol is @cite{True}.
5222 A symbol is an identifier, following normal Ada (case-insensitive)
5223 rules for its syntax, and value is either an arbitrary string between double
5224 quotes or any sequence (including an empty sequence) of characters from the
5225 set (letters, digits, period, underline).
5226 Ada reserved words may be used as symbols, with the exceptions of @cite{if},
5227 @cite{else}, @cite{elsif}, @cite{end}, @cite{and}, @cite{or} and @cite{then}.
5234 -gnateDFoo=\"Foo-Bar\"
5237 A symbol declared with this switch on the command line replaces a
5238 symbol with the same name either in a definition file or specified with a
5239 switch -D in the preprocessor data file.
5241 This switch is similar to switch @emph{-D} of @cite{gnatprep}.
5243 @item @code{-gnateG}
5245 When integrated preprocessing is performed and the preprocessor modifies
5246 the source text, write the result of this preprocessing into a file
5250 @node Mixed Language Programming,GNAT and Other Compilation Models,Conditional Compilation,The GNAT Compilation Model
5251 @anchor{gnat_ugn/the_gnat_compilation_model mixed-language-programming}@anchor{46}@anchor{gnat_ugn/the_gnat_compilation_model id61}@anchor{b7}
5252 @section Mixed Language Programming
5255 @geindex Mixed Language Programming
5257 This section describes how to develop a mixed-language program,
5258 with a focus on combining Ada with C or C++.
5261 * Interfacing to C::
5262 * Calling Conventions::
5263 * Building Mixed Ada and C++ Programs::
5264 * Generating Ada Bindings for C and C++ headers::
5268 @node Interfacing to C,Calling Conventions,,Mixed Language Programming
5269 @anchor{gnat_ugn/the_gnat_compilation_model interfacing-to-c}@anchor{b8}@anchor{gnat_ugn/the_gnat_compilation_model id62}@anchor{b9}
5270 @subsection Interfacing to C
5273 Interfacing Ada with a foreign language such as C involves using
5274 compiler directives to import and/or export entity definitions in each
5275 language -- using @cite{extern} statements in C, for instance, and the
5276 @cite{Import}, @cite{Export}, and @cite{Convention} pragmas in Ada.
5277 A full treatment of these topics is provided in Appendix B, section 1
5278 of the Ada Reference Manual.
5280 There are two ways to build a program using GNAT that contains some Ada
5281 sources and some foreign language sources, depending on whether or not
5282 the main subprogram is written in Ada. Here is a source example with
5283 the main subprogram in Ada:
5289 void print_num (int num)
5291 printf ("num is %d.\\n", num);
5299 /* num_from_Ada is declared in my_main.adb */
5300 extern int num_from_Ada;
5304 return num_from_Ada;
5310 procedure My_Main is
5312 -- Declare then export an Integer entity called num_from_Ada
5313 My_Num : Integer := 10;
5314 pragma Export (C, My_Num, "num_from_Ada");
5316 -- Declare an Ada function spec for Get_Num, then use
5317 -- C function get_num for the implementation.
5318 function Get_Num return Integer;
5319 pragma Import (C, Get_Num, "get_num");
5321 -- Declare an Ada procedure spec for Print_Num, then use
5322 -- C function print_num for the implementation.
5323 procedure Print_Num (Num : Integer);
5324 pragma Import (C, Print_Num, "print_num";
5327 Print_Num (Get_Num);
5331 To build this example:
5337 First compile the foreign language files to
5338 generate object files:
5346 Then, compile the Ada units to produce a set of object files and ALI
5350 $ gnatmake -c my_main.adb
5354 Run the Ada binder on the Ada main program:
5357 $ gnatbind my_main.ali
5361 Link the Ada main program, the Ada objects and the other language
5365 $ gnatlink my_main.ali file1.o file2.o
5369 The last three steps can be grouped in a single command:
5372 $ gnatmake my_main.adb -largs file1.o file2.o
5375 @geindex Binder output file
5377 If the main program is in a language other than Ada, then you may have
5378 more than one entry point into the Ada subsystem. You must use a special
5379 binder option to generate callable routines that initialize and
5380 finalize the Ada units (@ref{ba,,Binding with Non-Ada Main Programs}).
5381 Calls to the initialization and finalization routines must be inserted
5382 in the main program, or some other appropriate point in the code. The
5383 call to initialize the Ada units must occur before the first Ada
5384 subprogram is called, and the call to finalize the Ada units must occur
5385 after the last Ada subprogram returns. The binder will place the
5386 initialization and finalization subprograms into the
5387 @code{b~xxx.adb} file where they can be accessed by your C
5388 sources. To illustrate, we have the following example:
5392 extern void adainit (void);
5393 extern void adafinal (void);
5394 extern int add (int, int);
5395 extern int sub (int, int);
5397 int main (int argc, char *argv[])
5403 /* Should print "21 + 7 = 28" */
5404 printf ("%d + %d = %d\\n", a, b, add (a, b));
5406 /* Should print "21 - 7 = 14" */
5407 printf ("%d - %d = %d\\n", a, b, sub (a, b));
5416 function Add (A, B : Integer) return Integer;
5417 pragma Export (C, Add, "add");
5423 package body Unit1 is
5424 function Add (A, B : Integer) return Integer is
5434 function Sub (A, B : Integer) return Integer;
5435 pragma Export (C, Sub, "sub");
5441 package body Unit2 is
5442 function Sub (A, B : Integer) return Integer is
5449 The build procedure for this application is similar to the last
5456 First, compile the foreign language files to generate object files:
5463 Next, compile the Ada units to produce a set of object files and ALI
5467 $ gnatmake -c unit1.adb
5468 $ gnatmake -c unit2.adb
5472 Run the Ada binder on every generated ALI file. Make sure to use the
5473 @code{-n} option to specify a foreign main program:
5476 $ gnatbind -n unit1.ali unit2.ali
5480 Link the Ada main program, the Ada objects and the foreign language
5481 objects. You need only list the last ALI file here:
5484 $ gnatlink unit2.ali main.o -o exec_file
5487 This procedure yields a binary executable called @code{exec_file}.
5490 Depending on the circumstances (for example when your non-Ada main object
5491 does not provide symbol @cite{main}), you may also need to instruct the
5492 GNAT linker not to include the standard startup objects by passing the
5493 @code{-nostartfiles} switch to @cite{gnatlink}.
5495 @node Calling Conventions,Building Mixed Ada and C++ Programs,Interfacing to C,Mixed Language Programming
5496 @anchor{gnat_ugn/the_gnat_compilation_model calling-conventions}@anchor{bb}@anchor{gnat_ugn/the_gnat_compilation_model id63}@anchor{bc}
5497 @subsection Calling Conventions
5500 @geindex Foreign Languages
5502 @geindex Calling Conventions
5504 GNAT follows standard calling sequence conventions and will thus interface
5505 to any other language that also follows these conventions. The following
5506 Convention identifiers are recognized by GNAT:
5508 @geindex Interfacing to Ada
5510 @geindex Other Ada compilers
5512 @geindex Convention Ada
5519 This indicates that the standard Ada calling sequence will be
5520 used and all Ada data items may be passed without any limitations in the
5521 case where GNAT is used to generate both the caller and callee. It is also
5522 possible to mix GNAT generated code and code generated by another Ada
5523 compiler. In this case, the data types should be restricted to simple
5524 cases, including primitive types. Whether complex data types can be passed
5525 depends on the situation. Probably it is safe to pass simple arrays, such
5526 as arrays of integers or floats. Records may or may not work, depending
5527 on whether both compilers lay them out identically. Complex structures
5528 involving variant records, access parameters, tasks, or protected types,
5529 are unlikely to be able to be passed.
5531 Note that in the case of GNAT running
5532 on a platform that supports HP Ada 83, a higher degree of compatibility
5533 can be guaranteed, and in particular records are laid out in an identical
5534 manner in the two compilers. Note also that if output from two different
5535 compilers is mixed, the program is responsible for dealing with elaboration
5536 issues. Probably the safest approach is to write the main program in the
5537 version of Ada other than GNAT, so that it takes care of its own elaboration
5538 requirements, and then call the GNAT-generated adainit procedure to ensure
5539 elaboration of the GNAT components. Consult the documentation of the other
5540 Ada compiler for further details on elaboration.
5542 However, it is not possible to mix the tasking run time of GNAT and
5543 HP Ada 83, All the tasking operations must either be entirely within
5544 GNAT compiled sections of the program, or entirely within HP Ada 83
5545 compiled sections of the program.
5548 @geindex Interfacing to Assembly
5550 @geindex Convention Assembler
5555 @item @emph{Assembler}
5557 Specifies assembler as the convention. In practice this has the
5558 same effect as convention Ada (but is not equivalent in the sense of being
5559 considered the same convention).
5562 @geindex Convention Asm
5571 Equivalent to Assembler.
5573 @geindex Interfacing to COBOL
5575 @geindex Convention COBOL
5585 Data will be passed according to the conventions described
5586 in section B.4 of the Ada Reference Manual.
5591 @geindex Interfacing to C
5593 @geindex Convention C
5600 Data will be passed according to the conventions described
5601 in section B.3 of the Ada Reference Manual.
5603 A note on interfacing to a C 'varargs' function:
5607 @geindex C varargs function
5609 @geindex Interfacing to C varargs function
5611 @geindex varargs function interfaces
5613 In C, @cite{varargs} allows a function to take a variable number of
5614 arguments. There is no direct equivalent in this to Ada. One
5615 approach that can be used is to create a C wrapper for each
5616 different profile and then interface to this C wrapper. For
5617 example, to print an @cite{int} value using @cite{printf},
5618 create a C function @cite{printfi} that takes two arguments, a
5619 pointer to a string and an int, and calls @cite{printf}.
5620 Then in the Ada program, use pragma @cite{Import} to
5621 interface to @cite{printfi}.
5623 It may work on some platforms to directly interface to
5624 a @cite{varargs} function by providing a specific Ada profile
5625 for a particular call. However, this does not work on
5626 all platforms, since there is no guarantee that the
5627 calling sequence for a two argument normal C function
5628 is the same as for calling a @cite{varargs} C function with
5629 the same two arguments.
5633 @geindex Convention Default
5640 @item @emph{Default}
5645 @geindex Convention External
5652 @item @emph{External}
5659 @geindex Interfacing to C++
5661 @geindex Convention C++
5666 @item @emph{C_Plus_Plus (or CPP)}
5668 This stands for C++. For most purposes this is identical to C.
5669 See the separate description of the specialized GNAT pragmas relating to
5670 C++ interfacing for further details.
5675 @geindex Interfacing to Fortran
5677 @geindex Convention Fortran
5682 @item @emph{Fortran}
5684 Data will be passed according to the conventions described
5685 in section B.5 of the Ada Reference Manual.
5687 @item @emph{Intrinsic}
5689 This applies to an intrinsic operation, as defined in the Ada
5690 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
5691 this means that the body of the subprogram is provided by the compiler itself,
5692 usually by means of an efficient code sequence, and that the user does not
5693 supply an explicit body for it. In an application program, the pragma may
5694 be applied to the following sets of names:
5700 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_Arithmetic.
5701 The corresponding subprogram declaration must have
5702 two formal parameters. The
5703 first one must be a signed integer type or a modular type with a binary
5704 modulus, and the second parameter must be of type Natural.
5705 The return type must be the same as the type of the first argument. The size
5706 of this type can only be 8, 16, 32, or 64.
5709 Binary arithmetic operators: '+', '-', '*', '/'.
5710 The corresponding operator declaration must have parameters and result type
5711 that have the same root numeric type (for example, all three are long_float
5712 types). This simplifies the definition of operations that use type checking
5713 to perform dimensional checks:
5718 @c type Distance is new Long_Float;
5719 @c type Time is new Long_Float;
5720 @c type Velocity is new Long_Float;
5721 @c function "/" (D : Distance; T : Time)
5723 @c pragma Import (Intrinsic, "/");
5725 @c This common idiom is often programmed with a generic definition and an
5726 @c explicit body. The pragma makes it simpler to introduce such declarations.
5727 @c It incurs no overhead in compilation time or code size, because it is
5728 @c implemented as a single machine instruction.
5734 General subprogram entities. This is used to bind an Ada subprogram
5736 a compiler builtin by name with back-ends where such interfaces are
5737 available. A typical example is the set of @cite{__builtin} functions
5738 exposed by the GCC back-end, as in the following example:
5741 function builtin_sqrt (F : Float) return Float;
5742 pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
5745 Most of the GCC builtins are accessible this way, and as for other
5746 import conventions (e.g. C), it is the user's responsibility to ensure
5747 that the Ada subprogram profile matches the underlying builtin
5754 @geindex Convention Stdcall
5759 @item @emph{Stdcall}
5761 This is relevant only to Windows XP/2000/NT implementations of GNAT,
5762 and specifies that the @cite{Stdcall} calling sequence will be used,
5763 as defined by the NT API. Nevertheless, to ease building
5764 cross-platform bindings this convention will be handled as a @cite{C} calling
5765 convention on non-Windows platforms.
5770 @geindex Convention DLL
5777 This is equivalent to @cite{Stdcall}.
5782 @geindex Convention Win32
5789 This is equivalent to @cite{Stdcall}.
5794 @geindex Convention Stubbed
5799 @item @emph{Stubbed}
5801 This is a special convention that indicates that the compiler
5802 should provide a stub body that raises @cite{Program_Error}.
5805 GNAT additionally provides a useful pragma @cite{Convention_Identifier}
5806 that can be used to parameterize conventions and allow additional synonyms
5807 to be specified. For example if you have legacy code in which the convention
5808 identifier Fortran77 was used for Fortran, you can use the configuration
5812 pragma Convention_Identifier (Fortran77, Fortran);
5815 And from now on the identifier Fortran77 may be used as a convention
5816 identifier (for example in an @cite{Import} pragma) with the same
5819 @node Building Mixed Ada and C++ Programs,Generating Ada Bindings for C and C++ headers,Calling Conventions,Mixed Language Programming
5820 @anchor{gnat_ugn/the_gnat_compilation_model id64}@anchor{bd}@anchor{gnat_ugn/the_gnat_compilation_model building-mixed-ada-and-c-programs}@anchor{be}
5821 @subsection Building Mixed Ada and C++ Programs
5824 A programmer inexperienced with mixed-language development may find that
5825 building an application containing both Ada and C++ code can be a
5826 challenge. This section gives a few hints that should make this task easier.
5829 * Interfacing to C++::
5830 * Linking a Mixed C++ & Ada Program::
5831 * A Simple Example::
5832 * Interfacing with C++ constructors::
5833 * Interfacing with C++ at the Class Level::
5837 @node Interfacing to C++,Linking a Mixed C++ & Ada Program,,Building Mixed Ada and C++ Programs
5838 @anchor{gnat_ugn/the_gnat_compilation_model id65}@anchor{bf}@anchor{gnat_ugn/the_gnat_compilation_model id66}@anchor{c0}
5839 @subsubsection Interfacing to C++
5842 GNAT supports interfacing with the G++ compiler (or any C++ compiler
5843 generating code that is compatible with the G++ Application Binary
5844 Interface ---see @indicateurl{http://www.codesourcery.com/archives/cxx-abi}).
5846 Interfacing can be done at 3 levels: simple data, subprograms, and
5847 classes. In the first two cases, GNAT offers a specific @cite{Convention C_Plus_Plus}
5848 (or @cite{CPP}) that behaves exactly like @cite{Convention C}.
5849 Usually, C++ mangles the names of subprograms. To generate proper mangled
5850 names automatically, see @ref{1b,,Generating Ada Bindings for C and C++ headers}).
5851 This problem can also be addressed manually in two ways:
5857 by modifying the C++ code in order to force a C convention using
5858 the @cite{extern "C"} syntax.
5861 by figuring out the mangled name (using e.g. @emph{nm}) and using it as the
5862 Link_Name argument of the pragma import.
5865 Interfacing at the class level can be achieved by using the GNAT specific
5866 pragmas such as @cite{CPP_Constructor}. See the @cite{GNAT_Reference_Manual} for additional information.
5868 @node Linking a Mixed C++ & Ada Program,A Simple Example,Interfacing to C++,Building Mixed Ada and C++ Programs
5869 @anchor{gnat_ugn/the_gnat_compilation_model linking-a-mixed-c-ada-program}@anchor{c1}@anchor{gnat_ugn/the_gnat_compilation_model linking-a-mixed-c-and-ada-program}@anchor{c2}
5870 @subsubsection Linking a Mixed C++ & Ada Program
5873 Usually the linker of the C++ development system must be used to link
5874 mixed applications because most C++ systems will resolve elaboration
5875 issues (such as calling constructors on global class instances)
5876 transparently during the link phase. GNAT has been adapted to ease the
5877 use of a foreign linker for the last phase. Three cases can be
5884 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
5885 The C++ linker can simply be called by using the C++ specific driver
5888 Note that if the C++ code uses inline functions, you will need to
5889 compile your C++ code with the @cite{-fkeep-inline-functions} switch in
5890 order to provide an existing function implementation that the Ada code can
5894 $ g++ -c -fkeep-inline-functions file1.C
5895 $ g++ -c -fkeep-inline-functions file2.C
5896 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
5900 Using GNAT and G++ from two different GCC installations: If both
5901 compilers are on the :envvar`PATH`, the previous method may be used. It is
5902 important to note that environment variables such as
5903 @geindex C_INCLUDE_PATH
5904 @geindex environment variable; C_INCLUDE_PATH
5905 @code{C_INCLUDE_PATH},
5906 @geindex GCC_EXEC_PREFIX
5907 @geindex environment variable; GCC_EXEC_PREFIX
5908 @code{GCC_EXEC_PREFIX},
5909 @geindex BINUTILS_ROOT
5910 @geindex environment variable; BINUTILS_ROOT
5911 @code{BINUTILS_ROOT}, and
5913 @geindex environment variable; GCC_ROOT
5914 @code{GCC_ROOT} will affect both compilers
5915 at the same time and may make one of the two compilers operate
5916 improperly if set during invocation of the wrong compiler. It is also
5917 very important that the linker uses the proper @code{libgcc.a} GCC
5918 library -- that is, the one from the C++ compiler installation. The
5919 implicit link command as suggested in the @cite{gnatmake} command
5920 from the former example can be replaced by an explicit link command with
5921 the full-verbosity option in order to verify which library is used:
5925 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
5928 If there is a problem due to interfering environment variables, it can
5929 be worked around by using an intermediate script. The following example
5930 shows the proper script to use when GNAT has not been installed at its
5931 default location and g++ has been installed at its default location:
5939 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
5943 Using a non-GNU C++ compiler: The commands previously described can be
5944 used to insure that the C++ linker is used. Nonetheless, you need to add
5945 a few more parameters to the link command line, depending on the exception
5948 If the @cite{setjmp/longjmp} exception mechanism is used, only the paths
5949 to the libgcc libraries are required:
5954 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
5955 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
5958 where CC is the name of the non-GNU C++ compiler.
5960 If the @cite{zero cost} exception mechanism is used, and the platform
5961 supports automatic registration of exception tables (e.g., Solaris),
5962 paths to more objects are required:
5967 CC `gcc -print-file-name=crtbegin.o` $* \\
5968 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \\
5969 `gcc -print-file-name=crtend.o`
5970 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
5973 If the "zero cost exception" mechanism is used, and the platform
5974 doesn't support automatic registration of exception tables (e.g., HP-UX
5975 or AIX), the simple approach described above will not work and
5976 a pre-linking phase using GNAT will be necessary.
5979 Another alternative is to use the @code{gprbuild} multi-language builder
5980 which has a large knowledge base and knows how to link Ada and C++ code
5981 together automatically in most cases.
5983 @node A Simple Example,Interfacing with C++ constructors,Linking a Mixed C++ & Ada Program,Building Mixed Ada and C++ Programs
5984 @anchor{gnat_ugn/the_gnat_compilation_model id67}@anchor{c3}@anchor{gnat_ugn/the_gnat_compilation_model a-simple-example}@anchor{c4}
5985 @subsubsection A Simple Example
5988 The following example, provided as part of the GNAT examples, shows how
5989 to achieve procedural interfacing between Ada and C++ in both
5990 directions. The C++ class A has two methods. The first method is exported
5991 to Ada by the means of an extern C wrapper function. The second method
5992 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
5993 a limited record with a layout comparable to the C++ class. The Ada
5994 subprogram, in turn, calls the C++ method. So, starting from the C++
5995 main program, the process passes back and forth between the two
5998 Here are the compilation commands:
6001 $ gnatmake -c simple_cpp_interface
6004 $ gnatbind -n simple_cpp_interface
6005 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++ -lstdc++ ex7.o cpp_main.o
6008 Here are the corresponding sources:
6016 void adainit (void);
6017 void adafinal (void);
6018 void method1 (A *t);
6042 class A : public Origin @{
6044 void method1 (void);
6045 void method2 (int v);
6057 extern "C" @{ void ada_method2 (A *t, int v);@}
6059 void A::method1 (void)
6062 printf ("in A::method1, a_value = %d \\n",a_value);
6065 void A::method2 (int v)
6067 ada_method2 (this, v);
6068 printf ("in A::method2, a_value = %d \\n",a_value);
6074 printf ("in A::A, a_value = %d \\n",a_value);
6079 -- simple_cpp_interface.ads
6081 package Simple_Cpp_Interface is
6084 Vptr : System.Address;
6088 pragma Convention (C, A);
6090 procedure Method1 (This : in out A);
6091 pragma Import (C, Method1);
6093 procedure Ada_Method2 (This : in out A; V : Integer);
6094 pragma Export (C, Ada_Method2);
6096 end Simple_Cpp_Interface;
6100 -- simple_cpp_interface.adb
6101 package body Simple_Cpp_Interface is
6103 procedure Ada_Method2 (This : in out A; V : Integer) is
6109 end Simple_Cpp_Interface;
6112 @node Interfacing with C++ constructors,Interfacing with C++ at the Class Level,A Simple Example,Building Mixed Ada and C++ Programs
6113 @anchor{gnat_ugn/the_gnat_compilation_model id68}@anchor{c5}@anchor{gnat_ugn/the_gnat_compilation_model interfacing-with-c-constructors}@anchor{c6}
6114 @subsubsection Interfacing with C++ constructors
6117 In order to interface with C++ constructors GNAT provides the
6118 @cite{pragma CPP_Constructor} (see the @cite{GNAT_Reference_Manual}
6119 for additional information).
6120 In this section we present some common uses of C++ constructors
6121 in mixed-languages programs in GNAT.
6123 Let us assume that we need to interface with the following
6131 virtual int Get_Value ();
6132 Root(); // Default constructor
6133 Root(int v); // 1st non-default constructor
6134 Root(int v, int w); // 2nd non-default constructor
6138 For this purpose we can write the following package spec (further
6139 information on how to build this spec is available in
6140 @ref{c7,,Interfacing with C++ at the Class Level} and
6141 @ref{1b,,Generating Ada Bindings for C and C++ headers}).
6144 with Interfaces.C; use Interfaces.C;
6146 type Root is tagged limited record
6150 pragma Import (CPP, Root);
6152 function Get_Value (Obj : Root) return int;
6153 pragma Import (CPP, Get_Value);
6155 function Constructor return Root;
6156 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
6158 function Constructor (v : Integer) return Root;
6159 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
6161 function Constructor (v, w : Integer) return Root;
6162 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
6166 On the Ada side the constructor is represented by a function (whose
6167 name is arbitrary) that returns the classwide type corresponding to
6168 the imported C++ class. Although the constructor is described as a
6169 function, it is typically a procedure with an extra implicit argument
6170 (the object being initialized) at the implementation level. GNAT
6171 issues the appropriate call, whatever it is, to get the object
6172 properly initialized.
6174 Constructors can only appear in the following contexts:
6180 On the right side of an initialization of an object of type @cite{T}.
6183 On the right side of an initialization of a record component of type @cite{T}.
6186 In an Ada 2005 limited aggregate.
6189 In an Ada 2005 nested limited aggregate.
6192 In an Ada 2005 limited aggregate that initializes an object built in
6193 place by an extended return statement.
6196 In a declaration of an object whose type is a class imported from C++,
6197 either the default C++ constructor is implicitly called by GNAT, or
6198 else the required C++ constructor must be explicitly called in the
6199 expression that initializes the object. For example:
6203 Obj2 : Root := Constructor;
6204 Obj3 : Root := Constructor (v => 10);
6205 Obj4 : Root := Constructor (30, 40);
6208 The first two declarations are equivalent: in both cases the default C++
6209 constructor is invoked (in the former case the call to the constructor is
6210 implicit, and in the latter case the call is explicit in the object
6211 declaration). @cite{Obj3} is initialized by the C++ non-default constructor
6212 that takes an integer argument, and @cite{Obj4} is initialized by the
6213 non-default C++ constructor that takes two integers.
6215 Let us derive the imported C++ class in the Ada side. For example:
6218 type DT is new Root with record
6219 C_Value : Natural := 2009;
6223 In this case the components DT inherited from the C++ side must be
6224 initialized by a C++ constructor, and the additional Ada components
6225 of type DT are initialized by GNAT. The initialization of such an
6226 object is done either by default, or by means of a function returning
6227 an aggregate of type DT, or by means of an extension aggregate.
6231 Obj6 : DT := Function_Returning_DT (50);
6232 Obj7 : DT := (Constructor (30,40) with C_Value => 50);
6235 The declaration of @cite{Obj5} invokes the default constructors: the
6236 C++ default constructor of the parent type takes care of the initialization
6237 of the components inherited from Root, and GNAT takes care of the default
6238 initialization of the additional Ada components of type DT (that is,
6239 @cite{C_Value} is initialized to value 2009). The order of invocation of
6240 the constructors is consistent with the order of elaboration required by
6241 Ada and C++. That is, the constructor of the parent type is always called
6242 before the constructor of the derived type.
6244 Let us now consider a record that has components whose type is imported
6245 from C++. For example:
6248 type Rec1 is limited record
6249 Data1 : Root := Constructor (10);
6250 Value : Natural := 1000;
6253 type Rec2 (D : Integer := 20) is limited record
6255 Data2 : Root := Constructor (D, 30);
6259 The initialization of an object of type @cite{Rec2} will call the
6260 non-default C++ constructors specified for the imported components.
6267 Using Ada 2005 we can use limited aggregates to initialize an object
6268 invoking C++ constructors that differ from those specified in the type
6269 declarations. For example:
6272 Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
6277 The above declaration uses an Ada 2005 limited aggregate to
6278 initialize @cite{Obj9}, and the C++ constructor that has two integer
6279 arguments is invoked to initialize the @cite{Data1} component instead
6280 of the constructor specified in the declaration of type @cite{Rec1}. In
6281 Ada 2005 the box in the aggregate indicates that unspecified components
6282 are initialized using the expression (if any) available in the component
6283 declaration. That is, in this case discriminant @cite{D} is initialized
6284 to value @cite{20}, @cite{Value} is initialized to value 1000, and the
6285 non-default C++ constructor that handles two integers takes care of
6286 initializing component @cite{Data2} with values @cite{20@comma{}30}.
6288 In Ada 2005 we can use the extended return statement to build the Ada
6289 equivalent to C++ non-default constructors. For example:
6292 function Constructor (V : Integer) return Rec2 is
6294 return Obj : Rec2 := (Rec => (Data1 => Constructor (V, 20),
6297 -- Further actions required for construction of
6298 -- objects of type Rec2
6304 In this example the extended return statement construct is used to
6305 build in place the returned object whose components are initialized
6306 by means of a limited aggregate. Any further action associated with
6307 the constructor can be placed inside the construct.
6309 @node Interfacing with C++ at the Class Level,,Interfacing with C++ constructors,Building Mixed Ada and C++ Programs
6310 @anchor{gnat_ugn/the_gnat_compilation_model interfacing-with-c-at-the-class-level}@anchor{c7}@anchor{gnat_ugn/the_gnat_compilation_model id69}@anchor{c8}
6311 @subsubsection Interfacing with C++ at the Class Level
6314 In this section we demonstrate the GNAT features for interfacing with
6315 C++ by means of an example making use of Ada 2005 abstract interface
6316 types. This example consists of a classification of animals; classes
6317 have been used to model our main classification of animals, and
6318 interfaces provide support for the management of secondary
6319 classifications. We first demonstrate a case in which the types and
6320 constructors are defined on the C++ side and imported from the Ada
6321 side, and latter the reverse case.
6323 The root of our derivation will be the @cite{Animal} class, with a
6324 single private attribute (the @cite{Age} of the animal), a constructor,
6325 and two public primitives to set and get the value of this attribute.
6330 virtual void Set_Age (int New_Age);
6332 Animal() @{Age_Count = 0;@};
6338 Abstract interface types are defined in C++ by means of classes with pure
6339 virtual functions and no data members. In our example we will use two
6340 interfaces that provide support for the common management of @cite{Carnivore}
6341 and @cite{Domestic} animals:
6346 virtual int Number_Of_Teeth () = 0;
6351 virtual void Set_Owner (char* Name) = 0;
6355 Using these declarations, we can now say that a @cite{Dog} is an animal that is
6356 both Carnivore and Domestic, that is:
6359 class Dog : Animal, Carnivore, Domestic @{
6361 virtual int Number_Of_Teeth ();
6362 virtual void Set_Owner (char* Name);
6364 Dog(); // Constructor
6371 In the following examples we will assume that the previous declarations are
6372 located in a file named @cite{animals.h}. The following package demonstrates
6373 how to import these C++ declarations from the Ada side:
6376 with Interfaces.C.Strings; use Interfaces.C.Strings;
6378 type Carnivore is limited interface;
6379 pragma Convention (C_Plus_Plus, Carnivore);
6380 function Number_Of_Teeth (X : Carnivore)
6381 return Natural is abstract;
6383 type Domestic is limited interface;
6384 pragma Convention (C_Plus_Plus, Domestic);
6386 (X : in out Domestic;
6387 Name : Chars_Ptr) is abstract;
6389 type Animal is tagged limited record
6392 pragma Import (C_Plus_Plus, Animal);
6394 procedure Set_Age (X : in out Animal; Age : Integer);
6395 pragma Import (C_Plus_Plus, Set_Age);
6397 function Age (X : Animal) return Integer;
6398 pragma Import (C_Plus_Plus, Age);
6400 function New_Animal return Animal;
6401 pragma CPP_Constructor (New_Animal);
6402 pragma Import (CPP, New_Animal, "_ZN6AnimalC1Ev");
6404 type Dog is new Animal and Carnivore and Domestic with record
6405 Tooth_Count : Natural;
6406 Owner : String (1 .. 30);
6408 pragma Import (C_Plus_Plus, Dog);
6410 function Number_Of_Teeth (A : Dog) return Natural;
6411 pragma Import (C_Plus_Plus, Number_Of_Teeth);
6413 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
6414 pragma Import (C_Plus_Plus, Set_Owner);
6416 function New_Dog return Dog;
6417 pragma CPP_Constructor (New_Dog);
6418 pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
6422 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
6423 interfacing with these C++ classes is easy. The only requirement is that all
6424 the primitives and components must be declared exactly in the same order in
6427 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
6428 means of a @cite{pragma Convention (C_Plus_Plus)}, the convention used to pass
6429 the arguments to the called primitives will be the same as for C++. For the
6430 imported classes we use @cite{pragma Import} with convention @cite{C_Plus_Plus}
6431 to indicate that they have been defined on the C++ side; this is required
6432 because the dispatch table associated with these tagged types will be built
6433 in the C++ side and therefore will not contain the predefined Ada primitives
6434 which Ada would otherwise expect.
6436 As the reader can see there is no need to indicate the C++ mangled names
6437 associated with each subprogram because it is assumed that all the calls to
6438 these primitives will be dispatching calls. The only exception is the
6439 constructor, which must be registered with the compiler by means of
6440 @cite{pragma CPP_Constructor} and needs to provide its associated C++
6441 mangled name because the Ada compiler generates direct calls to it.
6443 With the above packages we can now declare objects of type Dog on the Ada side
6444 and dispatch calls to the corresponding subprograms on the C++ side. We can
6445 also extend the tagged type Dog with further fields and primitives, and
6446 override some of its C++ primitives on the Ada side. For example, here we have
6447 a type derivation defined on the Ada side that inherits all the dispatching
6448 primitives of the ancestor from the C++ side.
6451 with Animals; use Animals;
6452 package Vaccinated_Animals is
6453 type Vaccinated_Dog is new Dog with null record;
6454 function Vaccination_Expired (A : Vaccinated_Dog) return Boolean;
6455 end Vaccinated_Animals;
6458 It is important to note that, because of the ABI compatibility, the programmer
6459 does not need to add any further information to indicate either the object
6460 layout or the dispatch table entry associated with each dispatching operation.
6462 Now let us define all the types and constructors on the Ada side and export
6463 them to C++, using the same hierarchy of our previous example:
6466 with Interfaces.C.Strings;
6467 use Interfaces.C.Strings;
6469 type Carnivore is limited interface;
6470 pragma Convention (C_Plus_Plus, Carnivore);
6471 function Number_Of_Teeth (X : Carnivore)
6472 return Natural is abstract;
6474 type Domestic is limited interface;
6475 pragma Convention (C_Plus_Plus, Domestic);
6477 (X : in out Domestic;
6478 Name : Chars_Ptr) is abstract;
6480 type Animal is tagged record
6483 pragma Convention (C_Plus_Plus, Animal);
6485 procedure Set_Age (X : in out Animal; Age : Integer);
6486 pragma Export (C_Plus_Plus, Set_Age);
6488 function Age (X : Animal) return Integer;
6489 pragma Export (C_Plus_Plus, Age);
6491 function New_Animal return Animal'Class;
6492 pragma Export (C_Plus_Plus, New_Animal);
6494 type Dog is new Animal and Carnivore and Domestic with record
6495 Tooth_Count : Natural;
6496 Owner : String (1 .. 30);
6498 pragma Convention (C_Plus_Plus, Dog);
6500 function Number_Of_Teeth (A : Dog) return Natural;
6501 pragma Export (C_Plus_Plus, Number_Of_Teeth);
6503 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
6504 pragma Export (C_Plus_Plus, Set_Owner);
6506 function New_Dog return Dog'Class;
6507 pragma Export (C_Plus_Plus, New_Dog);
6511 Compared with our previous example the only differences are the use of
6512 @cite{pragma Convention} (instead of @cite{pragma Import}), and the use of
6513 @cite{pragma Export} to indicate to the GNAT compiler that the primitives will
6514 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
6515 nothing else to be done; as explained above, the only requirement is that all
6516 the primitives and components are declared in exactly the same order.
6518 For completeness, let us see a brief C++ main program that uses the
6519 declarations available in @cite{animals.h} (presented in our first example) to
6520 import and use the declarations from the Ada side, properly initializing and
6521 finalizing the Ada run-time system along the way:
6524 #include "animals.h"
6526 using namespace std;
6528 void Check_Carnivore (Carnivore *obj) @{...@}
6529 void Check_Domestic (Domestic *obj) @{...@}
6530 void Check_Animal (Animal *obj) @{...@}
6531 void Check_Dog (Dog *obj) @{...@}
6534 void adainit (void);
6535 void adafinal (void);
6541 Dog *obj = new_dog(); // Ada constructor
6542 Check_Carnivore (obj); // Check secondary DT
6543 Check_Domestic (obj); // Check secondary DT
6544 Check_Animal (obj); // Check primary DT
6545 Check_Dog (obj); // Check primary DT
6550 adainit (); test(); adafinal ();
6555 @node Generating Ada Bindings for C and C++ headers,,Building Mixed Ada and C++ Programs,Mixed Language Programming
6556 @anchor{gnat_ugn/the_gnat_compilation_model id70}@anchor{c9}@anchor{gnat_ugn/the_gnat_compilation_model generating-ada-bindings-for-c-and-c-headers}@anchor{1b}
6557 @subsection Generating Ada Bindings for C and C++ headers
6560 @geindex Binding generation (for C and C++ headers)
6562 @geindex C headers (binding generation)
6564 @geindex C++ headers (binding generation)
6566 GNAT includes a binding generator for C and C++ headers which is
6567 intended to do 95% of the tedious work of generating Ada specs from C
6568 or C++ header files.
6570 Note that this capability is not intended to generate 100% correct Ada specs,
6571 and will is some cases require manual adjustments, although it can often
6572 be used out of the box in practice.
6574 Some of the known limitations include:
6580 only very simple character constant macros are translated into Ada
6581 constants. Function macros (macros with arguments) are partially translated
6582 as comments, to be completed manually if needed.
6585 some extensions (e.g. vector types) are not supported
6588 pointers to pointers or complex structures are mapped to System.Address
6591 identifiers with identical name (except casing) will generate compilation
6592 errors (e.g. @cite{shm_get} vs @cite{SHM_GET}).
6595 The code generated is using the Ada 2005 syntax, which makes it
6596 easier to interface with other languages than previous versions of Ada.
6599 * Running the binding generator::
6600 * Generating bindings for C++ headers::
6605 @node Running the binding generator,Generating bindings for C++ headers,,Generating Ada Bindings for C and C++ headers
6606 @anchor{gnat_ugn/the_gnat_compilation_model id71}@anchor{ca}@anchor{gnat_ugn/the_gnat_compilation_model running-the-binding-generator}@anchor{cb}
6607 @subsubsection Running the binding generator
6610 The binding generator is part of the @emph{gcc} compiler and can be
6611 invoked via the @emph{-fdump-ada-spec} switch, which will generate Ada
6612 spec files for the header files specified on the command line, and all
6613 header files needed by these files transitively. For example:
6616 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
6617 $ gcc -c -gnat05 *.ads
6620 will generate, under GNU/Linux, the following files: @code{time_h.ads},
6621 @code{bits_time_h.ads}, @code{stddef_h.ads}, @code{bits_types_h.ads} which
6622 correspond to the files @code{/usr/include/time.h},
6623 @code{/usr/include/bits/time.h}, etc..., and will then compile in Ada 2005
6624 mode these Ada specs.
6626 The @cite{-C} switch tells @emph{gcc} to extract comments from headers,
6627 and will attempt to generate corresponding Ada comments.
6629 If you want to generate a single Ada file and not the transitive closure, you
6630 can use instead the @emph{-fdump-ada-spec-slim} switch.
6632 You can optionally specify a parent unit, of which all generated units will
6633 be children, using @cite{-fada-spec-parent=`@w{`}unit}.
6635 Note that we recommend when possible to use the @emph{g++} driver to
6636 generate bindings, even for most C headers, since this will in general
6637 generate better Ada specs. For generating bindings for C++ headers, it is
6638 mandatory to use the @emph{g++} command, or @emph{gcc -x c++} which
6639 is equivalent in this case. If @emph{g++} cannot work on your C headers
6640 because of incompatibilities between C and C++, then you can fallback to
6643 For an example of better bindings generated from the C++ front-end,
6644 the name of the parameters (when available) are actually ignored by the C
6645 front-end. Consider the following C header:
6648 extern void foo (int variable);
6651 with the C front-end, @cite{variable} is ignored, and the above is handled as:
6654 extern void foo (int);
6657 generating a generic:
6660 procedure foo (param1 : int);
6663 with the C++ front-end, the name is available, and we generate:
6666 procedure foo (variable : int);
6669 In some cases, the generated bindings will be more complete or more meaningful
6670 when defining some macros, which you can do via the @emph{-D} switch. This
6671 is for example the case with @code{Xlib.h} under GNU/Linux:
6674 $ g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
6677 The above will generate more complete bindings than a straight call without
6678 the @emph{-DXLIB_ILLEGAL_ACCESS} switch.
6680 In other cases, it is not possible to parse a header file in a stand-alone
6681 manner, because other include files need to be included first. In this
6682 case, the solution is to create a small header file including the needed
6683 @cite{#include} and possible @cite{#define} directives. For example, to
6684 generate Ada bindings for @code{readline/readline.h}, you need to first
6685 include @code{stdio.h}, so you can create a file with the following two
6686 lines in e.g. @code{readline1.h}:
6690 #include <readline/readline.h>
6693 and then generate Ada bindings from this file:
6696 $ g++ -c -fdump-ada-spec readline1.h
6699 @node Generating bindings for C++ headers,Switches,Running the binding generator,Generating Ada Bindings for C and C++ headers
6700 @anchor{gnat_ugn/the_gnat_compilation_model id72}@anchor{cc}@anchor{gnat_ugn/the_gnat_compilation_model generating-bindings-for-c-headers}@anchor{cd}
6701 @subsubsection Generating bindings for C++ headers
6704 Generating bindings for C++ headers is done using the same options, always
6705 with the @emph{g++} compiler. Note that generating Ada spec from C++ headers is a
6706 much more complex job and support for C++ headers is much more limited that
6707 support for C headers. As a result, you will need to modify the resulting
6708 bindings by hand more extensively when using C++ headers.
6710 In this mode, C++ classes will be mapped to Ada tagged types, constructors
6711 will be mapped using the @cite{CPP_Constructor} pragma, and when possible,
6712 multiple inheritance of abstract classes will be mapped to Ada interfaces
6713 (see the @emph{Interfacing to C++} section in the @cite{GNAT Reference Manual}
6714 for additional information on interfacing to C++).
6716 For example, given the following C++ header file:
6721 virtual int Number_Of_Teeth () = 0;
6726 virtual void Set_Owner (char* Name) = 0;
6732 virtual void Set_Age (int New_Age);
6735 class Dog : Animal, Carnivore, Domestic @{
6740 virtual int Number_Of_Teeth ();
6741 virtual void Set_Owner (char* Name);
6747 The corresponding Ada code is generated:
6750 package Class_Carnivore is
6751 type Carnivore is limited interface;
6752 pragma Import (CPP, Carnivore);
6754 function Number_Of_Teeth (this : access Carnivore) return int is abstract;
6756 use Class_Carnivore;
6758 package Class_Domestic is
6759 type Domestic is limited interface;
6760 pragma Import (CPP, Domestic);
6763 (this : access Domestic;
6764 Name : Interfaces.C.Strings.chars_ptr) is abstract;
6768 package Class_Animal is
6769 type Animal is tagged limited record
6770 Age_Count : aliased int;
6772 pragma Import (CPP, Animal);
6774 procedure Set_Age (this : access Animal; New_Age : int);
6775 pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
6779 package Class_Dog is
6780 type Dog is new Animal and Carnivore and Domestic with record
6781 Tooth_Count : aliased int;
6782 Owner : Interfaces.C.Strings.chars_ptr;
6784 pragma Import (CPP, Dog);
6786 function Number_Of_Teeth (this : access Dog) return int;
6787 pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
6790 (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
6791 pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
6793 function New_Dog return Dog;
6794 pragma CPP_Constructor (New_Dog);
6795 pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
6800 @node Switches,,Generating bindings for C++ headers,Generating Ada Bindings for C and C++ headers
6801 @anchor{gnat_ugn/the_gnat_compilation_model switches}@anchor{ce}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-ada-binding-generation}@anchor{cf}
6802 @subsubsection Switches
6805 @geindex -fdump-ada-spec (gcc)
6810 @item @code{-fdump-ada-spec}
6812 Generate Ada spec files for the given header files transitively (including
6813 all header files that these headers depend upon).
6816 @geindex -fdump-ada-spec-slim (gcc)
6821 @item @code{-fdump-ada-spec-slim}
6823 Generate Ada spec files for the header files specified on the command line
6827 @geindex -fada-spec-parent (gcc)
6832 @item @code{-fada-spec-parent=@emph{unit}}
6834 Specifies that all files generated by @emph{-fdump-ada-spec*} are
6835 to be child units of the specified parent unit.
6845 Extract comments from headers and generate Ada comments in the Ada spec files.
6848 @node GNAT and Other Compilation Models,Using GNAT Files with External Tools,Mixed Language Programming,The GNAT Compilation Model
6849 @anchor{gnat_ugn/the_gnat_compilation_model id73}@anchor{d0}@anchor{gnat_ugn/the_gnat_compilation_model gnat-and-other-compilation-models}@anchor{47}
6850 @section GNAT and Other Compilation Models
6853 This section compares the GNAT model with the approaches taken in
6854 other environents, first the C/C++ model and then the mechanism that
6855 has been used in other Ada systems, in particular those traditionally
6859 * Comparison between GNAT and C/C++ Compilation Models::
6860 * Comparison between GNAT and Conventional Ada Library Models::
6864 @node Comparison between GNAT and C/C++ Compilation Models,Comparison between GNAT and Conventional Ada Library Models,,GNAT and Other Compilation Models
6865 @anchor{gnat_ugn/the_gnat_compilation_model comparison-between-gnat-and-c-c-compilation-models}@anchor{d1}@anchor{gnat_ugn/the_gnat_compilation_model id74}@anchor{d2}
6866 @subsection Comparison between GNAT and C/C++ Compilation Models
6869 The GNAT model of compilation is close to the C and C++ models. You can
6870 think of Ada specs as corresponding to header files in C. As in C, you
6871 don't need to compile specs; they are compiled when they are used. The
6872 Ada @emph{with} is similar in effect to the @cite{#include} of a C
6875 One notable difference is that, in Ada, you may compile specs separately
6876 to check them for semantic and syntactic accuracy. This is not always
6877 possible with C headers because they are fragments of programs that have
6878 less specific syntactic or semantic rules.
6880 The other major difference is the requirement for running the binder,
6881 which performs two important functions. First, it checks for
6882 consistency. In C or C++, the only defense against assembling
6883 inconsistent programs lies outside the compiler, in a makefile, for
6884 example. The binder satisfies the Ada requirement that it be impossible
6885 to construct an inconsistent program when the compiler is used in normal
6888 @geindex Elaboration order control
6890 The other important function of the binder is to deal with elaboration
6891 issues. There are also elaboration issues in C++ that are handled
6892 automatically. This automatic handling has the advantage of being
6893 simpler to use, but the C++ programmer has no control over elaboration.
6894 Where @cite{gnatbind} might complain there was no valid order of
6895 elaboration, a C++ compiler would simply construct a program that
6896 malfunctioned at run time.
6898 @node Comparison between GNAT and Conventional Ada Library Models,,Comparison between GNAT and C/C++ Compilation Models,GNAT and Other Compilation Models
6899 @anchor{gnat_ugn/the_gnat_compilation_model comparison-between-gnat-and-conventional-ada-library-models}@anchor{d3}@anchor{gnat_ugn/the_gnat_compilation_model id75}@anchor{d4}
6900 @subsection Comparison between GNAT and Conventional Ada Library Models
6903 This section is intended for Ada programmers who have
6904 used an Ada compiler implementing the traditional Ada library
6905 model, as described in the Ada Reference Manual.
6907 @geindex GNAT library
6909 In GNAT, there is no 'library' in the normal sense. Instead, the set of
6910 source files themselves acts as the library. Compiling Ada programs does
6911 not generate any centralized information, but rather an object file and
6912 a ALI file, which are of interest only to the binder and linker.
6913 In a traditional system, the compiler reads information not only from
6914 the source file being compiled, but also from the centralized library.
6915 This means that the effect of a compilation depends on what has been
6916 previously compiled. In particular:
6922 When a unit is @emph{with}ed, the unit seen by the compiler corresponds
6923 to the version of the unit most recently compiled into the library.
6926 Inlining is effective only if the necessary body has already been
6927 compiled into the library.
6930 Compiling a unit may obsolete other units in the library.
6933 In GNAT, compiling one unit never affects the compilation of any other
6934 units because the compiler reads only source files. Only changes to source
6935 files can affect the results of a compilation. In particular:
6941 When a unit is @emph{with}ed, the unit seen by the compiler corresponds
6942 to the source version of the unit that is currently accessible to the
6948 Inlining requires the appropriate source files for the package or
6949 subprogram bodies to be available to the compiler. Inlining is always
6950 effective, independent of the order in which units are compiled.
6953 Compiling a unit never affects any other compilations. The editing of
6954 sources may cause previous compilations to be out of date if they
6955 depended on the source file being modified.
6958 The most important result of these differences is that order of compilation
6959 is never significant in GNAT. There is no situation in which one is
6960 required to do one compilation before another. What shows up as order of
6961 compilation requirements in the traditional Ada library becomes, in
6962 GNAT, simple source dependencies; in other words, there is only a set
6963 of rules saying what source files must be present when a file is
6966 @node Using GNAT Files with External Tools,,GNAT and Other Compilation Models,The GNAT Compilation Model
6967 @anchor{gnat_ugn/the_gnat_compilation_model using-gnat-files-with-external-tools}@anchor{1c}@anchor{gnat_ugn/the_gnat_compilation_model id76}@anchor{d5}
6968 @section Using GNAT Files with External Tools
6971 This section explains how files that are produced by GNAT may be
6972 used with tools designed for other languages.
6975 * Using Other Utility Programs with GNAT::
6976 * The External Symbol Naming Scheme of GNAT::
6980 @node Using Other Utility Programs with GNAT,The External Symbol Naming Scheme of GNAT,,Using GNAT Files with External Tools
6981 @anchor{gnat_ugn/the_gnat_compilation_model using-other-utility-programs-with-gnat}@anchor{d6}@anchor{gnat_ugn/the_gnat_compilation_model id77}@anchor{d7}
6982 @subsection Using Other Utility Programs with GNAT
6985 The object files generated by GNAT are in standard system format and in
6986 particular the debugging information uses this format. This means
6987 programs generated by GNAT can be used with existing utilities that
6988 depend on these formats.
6990 In general, any utility program that works with C will also often work with
6991 Ada programs generated by GNAT. This includes software utilities such as
6992 gprof (a profiling program), gdb (the FSF debugger), and utilities such
6995 @node The External Symbol Naming Scheme of GNAT,,Using Other Utility Programs with GNAT,Using GNAT Files with External Tools
6996 @anchor{gnat_ugn/the_gnat_compilation_model the-external-symbol-naming-scheme-of-gnat}@anchor{d8}@anchor{gnat_ugn/the_gnat_compilation_model id78}@anchor{d9}
6997 @subsection The External Symbol Naming Scheme of GNAT
7000 In order to interpret the output from GNAT, when using tools that are
7001 originally intended for use with other languages, it is useful to
7002 understand the conventions used to generate link names from the Ada
7005 All link names are in all lowercase letters. With the exception of library
7006 procedure names, the mechanism used is simply to use the full expanded
7007 Ada name with dots replaced by double underscores. For example, suppose
7008 we have the following package spec:
7016 @geindex pragma Export
7018 The variable @cite{MN} has a full expanded Ada name of @cite{QRS.MN}, so
7019 the corresponding link name is @cite{qrs__mn}.
7020 Of course if a @cite{pragma Export} is used this may be overridden:
7025 pragma Export (Var1, C, External_Name => "var1_name");
7027 pragma Export (Var2, C, Link_Name => "var2_link_name");
7031 In this case, the link name for @cite{Var1} is whatever link name the
7032 C compiler would assign for the C function @cite{var1_name}. This typically
7033 would be either @cite{var1_name} or @cite{_var1_name}, depending on operating
7034 system conventions, but other possibilities exist. The link name for
7035 @cite{Var2} is @cite{var2_link_name}, and this is not operating system
7038 One exception occurs for library level procedures. A potential ambiguity
7039 arises between the required name @cite{_main} for the C main program,
7040 and the name we would otherwise assign to an Ada library level procedure
7041 called @cite{Main} (which might well not be the main program).
7043 To avoid this ambiguity, we attach the prefix @cite{_ada_} to such
7044 names. So if we have a library level procedure such as:
7047 procedure Hello (S : String);
7050 the external name of this procedure will be @cite{_ada_hello}.
7052 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
7054 @node Building Executable Programs with GNAT,GNAT Project Manager,The GNAT Compilation Model,Top
7055 @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{da}@anchor{gnat_ugn/building_executable_programs_with_gnat id1}@anchor{db}
7056 @chapter Building Executable Programs with GNAT
7059 This chapter describes first the gnatmake tool
7060 (@ref{1d,,Building with gnatmake}),
7061 which automatically determines the set of sources
7062 needed by an Ada compilation unit and executes the necessary
7063 (re)compilations, binding and linking.
7064 It also explains how to use each tool individually: the
7065 compiler (gcc, see @ref{1e,,Compiling with gcc}),
7066 binder (gnatbind, see @ref{1f,,Binding with gnatbind}),
7067 and linker (gnatlink, see @ref{20,,Linking with gnatlink})
7068 to build executable programs.
7069 Finally, this chapter provides examples of
7070 how to make use of the general GNU make mechanism
7071 in a GNAT context (see @ref{21,,Using the GNU make Utility}).
7074 * Building with gnatmake::
7075 * Compiling with gcc::
7076 * Compiler Switches::
7077 * Binding with gnatbind::
7078 * Linking with gnatlink::
7079 * Using the GNU make Utility::
7083 @node Building with gnatmake,Compiling with gcc,,Building Executable Programs with GNAT
7084 @anchor{gnat_ugn/building_executable_programs_with_gnat the-gnat-make-program-gnatmake}@anchor{1d}@anchor{gnat_ugn/building_executable_programs_with_gnat building-with-gnatmake}@anchor{dc}
7085 @section Building with @emph{gnatmake}
7090 A typical development cycle when working on an Ada program consists of
7091 the following steps:
7097 Edit some sources to fix bugs;
7103 Compile all sources affected;
7106 Rebind and relink; and
7112 @geindex Dependency rules (compilation)
7114 The third step in particular can be tricky, because not only do the modified
7115 files have to be compiled, but any files depending on these files must also be
7116 recompiled. The dependency rules in Ada can be quite complex, especially
7117 in the presence of overloading, @cite{use} clauses, generics and inlined
7120 @emph{gnatmake} automatically takes care of the third and fourth steps
7121 of this process. It determines which sources need to be compiled,
7122 compiles them, and binds and links the resulting object files.
7124 Unlike some other Ada make programs, the dependencies are always
7125 accurately recomputed from the new sources. The source based approach of
7126 the GNAT compilation model makes this possible. This means that if
7127 changes to the source program cause corresponding changes in
7128 dependencies, they will always be tracked exactly correctly by
7131 Note that for advanced description of project structure, we recommend creating
7132 a project file as explained in @ref{b,,GNAT Project Manager} and use the
7133 @emph{gprbuild} tool which supports building with project files and works similarly
7137 * Running gnatmake::
7138 * Switches for gnatmake::
7139 * Mode Switches for gnatmake::
7140 * Notes on the Command Line::
7141 * How gnatmake Works::
7142 * Examples of gnatmake Usage::
7146 @node Running gnatmake,Switches for gnatmake,,Building with gnatmake
7147 @anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatmake}@anchor{dd}@anchor{gnat_ugn/building_executable_programs_with_gnat id2}@anchor{de}
7148 @subsection Running @emph{gnatmake}
7151 The usual form of the @emph{gnatmake} command is
7154 $ gnatmake [<switches>] <file_name> [<file_names>] [<mode_switches>]
7157 The only required argument is one @cite{file_name}, which specifies
7158 a compilation unit that is a main program. Several @cite{file_names} can be
7159 specified: this will result in several executables being built.
7160 If @cite{switches} are present, they can be placed before the first
7161 @cite{file_name}, between @cite{file_names} or after the last @cite{file_name}.
7162 If @cite{mode_switches} are present, they must always be placed after
7163 the last @cite{file_name} and all @cite{switches}.
7165 If you are using standard file extensions (@code{.adb} and
7166 @code{.ads}), then the
7167 extension may be omitted from the @cite{file_name} arguments. However, if
7168 you are using non-standard extensions, then it is required that the
7169 extension be given. A relative or absolute directory path can be
7170 specified in a @cite{file_name}, in which case, the input source file will
7171 be searched for in the specified directory only. Otherwise, the input
7172 source file will first be searched in the directory where
7173 @emph{gnatmake} was invoked and if it is not found, it will be search on
7174 the source path of the compiler as described in
7175 @ref{8e,,Search Paths and the Run-Time Library (RTL)}.
7177 All @emph{gnatmake} output (except when you specify @emph{-M}) is sent to
7178 @code{stderr}. The output produced by the
7179 @emph{-M} switch is sent to @code{stdout}.
7181 @node Switches for gnatmake,Mode Switches for gnatmake,Running gnatmake,Building with gnatmake
7182 @anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatmake}@anchor{df}@anchor{gnat_ugn/building_executable_programs_with_gnat id3}@anchor{e0}
7183 @subsection Switches for @emph{gnatmake}
7186 You may specify any of the following switches to @emph{gnatmake}:
7188 @geindex --version (gnatmake)
7193 @item @code{--version}
7195 Display Copyright and version, then exit disregarding all other options.
7198 @geindex --help (gnatmake)
7205 If @code{--version} was not used, display usage, then exit disregarding
7209 @geindex --GCC=compiler_name (gnatmake)
7214 @item @code{--GCC=@emph{compiler_name}}
7216 Program used for compiling. The default is @code{gcc}. You need to use
7217 quotes around @cite{compiler_name} if @cite{compiler_name} contains
7218 spaces or other separator characters.
7219 As an example @code{--GCC="foo -x -y"}
7220 will instruct @emph{gnatmake} to use @code{foo -x -y} as your
7221 compiler. A limitation of this syntax is that the name and path name of
7222 the executable itself must not include any embedded spaces. Note that
7223 switch @code{-c} is always inserted after your command name. Thus in the
7224 above example the compiler command that will be used by @emph{gnatmake}
7225 will be @code{foo -c -x -y}. If several @code{--GCC=compiler_name} are
7226 used, only the last @cite{compiler_name} is taken into account. However,
7227 all the additional switches are also taken into account. Thus,
7228 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
7229 @code{--GCC="bar -x -y -z -t"}.
7232 @geindex --GNATBIND=binder_name (gnatmake)
7237 @item @code{--GNATBIND=@emph{binder_name}}
7239 Program used for binding. The default is @code{gnatbind}. You need to
7240 use quotes around @cite{binder_name} if @cite{binder_name} contains spaces
7241 or other separator characters.
7242 As an example @code{--GNATBIND="bar -x -y"}
7243 will instruct @emph{gnatmake} to use @cite{bar -x -y} as your
7244 binder. Binder switches that are normally appended by @emph{gnatmake}
7245 to @code{gnatbind} are now appended to the end of @cite{bar -x -y}.
7246 A limitation of this syntax is that the name and path name of the executable
7247 itself must not include any embedded spaces.
7250 @geindex --GNATLINK=linker_name (gnatmake)
7255 @item @code{--GNATLINK=@emph{linker_name}}
7257 Program used for linking. The default is @code{gnatlink}. You need to
7258 use quotes around @cite{linker_name} if @cite{linker_name} contains spaces
7259 or other separator characters.
7260 As an example @code{--GNATLINK="lan -x -y"}
7261 will instruct @emph{gnatmake} to use @code{lan -x -y} as your
7262 linker. Linker switches that are normally appended by @code{gnatmake} to
7263 @code{gnatlink} are now appended to the end of @code{lan -x -y}.
7264 A limitation of this syntax is that the name and path name of the executable
7265 itself must not include any embedded spaces.
7267 @item @code{--create-map-file}
7269 When linking an executable, create a map file. The name of the map file
7270 has the same name as the executable with extension ".map".
7272 @item @code{--create-map-file=@emph{mapfile}}
7274 When linking an executable, create a map file with the specified name.
7277 @geindex --create-missing-dirs (gnatmake)
7282 @item @code{--create-missing-dirs}
7284 When using project files (@code{-P@emph{project}}), automatically create
7285 missing object directories, library directories and exec
7288 @item @code{--single-compile-per-obj-dir}
7290 Disallow simultaneous compilations in the same object directory when
7291 project files are used.
7293 @item @code{--subdirs=@emph{subdir}}
7295 Actual object directory of each project file is the subdirectory subdir of the
7296 object directory specified or defaulted in the project file.
7298 @item @code{--unchecked-shared-lib-imports}
7300 By default, shared library projects are not allowed to import static library
7301 projects. When this switch is used on the command line, this restriction is
7304 @item @code{--source-info=@emph{source info file}}
7306 Specify a source info file. This switch is active only when project files
7307 are used. If the source info file is specified as a relative path, then it is
7308 relative to the object directory of the main project. If the source info file
7309 does not exist, then after the Project Manager has successfully parsed and
7310 processed the project files and found the sources, it creates the source info
7311 file. If the source info file already exists and can be read successfully,
7312 then the Project Manager will get all the needed information about the sources
7313 from the source info file and will not look for them. This reduces the time
7314 to process the project files, especially when looking for sources that take a
7315 long time. If the source info file exists but cannot be parsed successfully,
7316 the Project Manager will attempt to recreate it. If the Project Manager fails
7317 to create the source info file, a message is issued, but gnatmake does not
7318 fail. @emph{gnatmake} "trusts" the source info file. This means that
7319 if the source files have changed (addition, deletion, moving to a different
7320 source directory), then the source info file need to be deleted and recreated.
7323 @geindex -a (gnatmake)
7330 Consider all files in the make process, even the GNAT internal system
7331 files (for example, the predefined Ada library files), as well as any
7332 locked files. Locked files are files whose ALI file is write-protected.
7334 @emph{gnatmake} does not check these files,
7335 because the assumption is that the GNAT internal files are properly up
7336 to date, and also that any write protected ALI files have been properly
7337 installed. Note that if there is an installation problem, such that one
7338 of these files is not up to date, it will be properly caught by the
7340 You may have to specify this switch if you are working on GNAT
7341 itself. The switch @code{-a} is also useful
7342 in conjunction with @code{-f}
7343 if you need to recompile an entire application,
7344 including run-time files, using special configuration pragmas,
7345 such as a @cite{Normalize_Scalars} pragma.
7348 @code{gnatmake -a} compiles all GNAT
7350 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
7353 @geindex -b (gnatmake)
7360 Bind only. Can be combined with @emph{-c} to do
7361 compilation and binding, but no link.
7362 Can be combined with @emph{-l}
7363 to do binding and linking. When not combined with
7365 all the units in the closure of the main program must have been previously
7366 compiled and must be up to date. The root unit specified by @cite{file_name}
7367 may be given without extension, with the source extension or, if no GNAT
7368 Project File is specified, with the ALI file extension.
7371 @geindex -c (gnatmake)
7378 Compile only. Do not perform binding, except when @emph{-b}
7379 is also specified. Do not perform linking, except if both
7381 @emph{-l} are also specified.
7382 If the root unit specified by @cite{file_name} is not a main unit, this is the
7383 default. Otherwise @emph{gnatmake} will attempt binding and linking
7384 unless all objects are up to date and the executable is more recent than
7388 @geindex -C (gnatmake)
7395 Use a temporary mapping file. A mapping file is a way to communicate
7396 to the compiler two mappings: from unit names to file names (without
7397 any directory information) and from file names to path names (with
7398 full directory information). A mapping file can make the compiler's
7399 file searches faster, especially if there are many source directories,
7400 or the sources are read over a slow network connection. If
7401 @emph{-P} is used, a mapping file is always used, so
7402 @emph{-C} is unnecessary; in this case the mapping file
7403 is initially populated based on the project file. If
7404 @emph{-C} is used without
7406 the mapping file is initially empty. Each invocation of the compiler
7407 will add any newly accessed sources to the mapping file.
7410 @geindex -C= (gnatmake)
7415 @item @code{-C=@emph{file}}
7417 Use a specific mapping file. The file, specified as a path name (absolute or
7418 relative) by this switch, should already exist, otherwise the switch is
7419 ineffective. The specified mapping file will be communicated to the compiler.
7420 This switch is not compatible with a project file
7421 (-P`file`) or with multiple compiling processes
7422 (-jnnn, when nnn is greater than 1).
7425 @geindex -d (gnatmake)
7432 Display progress for each source, up to date or not, as a single line:
7435 completed x out of y (zz%)
7438 If the file needs to be compiled this is displayed after the invocation of
7439 the compiler. These lines are displayed even in quiet output mode.
7442 @geindex -D (gnatmake)
7447 @item @code{-D @emph{dir}}
7449 Put all object files and ALI file in directory @cite{dir}.
7450 If the @emph{-D} switch is not used, all object files
7451 and ALI files go in the current working directory.
7453 This switch cannot be used when using a project file.
7456 @geindex -eI (gnatmake)
7461 @item @code{-eI@emph{nnn}}
7463 Indicates that the main source is a multi-unit source and the rank of the unit
7464 in the source file is nnn. nnn needs to be a positive number and a valid
7465 index in the source. This switch cannot be used when @emph{gnatmake} is
7466 invoked for several mains.
7469 @geindex -eL (gnatmake)
7471 @geindex symbolic links
7478 Follow all symbolic links when processing project files.
7479 This should be used if your project uses symbolic links for files or
7480 directories, but is not needed in other cases.
7482 @geindex naming scheme
7484 This also assumes that no directory matches the naming scheme for files (for
7485 instance that you do not have a directory called "sources.ads" when using the
7486 default GNAT naming scheme).
7488 When you do not have to use this switch (i.e., by default), gnatmake is able to
7489 save a lot of system calls (several per source file and object file), which
7490 can result in a significant speed up to load and manipulate a project file,
7491 especially when using source files from a remote system.
7494 @geindex -eS (gnatmake)
7501 Output the commands for the compiler, the binder and the linker
7503 instead of standard error.
7506 @geindex -f (gnatmake)
7513 Force recompilations. Recompile all sources, even though some object
7514 files may be up to date, but don't recompile predefined or GNAT internal
7515 files or locked files (files with a write-protected ALI file),
7516 unless the @emph{-a} switch is also specified.
7519 @geindex -F (gnatmake)
7526 When using project files, if some errors or warnings are detected during
7527 parsing and verbose mode is not in effect (no use of switch
7528 -v), then error lines start with the full path name of the project
7529 file, rather than its simple file name.
7532 @geindex -g (gnatmake)
7539 Enable debugging. This switch is simply passed to the compiler and to the
7543 @geindex -i (gnatmake)
7550 In normal mode, @emph{gnatmake} compiles all object files and ALI files
7551 into the current directory. If the @emph{-i} switch is used,
7552 then instead object files and ALI files that already exist are overwritten
7553 in place. This means that once a large project is organized into separate
7554 directories in the desired manner, then @emph{gnatmake} will automatically
7555 maintain and update this organization. If no ALI files are found on the
7556 Ada object path (see @ref{8e,,Search Paths and the Run-Time Library (RTL)}),
7557 the new object and ALI files are created in the
7558 directory containing the source being compiled. If another organization
7559 is desired, where objects and sources are kept in different directories,
7560 a useful technique is to create dummy ALI files in the desired directories.
7561 When detecting such a dummy file, @emph{gnatmake} will be forced to
7562 recompile the corresponding source file, and it will be put the resulting
7563 object and ALI files in the directory where it found the dummy file.
7566 @geindex -j (gnatmake)
7568 @geindex Parallel make
7573 @item @code{-j@emph{n}}
7575 Use @cite{n} processes to carry out the (re)compilations. On a multiprocessor
7576 machine compilations will occur in parallel. If @cite{n} is 0, then the
7577 maximum number of parallel compilations is the number of core processors
7578 on the platform. In the event of compilation errors, messages from various
7579 compilations might get interspersed (but @emph{gnatmake} will give you the
7580 full ordered list of failing compiles at the end). If this is problematic,
7581 rerun the make process with n set to 1 to get a clean list of messages.
7584 @geindex -k (gnatmake)
7591 Keep going. Continue as much as possible after a compilation error. To
7592 ease the programmer's task in case of compilation errors, the list of
7593 sources for which the compile fails is given when @emph{gnatmake}
7596 If @emph{gnatmake} is invoked with several @code{file_names} and with this
7597 switch, if there are compilation errors when building an executable,
7598 @emph{gnatmake} will not attempt to build the following executables.
7601 @geindex -l (gnatmake)
7608 Link only. Can be combined with @emph{-b} to binding
7609 and linking. Linking will not be performed if combined with
7611 but not with @emph{-b}.
7612 When not combined with @emph{-b}
7613 all the units in the closure of the main program must have been previously
7614 compiled and must be up to date, and the main program needs to have been bound.
7615 The root unit specified by @cite{file_name}
7616 may be given without extension, with the source extension or, if no GNAT
7617 Project File is specified, with the ALI file extension.
7620 @geindex -m (gnatmake)
7627 Specify that the minimum necessary amount of recompilations
7628 be performed. In this mode @emph{gnatmake} ignores time
7629 stamp differences when the only
7630 modifications to a source file consist in adding/removing comments,
7631 empty lines, spaces or tabs. This means that if you have changed the
7632 comments in a source file or have simply reformatted it, using this
7633 switch will tell @emph{gnatmake} not to recompile files that depend on it
7634 (provided other sources on which these files depend have undergone no
7635 semantic modifications). Note that the debugging information may be
7636 out of date with respect to the sources if the @emph{-m} switch causes
7637 a compilation to be switched, so the use of this switch represents a
7638 trade-off between compilation time and accurate debugging information.
7641 @geindex Dependencies
7642 @geindex producing list
7644 @geindex -M (gnatmake)
7651 Check if all objects are up to date. If they are, output the object
7652 dependences to @code{stdout} in a form that can be directly exploited in
7653 a @code{Makefile}. By default, each source file is prefixed with its
7654 (relative or absolute) directory name. This name is whatever you
7655 specified in the various @emph{-aI}
7656 and @emph{-I} switches. If you use
7657 @cite{gnatmake -M} @emph{-q}
7658 (see below), only the source file names,
7659 without relative paths, are output. If you just specify the @emph{-M}
7660 switch, dependencies of the GNAT internal system files are omitted. This
7661 is typically what you want. If you also specify
7662 the @emph{-a} switch,
7663 dependencies of the GNAT internal files are also listed. Note that
7664 dependencies of the objects in external Ada libraries (see
7665 switch @code{-aL@emph{dir}} in the following list)
7669 @geindex -n (gnatmake)
7676 Don't compile, bind, or link. Checks if all objects are up to date.
7677 If they are not, the full name of the first file that needs to be
7678 recompiled is printed.
7679 Repeated use of this option, followed by compiling the indicated source
7680 file, will eventually result in recompiling all required units.
7683 @geindex -o (gnatmake)
7688 @item @code{-o @emph{exec_name}}
7690 Output executable name. The name of the final executable program will be
7691 @cite{exec_name}. If the @emph{-o} switch is omitted the default
7692 name for the executable will be the name of the input file in appropriate form
7693 for an executable file on the host system.
7695 This switch cannot be used when invoking @emph{gnatmake} with several
7699 @geindex -p (gnatmake)
7706 Same as @code{--create-missing-dirs}
7709 @geindex -P (gnatmake)
7714 @item @code{-P@emph{project}}
7716 Use project file @cite{project}. Only one such switch can be used.
7717 @ref{e1,,gnatmake and Project Files}.
7720 @geindex -q (gnatmake)
7727 Quiet. When this flag is not set, the commands carried out by
7728 @emph{gnatmake} are displayed.
7731 @geindex -s (gnatmake)
7738 Recompile if compiler switches have changed since last compilation.
7739 All compiler switches but -I and -o are taken into account in the
7741 orders between different 'first letter' switches are ignored, but
7742 orders between same switches are taken into account. For example,
7743 @emph{-O -O2} is different than @emph{-O2 -O}, but @emph{-g -O}
7744 is equivalent to @emph{-O -g}.
7746 This switch is recommended when Integrated Preprocessing is used.
7749 @geindex -u (gnatmake)
7756 Unique. Recompile at most the main files. It implies -c. Combined with
7757 -f, it is equivalent to calling the compiler directly. Note that using
7758 -u with a project file and no main has a special meaning
7759 (@ref{e2,,Project Files and Main Subprograms}).
7762 @geindex -U (gnatmake)
7769 When used without a project file or with one or several mains on the command
7770 line, is equivalent to -u. When used with a project file and no main
7771 on the command line, all sources of all project files are checked and compiled
7772 if not up to date, and libraries are rebuilt, if necessary.
7775 @geindex -v (gnatmake)
7782 Verbose. Display the reason for all recompilations @emph{gnatmake}
7783 decides are necessary, with the highest verbosity level.
7786 @geindex -vl (gnatmake)
7793 Verbosity level Low. Display fewer lines than in verbosity Medium.
7796 @geindex -vm (gnatmake)
7803 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
7806 @geindex -vm (gnatmake)
7813 Verbosity level High. Equivalent to -v.
7815 @item @code{-vP@emph{x}}
7817 Indicate the verbosity of the parsing of GNAT project files.
7818 See @ref{e3,,Switches Related to Project Files}.
7821 @geindex -x (gnatmake)
7828 Indicate that sources that are not part of any Project File may be compiled.
7829 Normally, when using Project Files, only sources that are part of a Project
7830 File may be compile. When this switch is used, a source outside of all Project
7831 Files may be compiled. The ALI file and the object file will be put in the
7832 object directory of the main Project. The compilation switches used will only
7833 be those specified on the command line. Even when
7834 @emph{-x} is used, mains specified on the
7835 command line need to be sources of a project file.
7837 @item @code{-X@emph{name}=@emph{value}}
7839 Indicate that external variable @cite{name} has the value @cite{value}.
7840 The Project Manager will use this value for occurrences of
7841 @cite{external(name)} when parsing the project file.
7842 @ref{e3,,Switches Related to Project Files}.
7845 @geindex -z (gnatmake)
7852 No main subprogram. Bind and link the program even if the unit name
7853 given on the command line is a package name. The resulting executable
7854 will execute the elaboration routines of the package and its closure,
7855 then the finalization routines.
7858 @subsubheading GCC switches
7861 Any uppercase or multi-character switch that is not a @emph{gnatmake} switch
7862 is passed to @emph{gcc} (e.g., @emph{-O}, @emph{-gnato,} etc.)
7864 @subsubheading Source and library search path switches
7867 @geindex -aI (gnatmake)
7872 @item @code{-aI@emph{dir}}
7874 When looking for source files also look in directory @cite{dir}.
7875 The order in which source files search is undertaken is
7876 described in @ref{8e,,Search Paths and the Run-Time Library (RTL)}.
7879 @geindex -aL (gnatmake)
7884 @item @code{-aL@emph{dir}}
7886 Consider @cite{dir} as being an externally provided Ada library.
7887 Instructs @emph{gnatmake} to skip compilation units whose @code{.ALI}
7888 files have been located in directory @cite{dir}. This allows you to have
7889 missing bodies for the units in @cite{dir} and to ignore out of date bodies
7890 for the same units. You still need to specify
7891 the location of the specs for these units by using the switches
7892 @code{-aI@emph{dir}} or @code{-I@emph{dir}}.
7893 Note: this switch is provided for compatibility with previous versions
7894 of @emph{gnatmake}. The easier method of causing standard libraries
7895 to be excluded from consideration is to write-protect the corresponding
7899 @geindex -aO (gnatmake)
7904 @item @code{-aO@emph{dir}}
7906 When searching for library and object files, look in directory
7907 @cite{dir}. The order in which library files are searched is described in
7908 @ref{91,,Search Paths for gnatbind}.
7911 @geindex Search paths
7912 @geindex for gnatmake
7914 @geindex -A (gnatmake)
7919 @item @code{-A@emph{dir}}
7921 Equivalent to @code{-aL@emph{dir}} @code{-aI@emph{dir}}.
7923 @geindex -I (gnatmake)
7925 @item @code{-I@emph{dir}}
7927 Equivalent to @code{-aO@emph{dir} -aI@emph{dir}}.
7930 @geindex -I- (gnatmake)
7932 @geindex Source files
7933 @geindex suppressing search
7940 Do not look for source files in the directory containing the source
7941 file named in the command line.
7942 Do not look for ALI or object files in the directory
7943 where @emph{gnatmake} was invoked.
7946 @geindex -L (gnatmake)
7948 @geindex Linker libraries
7953 @item @code{-L@emph{dir}}
7955 Add directory @cite{dir} to the list of directories in which the linker
7956 will search for libraries. This is equivalent to
7957 @code{-largs} @code{-L@emph{dir}}.
7958 Furthermore, under Windows, the sources pointed to by the libraries path
7959 set in the registry are not searched for.
7962 @geindex -nostdinc (gnatmake)
7967 @item @code{-nostdinc}
7969 Do not look for source files in the system default directory.
7972 @geindex -nostdlib (gnatmake)
7977 @item @code{-nostdlib}
7979 Do not look for library files in the system default directory.
7982 @geindex --RTS (gnatmake)
7987 @item @code{--RTS=@emph{rts-path}}
7989 Specifies the default location of the runtime library. GNAT looks for the
7991 in the following directories, and stops as soon as a valid runtime is found
7992 (@code{adainclude} or @code{ada_source_path}, and @code{adalib} or
7993 @code{ada_object_path} present):
7999 @emph{<current directory>/$rts_path}
8002 @emph{<default-search-dir>/$rts_path}
8005 @emph{<default-search-dir>/rts-$rts_path}
8008 The selected path is handled like a normal RTS path.
8012 @node Mode Switches for gnatmake,Notes on the Command Line,Switches for gnatmake,Building with gnatmake
8013 @anchor{gnat_ugn/building_executable_programs_with_gnat id4}@anchor{e4}@anchor{gnat_ugn/building_executable_programs_with_gnat mode-switches-for-gnatmake}@anchor{e5}
8014 @subsection Mode Switches for @emph{gnatmake}
8017 The mode switches (referred to as @cite{mode_switches}) allow the
8018 inclusion of switches that are to be passed to the compiler itself, the
8019 binder or the linker. The effect of a mode switch is to cause all
8020 subsequent switches up to the end of the switch list, or up to the next
8021 mode switch, to be interpreted as switches to be passed on to the
8022 designated component of GNAT.
8024 @geindex -cargs (gnatmake)
8029 @item @code{-cargs @emph{switches}}
8031 Compiler switches. Here @cite{switches} is a list of switches
8032 that are valid switches for @emph{gcc}. They will be passed on to
8033 all compile steps performed by @emph{gnatmake}.
8036 @geindex -bargs (gnatmake)
8041 @item @code{-bargs @emph{switches}}
8043 Binder switches. Here @cite{switches} is a list of switches
8044 that are valid switches for @cite{gnatbind}. They will be passed on to
8045 all bind steps performed by @emph{gnatmake}.
8048 @geindex -largs (gnatmake)
8053 @item @code{-largs @emph{switches}}
8055 Linker switches. Here @cite{switches} is a list of switches
8056 that are valid switches for @emph{gnatlink}. They will be passed on to
8057 all link steps performed by @emph{gnatmake}.
8060 @geindex -margs (gnatmake)
8065 @item @code{-margs @emph{switches}}
8067 Make switches. The switches are directly interpreted by @emph{gnatmake},
8068 regardless of any previous occurrence of @emph{-cargs}, @emph{-bargs}
8072 @node Notes on the Command Line,How gnatmake Works,Mode Switches for gnatmake,Building with gnatmake
8073 @anchor{gnat_ugn/building_executable_programs_with_gnat id5}@anchor{e6}@anchor{gnat_ugn/building_executable_programs_with_gnat notes-on-the-command-line}@anchor{e7}
8074 @subsection Notes on the Command Line
8077 This section contains some additional useful notes on the operation
8078 of the @emph{gnatmake} command.
8080 @geindex Recompilation (by gnatmake)
8086 If @emph{gnatmake} finds no ALI files, it recompiles the main program
8087 and all other units required by the main program.
8088 This means that @emph{gnatmake}
8089 can be used for the initial compile, as well as during subsequent steps of
8090 the development cycle.
8093 If you enter @code{gnatmake foo.adb}, where @code{foo}
8094 is a subunit or body of a generic unit, @emph{gnatmake} recompiles
8095 @code{foo.adb} (because it finds no ALI) and stops, issuing a
8099 In @emph{gnatmake} the switch @emph{-I}
8100 is used to specify both source and
8101 library file paths. Use @emph{-aI}
8102 instead if you just want to specify
8103 source paths only and @emph{-aO}
8104 if you want to specify library paths
8108 @emph{gnatmake} will ignore any files whose ALI file is write-protected.
8109 This may conveniently be used to exclude standard libraries from
8110 consideration and in particular it means that the use of the
8111 @emph{-f} switch will not recompile these files
8112 unless @emph{-a} is also specified.
8115 @emph{gnatmake} has been designed to make the use of Ada libraries
8116 particularly convenient. Assume you have an Ada library organized
8117 as follows: @emph{obj-dir} contains the objects and ALI files for
8118 of your Ada compilation units,
8119 whereas @emph{include-dir} contains the
8120 specs of these units, but no bodies. Then to compile a unit
8121 stored in @cite{main.adb}, which uses this Ada library you would just type:
8124 $ gnatmake -aI`include-dir` -aL`obj-dir` main
8128 Using @emph{gnatmake} along with the @emph{-m (minimal recompilation)}
8129 switch provides a mechanism for avoiding unnecessary recompilations. Using
8131 you can update the comments/format of your
8132 source files without having to recompile everything. Note, however, that
8133 adding or deleting lines in a source files may render its debugging
8134 info obsolete. If the file in question is a spec, the impact is rather
8135 limited, as that debugging info will only be useful during the
8136 elaboration phase of your program. For bodies the impact can be more
8137 significant. In all events, your debugger will warn you if a source file
8138 is more recent than the corresponding object, and alert you to the fact
8139 that the debugging information may be out of date.
8142 @node How gnatmake Works,Examples of gnatmake Usage,Notes on the Command Line,Building with gnatmake
8143 @anchor{gnat_ugn/building_executable_programs_with_gnat id6}@anchor{e8}@anchor{gnat_ugn/building_executable_programs_with_gnat how-gnatmake-works}@anchor{e9}
8144 @subsection How @emph{gnatmake} Works
8147 Generally @emph{gnatmake} automatically performs all necessary
8148 recompilations and you don't need to worry about how it works. However,
8149 it may be useful to have some basic understanding of the @emph{gnatmake}
8150 approach and in particular to understand how it uses the results of
8151 previous compilations without incorrectly depending on them.
8153 First a definition: an object file is considered @emph{up to date} if the
8154 corresponding ALI file exists and if all the source files listed in the
8155 dependency section of this ALI file have time stamps matching those in
8156 the ALI file. This means that neither the source file itself nor any
8157 files that it depends on have been modified, and hence there is no need
8158 to recompile this file.
8160 @emph{gnatmake} works by first checking if the specified main unit is up
8161 to date. If so, no compilations are required for the main unit. If not,
8162 @emph{gnatmake} compiles the main program to build a new ALI file that
8163 reflects the latest sources. Then the ALI file of the main unit is
8164 examined to find all the source files on which the main program depends,
8165 and @emph{gnatmake} recursively applies the above procedure on all these
8168 This process ensures that @emph{gnatmake} only trusts the dependencies
8169 in an existing ALI file if they are known to be correct. Otherwise it
8170 always recompiles to determine a new, guaranteed accurate set of
8171 dependencies. As a result the program is compiled 'upside down' from what may
8172 be more familiar as the required order of compilation in some other Ada
8173 systems. In particular, clients are compiled before the units on which
8174 they depend. The ability of GNAT to compile in any order is critical in
8175 allowing an order of compilation to be chosen that guarantees that
8176 @emph{gnatmake} will recompute a correct set of new dependencies if
8179 When invoking @emph{gnatmake} with several @cite{file_names}, if a unit is
8180 imported by several of the executables, it will be recompiled at most once.
8182 Note: when using non-standard naming conventions
8183 (@ref{37,,Using Other File Names}), changing through a configuration pragmas
8184 file the version of a source and invoking @emph{gnatmake} to recompile may
8185 have no effect, if the previous version of the source is still accessible
8186 by @emph{gnatmake}. It may be necessary to use the switch
8189 @node Examples of gnatmake Usage,,How gnatmake Works,Building with gnatmake
8190 @anchor{gnat_ugn/building_executable_programs_with_gnat examples-of-gnatmake-usage}@anchor{ea}@anchor{gnat_ugn/building_executable_programs_with_gnat id7}@anchor{eb}
8191 @subsection Examples of @emph{gnatmake} Usage
8197 @item @emph{gnatmake hello.adb}
8199 Compile all files necessary to bind and link the main program
8200 @code{hello.adb} (containing unit @cite{Hello}) and bind and link the
8201 resulting object files to generate an executable file @code{hello}.
8203 @item @emph{gnatmake main1 main2 main3}
8205 Compile all files necessary to bind and link the main programs
8206 @code{main1.adb} (containing unit @cite{Main1}), @code{main2.adb}
8207 (containing unit @cite{Main2}) and @code{main3.adb}
8208 (containing unit @cite{Main3}) and bind and link the resulting object files
8209 to generate three executable files @code{main1},
8210 @code{main2} and @code{main3}.
8212 @item @emph{gnatmake -q Main_Unit -cargs -O2 -bargs -l}
8214 Compile all files necessary to bind and link the main program unit
8215 @cite{Main_Unit} (from file @code{main_unit.adb}). All compilations will
8216 be done with optimization level 2 and the order of elaboration will be
8217 listed by the binder. @emph{gnatmake} will operate in quiet mode, not
8218 displaying commands it is executing.
8221 @node Compiling with gcc,Compiler Switches,Building with gnatmake,Building Executable Programs with GNAT
8222 @anchor{gnat_ugn/building_executable_programs_with_gnat compiling-with-gcc}@anchor{1e}@anchor{gnat_ugn/building_executable_programs_with_gnat id8}@anchor{ec}
8223 @section Compiling with @emph{gcc}
8226 This section discusses how to compile Ada programs using the @emph{gcc}
8227 command. It also describes the set of switches
8228 that can be used to control the behavior of the compiler.
8231 * Compiling Programs::
8232 * Search Paths and the Run-Time Library (RTL): Search Paths and the Run-Time Library RTL.
8233 * Order of Compilation Issues::
8238 @node Compiling Programs,Search Paths and the Run-Time Library RTL,,Compiling with gcc
8239 @anchor{gnat_ugn/building_executable_programs_with_gnat compiling-programs}@anchor{ed}@anchor{gnat_ugn/building_executable_programs_with_gnat id9}@anchor{ee}
8240 @subsection Compiling Programs
8243 The first step in creating an executable program is to compile the units
8244 of the program using the @emph{gcc} command. You must compile the
8251 the body file (@code{.adb}) for a library level subprogram or generic
8255 the spec file (@code{.ads}) for a library level package or generic
8256 package that has no body
8259 the body file (@code{.adb}) for a library level package
8260 or generic package that has a body
8263 You need @emph{not} compile the following files
8269 the spec of a library unit which has a body
8275 because they are compiled as part of compiling related units. GNAT
8277 when the corresponding body is compiled, and subunits when the parent is
8280 @geindex cannot generate code
8282 If you attempt to compile any of these files, you will get one of the
8283 following error messages (where @cite{fff} is the name of the file you
8289 cannot generate code for file `fff` (package spec)
8290 to check package spec, use -gnatc
8292 cannot generate code for file `fff` (missing subunits)
8293 to check parent unit, use -gnatc
8295 cannot generate code for file `fff` (subprogram spec)
8296 to check subprogram spec, use -gnatc
8298 cannot generate code for file `fff` (subunit)
8299 to check subunit, use -gnatc
8303 As indicated by the above error messages, if you want to submit
8304 one of these files to the compiler to check for correct semantics
8305 without generating code, then use the @emph{-gnatc} switch.
8307 The basic command for compiling a file containing an Ada unit is:
8310 $ gcc -c [switches] <file name>
8313 where @cite{file name} is the name of the Ada file (usually
8314 having an extension @code{.ads} for a spec or @code{.adb} for a body).
8316 @code{-c} switch to tell @emph{gcc} to compile, but not link, the file.
8317 The result of a successful compilation is an object file, which has the
8318 same name as the source file but an extension of @code{.o} and an Ada
8319 Library Information (ALI) file, which also has the same name as the
8320 source file, but with @code{.ali} as the extension. GNAT creates these
8321 two output files in the current directory, but you may specify a source
8322 file in any directory using an absolute or relative path specification
8323 containing the directory information.
8327 @emph{gcc} is actually a driver program that looks at the extensions of
8328 the file arguments and loads the appropriate compiler. For example, the
8329 GNU C compiler is @code{cc1}, and the Ada compiler is @code{gnat1}.
8330 These programs are in directories known to the driver program (in some
8331 configurations via environment variables you set), but need not be in
8332 your path. The @emph{gcc} driver also calls the assembler and any other
8333 utilities needed to complete the generation of the required object
8336 It is possible to supply several file names on the same @emph{gcc}
8337 command. This causes @emph{gcc} to call the appropriate compiler for
8338 each file. For example, the following command lists two separate
8339 files to be compiled:
8342 $ gcc -c x.adb y.adb
8345 calls @cite{gnat1} (the Ada compiler) twice to compile @code{x.adb} and
8347 The compiler generates two object files @code{x.o} and @code{y.o}
8348 and the two ALI files @code{x.ali} and @code{y.ali}.
8350 Any switches apply to all the files listed, see @ref{ef,,Compiler Switches} for a
8351 list of available @emph{gcc} switches.
8353 @node Search Paths and the Run-Time Library RTL,Order of Compilation Issues,Compiling Programs,Compiling with gcc
8354 @anchor{gnat_ugn/building_executable_programs_with_gnat id10}@anchor{f0}@anchor{gnat_ugn/building_executable_programs_with_gnat search-paths-and-the-run-time-library-rtl}@anchor{8e}
8355 @subsection Search Paths and the Run-Time Library (RTL)
8358 With the GNAT source-based library system, the compiler must be able to
8359 find source files for units that are needed by the unit being compiled.
8360 Search paths are used to guide this process.
8362 The compiler compiles one source file whose name must be given
8363 explicitly on the command line. In other words, no searching is done
8364 for this file. To find all other source files that are needed (the most
8365 common being the specs of units), the compiler examines the following
8366 directories, in the following order:
8372 The directory containing the source file of the main unit being compiled
8373 (the file name on the command line).
8376 Each directory named by an @emph{-I} switch given on the @emph{gcc}
8377 command line, in the order given.
8379 @geindex ADA_PRJ_INCLUDE_FILE
8382 Each of the directories listed in the text file whose name is given
8384 @geindex ADA_PRJ_INCLUDE_FILE
8385 @geindex environment variable; ADA_PRJ_INCLUDE_FILE
8386 @code{ADA_PRJ_INCLUDE_FILE} environment variable.
8387 @geindex ADA_PRJ_INCLUDE_FILE
8388 @geindex environment variable; ADA_PRJ_INCLUDE_FILE
8389 @code{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the gnat
8390 driver when project files are used. It should not normally be set
8393 @geindex ADA_INCLUDE_PATH
8396 Each of the directories listed in the value of the
8397 @geindex ADA_INCLUDE_PATH
8398 @geindex environment variable; ADA_INCLUDE_PATH
8399 @code{ADA_INCLUDE_PATH} environment variable.
8400 Construct this value
8403 @geindex environment variable; PATH
8404 @code{PATH} environment variable: a list of directory
8405 names separated by colons (semicolons when working with the NT version).
8408 The content of the @code{ada_source_path} file which is part of the GNAT
8409 installation tree and is used to store standard libraries such as the
8410 GNAT Run Time Library (RTL) source files.
8411 @ref{8b,,Installing a library}
8414 Specifying the switch @emph{-I-}
8415 inhibits the use of the directory
8416 containing the source file named in the command line. You can still
8417 have this directory on your search path, but in this case it must be
8418 explicitly requested with a @emph{-I} switch.
8420 Specifying the switch @emph{-nostdinc}
8421 inhibits the search of the default location for the GNAT Run Time
8422 Library (RTL) source files.
8424 The compiler outputs its object files and ALI files in the current
8426 Caution: The object file can be redirected with the @emph{-o} switch;
8427 however, @emph{gcc} and @cite{gnat1} have not been coordinated on this
8428 so the @code{ALI} file will not go to the right place. Therefore, you should
8429 avoid using the @emph{-o} switch.
8433 The packages @cite{Ada}, @cite{System}, and @cite{Interfaces} and their
8434 children make up the GNAT RTL, together with the simple @cite{System.IO}
8435 package used in the @cite{"Hello World"} example. The sources for these units
8436 are needed by the compiler and are kept together in one directory. Not
8437 all of the bodies are needed, but all of the sources are kept together
8438 anyway. In a normal installation, you need not specify these directory
8439 names when compiling or binding. Either the environment variables or
8440 the built-in defaults cause these files to be found.
8442 In addition to the language-defined hierarchies (@cite{System}, @cite{Ada} and
8443 @cite{Interfaces}), the GNAT distribution provides a fourth hierarchy,
8444 consisting of child units of @cite{GNAT}. This is a collection of generally
8445 useful types, subprograms, etc. See the @cite{GNAT_Reference_Manual}
8446 for further details.
8448 Besides simplifying access to the RTL, a major use of search paths is
8449 in compiling sources from multiple directories. This can make
8450 development environments much more flexible.
8452 @node Order of Compilation Issues,Examples,Search Paths and the Run-Time Library RTL,Compiling with gcc
8453 @anchor{gnat_ugn/building_executable_programs_with_gnat id11}@anchor{f1}@anchor{gnat_ugn/building_executable_programs_with_gnat order-of-compilation-issues}@anchor{f2}
8454 @subsection Order of Compilation Issues
8457 If, in our earlier example, there was a spec for the @cite{hello}
8458 procedure, it would be contained in the file @code{hello.ads}; yet this
8459 file would not have to be explicitly compiled. This is the result of the
8460 model we chose to implement library management. Some of the consequences
8461 of this model are as follows:
8467 There is no point in compiling specs (except for package
8468 specs with no bodies) because these are compiled as needed by clients. If
8469 you attempt a useless compilation, you will receive an error message.
8470 It is also useless to compile subunits because they are compiled as needed
8474 There are no order of compilation requirements: performing a
8475 compilation never obsoletes anything. The only way you can obsolete
8476 something and require recompilations is to modify one of the
8477 source files on which it depends.
8480 There is no library as such, apart from the ALI files
8481 (@ref{44,,The Ada Library Information Files}, for information on the format
8482 of these files). For now we find it convenient to create separate ALI files,
8483 but eventually the information therein may be incorporated into the object
8487 When you compile a unit, the source files for the specs of all units
8488 that it @emph{with}s, all its subunits, and the bodies of any generics it
8489 instantiates must be available (reachable by the search-paths mechanism
8490 described above), or you will receive a fatal error message.
8493 @node Examples,,Order of Compilation Issues,Compiling with gcc
8494 @anchor{gnat_ugn/building_executable_programs_with_gnat id12}@anchor{f3}@anchor{gnat_ugn/building_executable_programs_with_gnat examples}@anchor{f4}
8495 @subsection Examples
8498 The following are some typical Ada compilation command line examples:
8504 Compile body in file @code{xyz.adb} with all default options.
8507 $ gcc -c -O2 -gnata xyz-def.adb
8510 Compile the child unit package in file @code{xyz-def.adb} with extensive
8511 optimizations, and pragma @cite{Assert}/@cite{Debug} statements
8515 $ gcc -c -gnatc abc-def.adb
8518 Compile the subunit in file @code{abc-def.adb} in semantic-checking-only
8521 @node Compiler Switches,Binding with gnatbind,Compiling with gcc,Building Executable Programs with GNAT
8522 @anchor{gnat_ugn/building_executable_programs_with_gnat compiler-switches}@anchor{f5}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gcc}@anchor{ef}
8523 @section Compiler Switches
8526 The @emph{gcc} command accepts switches that control the
8527 compilation process. These switches are fully described in this section:
8528 first an alphabetical listing of all switches with a brief description,
8529 and then functionally grouped sets of switches with more detailed
8532 More switches exist for GCC than those documented here, especially
8533 for specific targets. However, their use is not recommended as
8534 they may change code generation in ways that are incompatible with
8535 the Ada run-time library, or can cause inconsistencies between
8539 * Alphabetical List of All Switches::
8540 * Output and Error Message Control::
8541 * Warning Message Control::
8542 * Debugging and Assertion Control::
8543 * Validity Checking::
8546 * Using gcc for Syntax Checking::
8547 * Using gcc for Semantic Checking::
8548 * Compiling Different Versions of Ada::
8549 * Character Set Control::
8550 * File Naming Control::
8551 * Subprogram Inlining Control::
8552 * Auxiliary Output Control::
8553 * Debugging Control::
8554 * Exception Handling Control::
8555 * Units to Sources Mapping Files::
8556 * Code Generation Control::
8560 @node Alphabetical List of All Switches,Output and Error Message Control,,Compiler Switches
8561 @anchor{gnat_ugn/building_executable_programs_with_gnat id13}@anchor{f6}@anchor{gnat_ugn/building_executable_programs_with_gnat alphabetical-list-of-all-switches}@anchor{f7}
8562 @subsection Alphabetical List of All Switches
8570 @item @code{-b @emph{target}}
8572 Compile your program to run on @cite{target}, which is the name of a
8573 system configuration. You must have a GNAT cross-compiler built if
8574 @cite{target} is not the same as your host system.
8582 @item @code{-B@emph{dir}}
8584 Load compiler executables (for example, @cite{gnat1}, the Ada compiler)
8585 from @cite{dir} instead of the default location. Only use this switch
8586 when multiple versions of the GNAT compiler are available.
8587 See the "Options for Directory Search" section in the
8588 @cite{Using the GNU Compiler Collection (GCC)} manual for further details.
8589 You would normally use the @emph{-b} or @emph{-V} switch instead.
8599 Compile. Always use this switch when compiling Ada programs.
8601 Note: for some other languages when using @emph{gcc}, notably in
8602 the case of C and C++, it is possible to use
8603 use @emph{gcc} without a @emph{-c} switch to
8604 compile and link in one step. In the case of GNAT, you
8605 cannot use this approach, because the binder must be run
8606 and @emph{gcc} cannot be used to run the GNAT binder.
8609 @geindex -fcallgraph-info (gcc)
8614 @item @code{-fcallgraph-info[=su,da]}
8616 Makes the compiler output callgraph information for the program, on a
8617 per-file basis. The information is generated in the VCG format. It can
8618 be decorated with additional, per-node and/or per-edge information, if a
8619 list of comma-separated markers is additionally specified. When the
8620 @cite{su} marker is specified, the callgraph is decorated with stack usage
8621 information; it is equivalent to @emph{-fstack-usage}. When the @cite{da}
8622 marker is specified, the callgraph is decorated with information about
8623 dynamically allocated objects.
8626 @geindex -fdump-scos (gcc)
8631 @item @code{-fdump-scos}
8633 Generates SCO (Source Coverage Obligation) information in the ALI file.
8634 This information is used by advanced coverage tools. See unit @code{SCOs}
8635 in the compiler sources for details in files @code{scos.ads} and
8639 @geindex -fdump-xref (gcc)
8644 @item @code{-fdump-xref}
8646 Generates cross reference information in GLI files for C and C++ sources.
8647 The GLI files have the same syntax as the ALI files for Ada, and can be used
8648 for source navigation in IDEs and on the command line using e.g. gnatxref
8649 and the @emph{--ext=gli} switch.
8652 @geindex -flto (gcc)
8657 @item @code{-flto[=@emph{n}]}
8659 Enables Link Time Optimization. This switch must be used in conjunction
8660 with the traditional @emph{-Ox} switches and instructs the compiler to
8661 defer most optimizations until the link stage. The advantage of this
8662 approach is that the compiler can do a whole-program analysis and choose
8663 the best interprocedural optimization strategy based on a complete view
8664 of the program, instead of a fragmentary view with the usual approach.
8665 This can also speed up the compilation of big programs and reduce the
8666 size of the executable, compared with a traditional per-unit compilation
8667 with inlining across modules enabled by the @emph{-gnatn} switch.
8668 The drawback of this approach is that it may require more memory and that
8669 the debugging information generated by -g with it might be hardly usable.
8670 The switch, as well as the accompanying @emph{-Ox} switches, must be
8671 specified both for the compilation and the link phases.
8672 If the @cite{n} parameter is specified, the optimization and final code
8673 generation at link time are executed using @cite{n} parallel jobs by
8674 means of an installed @emph{make} program.
8677 @geindex -fno-inline (gcc)
8682 @item @code{-fno-inline}
8684 Suppresses all inlining, unless requested with pragma @cite{Inline_Always}. The
8685 effect is enforced regardless of other optimization or inlining switches.
8686 Note that inlining can also be suppressed on a finer-grained basis with
8687 pragma @cite{No_Inline}.
8690 @geindex -fno-inline-functions (gcc)
8695 @item @code{-fno-inline-functions}
8697 Suppresses automatic inlining of subprograms, which is enabled
8698 if @emph{-O3} is used.
8701 @geindex -fno-inline-small-functions (gcc)
8706 @item @code{-fno-inline-small-functions}
8708 Suppresses automatic inlining of small subprograms, which is enabled
8709 if @emph{-O2} is used.
8712 @geindex -fno-inline-functions-called-once (gcc)
8717 @item @code{-fno-inline-functions-called-once}
8719 Suppresses inlining of subprograms local to the unit and called once
8720 from within it, which is enabled if @emph{-O1} is used.
8723 @geindex -fno-ivopts (gcc)
8728 @item @code{-fno-ivopts}
8730 Suppresses high-level loop induction variable optimizations, which are
8731 enabled if @emph{-O1} is used. These optimizations are generally
8732 profitable but, for some specific cases of loops with numerous uses
8733 of the iteration variable that follow a common pattern, they may end
8734 up destroying the regularity that could be exploited at a lower level
8735 and thus producing inferior code.
8738 @geindex -fno-strict-aliasing (gcc)
8743 @item @code{-fno-strict-aliasing}
8745 Causes the compiler to avoid assumptions regarding non-aliasing
8746 of objects of different types. See
8747 @ref{f8,,Optimization and Strict Aliasing} for details.
8750 @geindex -fstack-check (gcc)
8755 @item @code{-fstack-check}
8757 Activates stack checking.
8758 See @ref{f9,,Stack Overflow Checking} for details.
8761 @geindex -fstack-usage (gcc)
8766 @item @code{-fstack-usage}
8768 Makes the compiler output stack usage information for the program, on a
8769 per-subprogram basis. See @ref{fa,,Static Stack Usage Analysis} for details.
8779 Generate debugging information. This information is stored in the object
8780 file and copied from there to the final executable file by the linker,
8781 where it can be read by the debugger. You must use the
8782 @emph{-g} switch if you plan on using the debugger.
8785 @geindex -gnat05 (gcc)
8790 @item @code{-gnat05}
8792 Allow full Ada 2005 features.
8795 @geindex -gnat12 (gcc)
8800 @item @code{-gnat12}
8802 Allow full Ada 2012 features.
8805 @geindex -gnat83 (gcc)
8807 @geindex -gnat2005 (gcc)
8812 @item @code{-gnat2005}
8814 Allow full Ada 2005 features (same as @emph{-gnat05})
8817 @geindex -gnat2012 (gcc)
8822 @item @code{-gnat2012}
8824 Allow full Ada 2012 features (same as @emph{-gnat12})
8826 @item @code{-gnat83}
8828 Enforce Ada 83 restrictions.
8831 @geindex -gnat95 (gcc)
8836 @item @code{-gnat95}
8838 Enforce Ada 95 restrictions.
8840 Note: for compatibility with some Ada 95 compilers which support only
8841 the @cite{overriding} keyword of Ada 2005, the @emph{-gnatd.D} switch can
8842 be used along with @emph{-gnat95} to achieve a similar effect with GNAT.
8844 @emph{-gnatd.D} instructs GNAT to consider @cite{overriding} as a keyword
8845 and handle its associated semantic checks, even in Ada 95 mode.
8848 @geindex -gnata (gcc)
8855 Assertions enabled. @cite{Pragma Assert} and @cite{pragma Debug} to be
8856 activated. Note that these pragmas can also be controlled using the
8857 configuration pragmas @cite{Assertion_Policy} and @cite{Debug_Policy}.
8858 It also activates pragmas @cite{Check}, @cite{Precondition}, and
8859 @cite{Postcondition}. Note that these pragmas can also be controlled
8860 using the configuration pragma @cite{Check_Policy}. In Ada 2012, it
8861 also activates all assertions defined in the RM as aspects: preconditions,
8862 postconditions, type invariants and (sub)type predicates. In all Ada modes,
8863 corresponding pragmas for type invariants and (sub)type predicates are
8864 also activated. The default is that all these assertions are disabled,
8865 and have no effect, other than being checked for syntactic validity, and
8866 in the case of subtype predicates, constructions such as membership tests
8867 still test predicates even if assertions are turned off.
8870 @geindex -gnatA (gcc)
8877 Avoid processing @code{gnat.adc}. If a @code{gnat.adc} file is present,
8881 @geindex -gnatb (gcc)
8888 Generate brief messages to @code{stderr} even if verbose mode set.
8891 @geindex -gnatB (gcc)
8898 Assume no invalid (bad) values except for 'Valid attribute use
8899 (@ref{fb,,Validity Checking}).
8902 @geindex -gnatc (gcc)
8909 Check syntax and semantics only (no code generation attempted). When the
8910 compiler is invoked by @emph{gnatmake}, if the switch @emph{-gnatc} is
8911 only given to the compiler (after @emph{-cargs} or in package Compiler of
8912 the project file, @emph{gnatmake} will fail because it will not find the
8913 object file after compilation. If @emph{gnatmake} is called with
8914 @emph{-gnatc} as a builder switch (before @emph{-cargs} or in package
8915 Builder of the project file) then @emph{gnatmake} will not fail because
8916 it will not look for the object files after compilation, and it will not try
8917 to build and link. This switch may not be given if a previous @cite{-gnatR}
8918 switch has been given, since @cite{-gnatR} requires that the code generator
8919 be called to complete determination of representation information.
8922 @geindex -gnatC (gcc)
8929 Generate CodePeer intermediate format (no code generation attempted).
8930 This switch will generate an intermediate representation suitable for
8931 use by CodePeer (@code{.scil} files). This switch is not compatible with
8932 code generation (it will, among other things, disable some switches such
8933 as -gnatn, and enable others such as -gnata).
8936 @geindex -gnatd (gcc)
8943 Specify debug options for the compiler. The string of characters after
8944 the @emph{-gnatd} specify the specific debug options. The possible
8945 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
8946 compiler source file @code{debug.adb} for details of the implemented
8947 debug options. Certain debug options are relevant to applications
8948 programmers, and these are documented at appropriate points in this
8952 @geindex -gnatD[nn] (gcc)
8959 Create expanded source files for source level debugging. This switch
8960 also suppress generation of cross-reference information
8961 (see @emph{-gnatx}). Note that this switch is not allowed if a previous
8962 -gnatR switch has been given, since these two switches are not compatible.
8965 @geindex -gnateA (gcc)
8970 @item @code{-gnateA}
8972 Check that the actual parameters of a subprogram call are not aliases of one
8973 another. To qualify as aliasing, the actuals must denote objects of a composite
8974 type, their memory locations must be identical or overlapping, and at least one
8975 of the corresponding formal parameters must be of mode OUT or IN OUT.
8978 type Rec_Typ is record
8979 Data : Integer := 0;
8982 function Self (Val : Rec_Typ) return Rec_Typ is
8987 procedure Detect_Aliasing (Val_1 : in out Rec_Typ; Val_2 : Rec_Typ) is
8990 end Detect_Aliasing;
8994 Detect_Aliasing (Obj, Obj);
8995 Detect_Aliasing (Obj, Self (Obj));
8998 In the example above, the first call to @cite{Detect_Aliasing} fails with a
8999 @cite{Program_Error} at runtime because the actuals for @cite{Val_1} and
9000 @cite{Val_2} denote the same object. The second call executes without raising
9001 an exception because @cite{Self(Obj)} produces an anonymous object which does
9002 not share the memory location of @cite{Obj}.
9005 @geindex -gnatec (gcc)
9010 @item @code{-gnatec=@emph{path}}
9012 Specify a configuration pragma file
9013 (the equal sign is optional)
9014 (@ref{7b,,The Configuration Pragmas Files}).
9017 @geindex -gnateC (gcc)
9022 @item @code{-gnateC}
9024 Generate CodePeer messages in a compiler-like format. This switch is only
9025 effective if @emph{-gnatcC} is also specified and requires an installation
9029 @geindex -gnated (gcc)
9034 @item @code{-gnated}
9036 Disable atomic synchronization
9039 @geindex -gnateD (gcc)
9044 @item @code{-gnateDsymbol[=@emph{value}]}
9046 Defines a symbol, associated with @cite{value}, for preprocessing.
9047 (@ref{1a,,Integrated Preprocessing}).
9050 @geindex -gnateE (gcc)
9055 @item @code{-gnateE}
9057 Generate extra information in exception messages. In particular, display
9058 extra column information and the value and range associated with index and
9059 range check failures, and extra column information for access checks.
9060 In cases where the compiler is able to determine at compile time that
9061 a check will fail, it gives a warning, and the extra information is not
9062 produced at run time.
9065 @geindex -gnatef (gcc)
9070 @item @code{-gnatef}
9072 Display full source path name in brief error messages.
9075 @geindex -gnateF (gcc)
9080 @item @code{-gnateF}
9082 Check for overflow on all floating-point operations, including those
9083 for unconstrained predefined types. See description of pragma
9084 @cite{Check_Float_Overflow} in GNAT RM.
9087 @geindex -gnateG (gcc)
9092 @item @code{-gnateG}
9094 Save result of preprocessing in a text file.
9097 @geindex -gnatei (gcc)
9102 @item @code{-gnatei@emph{nnn}}
9104 Set maximum number of instantiations during compilation of a single unit to
9105 @cite{nnn}. This may be useful in increasing the default maximum of 8000 for
9106 the rare case when a single unit legitimately exceeds this limit.
9109 @geindex -gnateI (gcc)
9114 @item @code{-gnateI@emph{nnn}}
9116 Indicates that the source is a multi-unit source and that the index of the
9117 unit to compile is @cite{nnn}. @cite{nnn} needs to be a positive number and need
9118 to be a valid index in the multi-unit source.
9121 @geindex -gnatel (gcc)
9126 @item @code{-gnatel}
9128 This switch can be used with the static elaboration model to issue info
9130 where implicit @cite{pragma Elaborate} and @cite{pragma Elaborate_All}
9131 are generated. This is useful in diagnosing elaboration circularities
9132 caused by these implicit pragmas when using the static elaboration
9133 model. See See the section in this guide on elaboration checking for
9134 further details. These messages are not generated by default, and are
9135 intended only for temporary use when debugging circularity problems.
9138 @geindex -gnatel (gcc)
9143 @item @code{-gnateL}
9145 This switch turns off the info messages about implicit elaboration pragmas.
9148 @geindex -gnatem (gcc)
9153 @item @code{-gnatem=@emph{path}}
9155 Specify a mapping file
9156 (the equal sign is optional)
9157 (@ref{fc,,Units to Sources Mapping Files}).
9160 @geindex -gnatep (gcc)
9165 @item @code{-gnatep=@emph{file}}
9167 Specify a preprocessing data file
9168 (the equal sign is optional)
9169 (@ref{1a,,Integrated Preprocessing}).
9172 @geindex -gnateP (gcc)
9177 @item @code{-gnateP}
9179 Turn categorization dependency errors into warnings.
9180 Ada requires that units that WITH one another have compatible categories, for
9181 example a Pure unit cannot WITH a Preelaborate unit. If this switch is used,
9182 these errors become warnings (which can be ignored, or suppressed in the usual
9183 manner). This can be useful in some specialized circumstances such as the
9184 temporary use of special test software.
9187 @geindex -gnateS (gcc)
9192 @item @code{-gnateS}
9194 Synonym of @emph{-fdump-scos}, kept for backwards compatibility.
9197 @geindex -gnatet=file (gcc)
9202 @item @code{-gnatet=@emph{path}}
9204 Generate target dependent information. The format of the output file is
9205 described in the section about switch @emph{-gnateT}.
9208 @geindex -gnateT (gcc)
9213 @item @code{-gnateT=@emph{path}}
9215 Read target dependent information, such as endianness or sizes and alignments
9216 of base type. If this switch is passed, the default target dependent
9217 information of the compiler is replaced by the one read from the input file.
9218 This is used by tools other than the compiler, e.g. to do
9219 semantic analysis of programs that will run on some other target than
9220 the machine on which the tool is run.
9222 The following target dependent values should be defined,
9223 where @cite{Nat} denotes a natural integer value, @cite{Pos} denotes a
9224 positive integer value, and fields marked with a question mark are
9225 boolean fields, where a value of 0 is False, and a value of 1 is True:
9228 Bits_BE : Nat; -- Bits stored big-endian?
9229 Bits_Per_Unit : Pos; -- Bits in a storage unit
9230 Bits_Per_Word : Pos; -- Bits in a word
9231 Bytes_BE : Nat; -- Bytes stored big-endian?
9232 Char_Size : Pos; -- Standard.Character'Size
9233 Double_Float_Alignment : Nat; -- Alignment of double float
9234 Double_Scalar_Alignment : Nat; -- Alignment of double length scalar
9235 Double_Size : Pos; -- Standard.Long_Float'Size
9236 Float_Size : Pos; -- Standard.Float'Size
9237 Float_Words_BE : Nat; -- Float words stored big-endian?
9238 Int_Size : Pos; -- Standard.Integer'Size
9239 Long_Double_Size : Pos; -- Standard.Long_Long_Float'Size
9240 Long_Long_Size : Pos; -- Standard.Long_Long_Integer'Size
9241 Long_Size : Pos; -- Standard.Long_Integer'Size
9242 Maximum_Alignment : Pos; -- Maximum permitted alignment
9243 Max_Unaligned_Field : Pos; -- Maximum size for unaligned bit field
9244 Pointer_Size : Pos; -- System.Address'Size
9245 Short_Enums : Nat; -- Short foreign convention enums?
9246 Short_Size : Pos; -- Standard.Short_Integer'Size
9247 Strict_Alignment : Nat; -- Strict alignment?
9248 System_Allocator_Alignment : Nat; -- Alignment for malloc calls
9249 Wchar_T_Size : Pos; -- Interfaces.C.wchar_t'Size
9250 Words_BE : Nat; -- Words stored big-endian?
9253 The format of the input file is as follows. First come the values of
9254 the variables defined above, with one line per value:
9260 where @cite{name} is the name of the parameter, spelled out in full,
9261 and cased as in the above list, and @cite{value} is an unsigned decimal
9262 integer. Two or more blanks separates the name from the value.
9264 All the variables must be present, in alphabetical order (i.e. the
9265 same order as the list above).
9267 Then there is a blank line to separate the two parts of the file. Then
9268 come the lines showing the floating-point types to be registered, with
9269 one line per registered mode:
9272 name digs float_rep size alignment
9275 where @cite{name} is the string name of the type (which can have
9276 single spaces embedded in the name (e.g. long double), @cite{digs} is
9277 the number of digits for the floating-point type, @cite{float_rep} is
9278 the float representation (I/V/A for IEEE-754-Binary, Vax_Native,
9279 AAMP), @cite{size} is the size in bits, @cite{alignment} is the
9280 alignment in bits. The name is followed by at least two blanks, fields
9281 are separated by at least one blank, and a LF character immediately
9282 follows the alignment field.
9284 Here is an example of a target parameterization file:
9292 Double_Float_Alignment 0
9293 Double_Scalar_Alignment 0
9298 Long_Double_Size 128
9301 Maximum_Alignment 16
9302 Max_Unaligned_Field 64
9306 System_Allocator_Alignment 16
9312 long double 18 I 80 128
9317 @geindex -gnateu (gcc)
9322 @item @code{-gnateu}
9324 Ignore unrecognized validity, warning, and style switches that
9325 appear after this switch is given. This may be useful when
9326 compiling sources developed on a later version of the compiler
9327 with an earlier version. Of course the earlier version must
9328 support this switch.
9331 @geindex -gnateV (gcc)
9336 @item @code{-gnateV}
9338 Check that all actual parameters of a subprogram call are valid according to
9339 the rules of validity checking (@ref{fb,,Validity Checking}).
9342 @geindex -gnateY (gcc)
9347 @item @code{-gnateY}
9349 Ignore all STYLE_CHECKS pragmas. Full legality checks
9350 are still carried out, but the pragmas have no effect
9351 on what style checks are active. This allows all style
9352 checking options to be controlled from the command line.
9355 @geindex -gnatE (gcc)
9362 Full dynamic elaboration checks.
9365 @geindex -gnatf (gcc)
9372 Full errors. Multiple errors per line, all undefined references, do not
9373 attempt to suppress cascaded errors.
9376 @geindex -gnatF (gcc)
9383 Externals names are folded to all uppercase.
9386 @geindex -gnatg (gcc)
9393 Internal GNAT implementation mode. This should not be used for
9394 applications programs, it is intended only for use by the compiler
9395 and its run-time library. For documentation, see the GNAT sources.
9396 Note that @emph{-gnatg} implies
9397 @emph{-gnatw.ge} and
9399 so that all standard warnings and all standard style options are turned on.
9400 All warnings and style messages are treated as errors.
9403 @geindex -gnatG[nn] (gcc)
9408 @item @code{-gnatG=nn}
9410 List generated expanded code in source form.
9413 @geindex -gnath (gcc)
9420 Output usage information. The output is written to @code{stdout}.
9423 @geindex -gnati (gcc)
9428 @item @code{-gnati@emph{c}}
9430 Identifier character set (@cite{c} = 1/2/3/4/8/9/p/f/n/w).
9431 For details of the possible selections for @cite{c},
9432 see @ref{4a,,Character Set Control}.
9435 @geindex -gnatI (gcc)
9442 Ignore representation clauses. When this switch is used,
9443 representation clauses are treated as comments. This is useful
9444 when initially porting code where you want to ignore rep clause
9445 problems, and also for compiling foreign code (particularly
9446 for use with ASIS). The representation clauses that are ignored
9447 are: enumeration_representation_clause, record_representation_clause,
9448 and attribute_definition_clause for the following attributes:
9449 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
9450 Object_Size, Size, Small, Stream_Size, and Value_Size.
9451 Note that this option should be used only for compiling -- the
9452 code is likely to malfunction at run time.
9454 Note that when @cite{-gnatct} is used to generate trees for input
9455 into @cite{ASIS} tools, these representation clauses are removed
9456 from the tree and ignored. This means that the tool will not see them.
9459 @geindex -gnatjnn (gcc)
9464 @item @code{-gnatj@emph{nn}}
9466 Reformat error messages to fit on @cite{nn} character lines
9469 @geindex -gnatk (gcc)
9474 @item @code{-gnatk=@emph{n}}
9476 Limit file names to @cite{n} (1-999) characters (@cite{k} = krunch).
9479 @geindex -gnatl (gcc)
9486 Output full source listing with embedded error messages.
9489 @geindex -gnatL (gcc)
9496 Used in conjunction with -gnatG or -gnatD to intersperse original
9497 source lines (as comment lines with line numbers) in the expanded
9501 @geindex -gnatm (gcc)
9506 @item @code{-gnatm=@emph{n}}
9508 Limit number of detected error or warning messages to @cite{n}
9509 where @cite{n} is in the range 1..999999. The default setting if
9510 no switch is given is 9999. If the number of warnings reaches this
9511 limit, then a message is output and further warnings are suppressed,
9512 but the compilation is continued. If the number of error messages
9513 reaches this limit, then a message is output and the compilation
9514 is abandoned. The equal sign here is optional. A value of zero
9515 means that no limit applies.
9518 @geindex -gnatn (gcc)
9523 @item @code{-gnatn[12]}
9525 Activate inlining for subprograms for which pragma @cite{Inline} is
9526 specified. This inlining is performed by the GCC back-end. An optional
9527 digit sets the inlining level: 1 for moderate inlining across modules
9528 or 2 for full inlining across modules. If no inlining level is specified,
9529 the compiler will pick it based on the optimization level.
9532 @geindex -gnatN (gcc)
9539 Activate front end inlining for subprograms for which
9540 pragma @cite{Inline} is specified. This inlining is performed
9541 by the front end and will be visible in the
9542 @emph{-gnatG} output.
9544 When using a gcc-based back end (in practice this means using any version
9545 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
9546 @emph{-gnatN} is deprecated, and the use of @emph{-gnatn} is preferred.
9547 Historically front end inlining was more extensive than the gcc back end
9548 inlining, but that is no longer the case.
9551 @geindex -gnato0 (gcc)
9556 @item @code{-gnato0}
9558 Suppresses overflow checking. This causes the behavior of the compiler to
9559 match the default for older versions where overflow checking was suppressed
9560 by default. This is equivalent to having
9561 @cite{pragma Suppress (Overflow_Mode)} in a configuration pragma file.
9564 @geindex -gnato?? (gcc)
9569 @item @code{-gnato??}
9571 Set default mode for handling generation of code to avoid intermediate
9572 arithmetic overflow. Here @cite{??} is two digits, a
9573 single digit, or nothing. Each digit is one of the digits @cite{1}
9577 @multitable {xxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
9592 All intermediate overflows checked against base type (@cite{STRICT})
9600 Minimize intermediate overflows (@cite{MINIMIZED})
9608 Eliminate intermediate overflows (@cite{ELIMINATED})
9613 If only one digit appears then it applies to all
9614 cases; if two digits are given, then the first applies outside
9615 assertions, and the second within assertions.
9617 If no digits follow the @emph{-gnato}, then it is equivalent to
9619 causing all intermediate overflows to be handled in strict mode.
9621 This switch also causes arithmetic overflow checking to be performed
9622 (as though @cite{pragma Unsuppress (Overflow_Mode)} had been specified.
9624 The default if no option @emph{-gnato} is given is that overflow handling
9625 is in @cite{STRICT} mode (computations done using the base type), and that
9626 overflow checking is enabled.
9628 Note that division by zero is a separate check that is not
9629 controlled by this switch (division by zero checking is on by default).
9631 See also @ref{fd,,Specifying the Desired Mode}.
9634 @geindex -gnatp (gcc)
9641 Suppress all checks. See @ref{fe,,Run-Time Checks} for details. This switch
9642 has no effect if cancelled by a subsequent @emph{-gnat-p} switch.
9645 @geindex -gnat-p (gcc)
9650 @item @code{-gnat-p}
9652 Cancel effect of previous @emph{-gnatp} switch.
9655 @geindex -gnatP (gcc)
9662 Enable polling. This is required on some systems (notably Windows NT) to
9663 obtain asynchronous abort and asynchronous transfer of control capability.
9664 See @cite{Pragma_Polling} in the @cite{GNAT_Reference_Manual} for full
9668 @geindex -gnatq (gcc)
9675 Don't quit. Try semantics, even if parse errors.
9678 @geindex -gnatQ (gcc)
9685 Don't quit. Generate @code{ALI} and tree files even if illegalities.
9686 Note that code generation is still suppressed in the presence of any
9687 errors, so even with @emph{-gnatQ} no object file is generated.
9690 @geindex -gnatr (gcc)
9697 Treat pragma Restrictions as Restriction_Warnings.
9700 @geindex -gnatR (gcc)
9705 @item @code{-gnatR[0/1/2/3[s]]}
9707 Output representation information for declared types and objects.
9708 Note that this switch is not allowed if a previous @cite{-gnatD} switch has
9709 been given, since these two switches are not compatible.
9711 @item @code{-gnatRm[s]}
9713 Output convention and parameter passing mechanisms for all subprograms.
9716 @geindex -gnats (gcc)
9726 @geindex -gnatS (gcc)
9733 Print package Standard.
9736 @geindex -gnatt (gcc)
9743 Generate tree output file.
9746 @geindex -gnatT (gcc)
9751 @item @code{-gnatT@emph{nnn}}
9753 All compiler tables start at @cite{nnn} times usual starting size.
9756 @geindex -gnatu (gcc)
9763 List units for this compilation.
9766 @geindex -gnatU (gcc)
9773 Tag all error messages with the unique string 'error:'
9776 @geindex -gnatv (gcc)
9783 Verbose mode. Full error output with source lines to @code{stdout}.
9786 @geindex -gnatV (gcc)
9793 Control level of validity checking (@ref{fb,,Validity Checking}).
9796 @geindex -gnatw (gcc)
9801 @item @code{-gnatw@emph{xxx}}
9804 @cite{xxx} is a string of option letters that denotes
9805 the exact warnings that
9806 are enabled or disabled (@ref{ff,,Warning Message Control}).
9809 @geindex -gnatW (gcc)
9814 @item @code{-gnatW@emph{e}}
9816 Wide character encoding method
9817 (@cite{e}=n/h/u/s/e/8).
9820 @geindex -gnatx (gcc)
9827 Suppress generation of cross-reference information.
9830 @geindex -gnatX (gcc)
9837 Enable GNAT implementation extensions and latest Ada version.
9840 @geindex -gnaty (gcc)
9847 Enable built-in style checks (@ref{100,,Style Checking}).
9850 @geindex -gnatz (gcc)
9855 @item @code{-gnatz@emph{m}}
9857 Distribution stub generation and compilation
9858 (@cite{m}=r/c for receiver/caller stubs).
9866 @item @code{-I@emph{dir}}
9870 Direct GNAT to search the @cite{dir} directory for source files needed by
9871 the current compilation
9872 (see @ref{8e,,Search Paths and the Run-Time Library (RTL)}).
9884 Except for the source file named in the command line, do not look for source
9885 files in the directory containing the source file named in the command line
9886 (see @ref{8e,,Search Paths and the Run-Time Library (RTL)}).
9894 @item @code{-o @emph{file}}
9896 This switch is used in @emph{gcc} to redirect the generated object file
9897 and its associated ALI file. Beware of this switch with GNAT, because it may
9898 cause the object file and ALI file to have different names which in turn
9899 may confuse the binder and the linker.
9902 @geindex -nostdinc (gcc)
9907 @item @code{-nostdinc}
9909 Inhibit the search of the default location for the GNAT Run Time
9910 Library (RTL) source files.
9913 @geindex -nostdlib (gcc)
9918 @item @code{-nostdlib}
9920 Inhibit the search of the default location for the GNAT Run Time
9921 Library (RTL) ALI files.
9929 @item @code{-O[@emph{n}]}
9931 @cite{n} controls the optimization level:
9934 @multitable {xxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
9949 No optimization, the default setting if no @emph{-O} appears
9957 Normal optimization, the default if you specify @emph{-O} without an
9958 operand. A good compromise between code quality and compilation
9967 Extensive optimization, may improve execution time, possibly at
9968 the cost of substantially increased compilation time.
9976 Same as @emph{-O2}, and also includes inline expansion for small
9977 subprograms in the same unit.
9985 Optimize space usage
9990 See also @ref{101,,Optimization Levels}.
9993 @geindex -pass-exit-codes (gcc)
9998 @item @code{-pass-exit-codes}
10000 Catch exit codes from the compiler and use the most meaningful as
10004 @geindex --RTS (gcc)
10009 @item @code{--RTS=@emph{rts-path}}
10011 Specifies the default location of the runtime library. Same meaning as the
10012 equivalent @emph{gnatmake} flag (@ref{df,,Switches for gnatmake}).
10022 Used in place of @emph{-c} to
10023 cause the assembler source file to be
10024 generated, using @code{.s} as the extension,
10025 instead of the object file.
10026 This may be useful if you need to examine the generated assembly code.
10029 @geindex -fverbose-asm (gcc)
10034 @item @code{-fverbose-asm}
10036 Used in conjunction with @emph{-S}
10037 to cause the generated assembly code file to be annotated with variable
10038 names, making it significantly easier to follow.
10048 Show commands generated by the @emph{gcc} driver. Normally used only for
10049 debugging purposes or if you need to be sure what version of the
10050 compiler you are executing.
10058 @item @code{-V @emph{ver}}
10060 Execute @cite{ver} version of the compiler. This is the @emph{gcc}
10061 version, not the GNAT version.
10071 Turn off warnings generated by the back end of the compiler. Use of
10072 this switch also causes the default for front end warnings to be set
10073 to suppress (as though @emph{-gnatws} had appeared at the start of
10077 @geindex Combining GNAT switches
10079 You may combine a sequence of GNAT switches into a single switch. For
10080 example, the combined switch
10089 is equivalent to specifying the following sequence of switches:
10094 -gnato -gnatf -gnati3
10098 The following restrictions apply to the combination of switches
10105 The switch @emph{-gnatc} if combined with other switches must come
10106 first in the string.
10109 The switch @emph{-gnats} if combined with other switches must come
10110 first in the string.
10114 @emph{-gnatzc} and @emph{-gnatzr} may not be combined with any other
10115 switches, and only one of them may appear in the command line.
10118 The switch @emph{-gnat-p} may not be combined with any other switch.
10121 Once a 'y' appears in the string (that is a use of the @emph{-gnaty}
10122 switch), then all further characters in the switch are interpreted
10123 as style modifiers (see description of @emph{-gnaty}).
10126 Once a 'd' appears in the string (that is a use of the @emph{-gnatd}
10127 switch), then all further characters in the switch are interpreted
10128 as debug flags (see description of @emph{-gnatd}).
10131 Once a 'w' appears in the string (that is a use of the @emph{-gnatw}
10132 switch), then all further characters in the switch are interpreted
10133 as warning mode modifiers (see description of @emph{-gnatw}).
10136 Once a 'V' appears in the string (that is a use of the @emph{-gnatV}
10137 switch), then all further characters in the switch are interpreted
10138 as validity checking options (@ref{fb,,Validity Checking}).
10141 Option 'em', 'ec', 'ep', 'l=' and 'R' must be the last options in
10142 a combined list of options.
10145 @node Output and Error Message Control,Warning Message Control,Alphabetical List of All Switches,Compiler Switches
10146 @anchor{gnat_ugn/building_executable_programs_with_gnat id14}@anchor{102}@anchor{gnat_ugn/building_executable_programs_with_gnat output-and-error-message-control}@anchor{103}
10147 @subsection Output and Error Message Control
10152 The standard default format for error messages is called 'brief format'.
10153 Brief format messages are written to @code{stderr} (the standard error
10154 file) and have the following form:
10157 e.adb:3:04: Incorrect spelling of keyword "function"
10158 e.adb:4:20: ";" should be "is"
10161 The first integer after the file name is the line number in the file,
10162 and the second integer is the column number within the line.
10163 @cite{GPS} can parse the error messages
10164 and point to the referenced character.
10165 The following switches provide control over the error message
10168 @geindex -gnatv (gcc)
10173 @item @code{-gnatv}
10175 The @cite{v} stands for verbose.
10176 The effect of this setting is to write long-format error
10177 messages to @code{stdout} (the standard output file.
10178 The same program compiled with the
10179 @emph{-gnatv} switch would generate:
10182 3. funcion X (Q : Integer)
10184 >>> Incorrect spelling of keyword "function"
10187 >>> ";" should be "is"
10190 The vertical bar indicates the location of the error, and the @code{>>>}
10191 prefix can be used to search for error messages. When this switch is
10192 used the only source lines output are those with errors.
10195 @geindex -gnatl (gcc)
10200 @item @code{-gnatl}
10202 The @cite{l} stands for list.
10203 This switch causes a full listing of
10204 the file to be generated. In the case where a body is
10205 compiled, the corresponding spec is also listed, along
10206 with any subunits. Typical output from compiling a package
10207 body @code{p.adb} might look like:
10212 1. package body p is
10214 3. procedure a is separate;
10225 2. pragma Elaborate_Body
10246 When you specify the @emph{-gnatv} or @emph{-gnatl} switches and
10247 standard output is redirected, a brief summary is written to
10248 @code{stderr} (standard error) giving the number of error messages and
10249 warning messages generated.
10252 @geindex -gnatl=fname (gcc)
10257 @item @code{-gnatl=@emph{fname}}
10259 This has the same effect as @emph{-gnatl} except that the output is
10260 written to a file instead of to standard output. If the given name
10261 @code{fname} does not start with a period, then it is the full name
10262 of the file to be written. If @code{fname} is an extension, it is
10263 appended to the name of the file being compiled. For example, if
10264 file @code{xyz.adb} is compiled with @emph{-gnatl=.lst},
10265 then the output is written to file xyz.adb.lst.
10268 @geindex -gnatU (gcc)
10273 @item @code{-gnatU}
10275 This switch forces all error messages to be preceded by the unique
10276 string 'error:'. This means that error messages take a few more
10277 characters in space, but allows easy searching for and identification
10281 @geindex -gnatb (gcc)
10286 @item @code{-gnatb}
10288 The @cite{b} stands for brief.
10289 This switch causes GNAT to generate the
10290 brief format error messages to @code{stderr} (the standard error
10291 file) as well as the verbose
10292 format message or full listing (which as usual is written to
10293 @code{stdout} (the standard output file).
10296 @geindex -gnatm (gcc)
10301 @item @code{-gnatm=@emph{n}}
10303 The @cite{m} stands for maximum.
10304 @cite{n} is a decimal integer in the
10305 range of 1 to 999999 and limits the number of error or warning
10306 messages to be generated. For example, using
10307 @emph{-gnatm2} might yield
10310 e.adb:3:04: Incorrect spelling of keyword "function"
10311 e.adb:5:35: missing ".."
10312 fatal error: maximum number of errors detected
10313 compilation abandoned
10316 The default setting if
10317 no switch is given is 9999. If the number of warnings reaches this
10318 limit, then a message is output and further warnings are suppressed,
10319 but the compilation is continued. If the number of error messages
10320 reaches this limit, then a message is output and the compilation
10321 is abandoned. A value of zero means that no limit applies.
10323 Note that the equal sign is optional, so the switches
10324 @emph{-gnatm2} and @emph{-gnatm=2} are equivalent.
10327 @geindex -gnatf (gcc)
10332 @item @code{-gnatf}
10334 @geindex Error messages
10335 @geindex suppressing
10337 The @cite{f} stands for full.
10338 Normally, the compiler suppresses error messages that are likely to be
10339 redundant. This switch causes all error
10340 messages to be generated. In particular, in the case of
10341 references to undefined variables. If a given variable is referenced
10342 several times, the normal format of messages is
10345 e.adb:7:07: "V" is undefined (more references follow)
10348 where the parenthetical comment warns that there are additional
10349 references to the variable @cite{V}. Compiling the same program with the
10350 @emph{-gnatf} switch yields
10353 e.adb:7:07: "V" is undefined
10354 e.adb:8:07: "V" is undefined
10355 e.adb:8:12: "V" is undefined
10356 e.adb:8:16: "V" is undefined
10357 e.adb:9:07: "V" is undefined
10358 e.adb:9:12: "V" is undefined
10361 The @emph{-gnatf} switch also generates additional information for
10362 some error messages. Some examples are:
10368 Details on possibly non-portable unchecked conversion
10371 List possible interpretations for ambiguous calls
10374 Additional details on incorrect parameters
10378 @geindex -gnatjnn (gcc)
10383 @item @code{-gnatjnn}
10385 In normal operation mode (or if @emph{-gnatj0} is used), then error messages
10386 with continuation lines are treated as though the continuation lines were
10387 separate messages (and so a warning with two continuation lines counts as
10388 three warnings, and is listed as three separate messages).
10390 If the @emph{-gnatjnn} switch is used with a positive value for nn, then
10391 messages are output in a different manner. A message and all its continuation
10392 lines are treated as a unit, and count as only one warning or message in the
10393 statistics totals. Furthermore, the message is reformatted so that no line
10394 is longer than nn characters.
10397 @geindex -gnatq (gcc)
10402 @item @code{-gnatq}
10404 The @cite{q} stands for quit (really 'don't quit').
10405 In normal operation mode, the compiler first parses the program and
10406 determines if there are any syntax errors. If there are, appropriate
10407 error messages are generated and compilation is immediately terminated.
10409 GNAT to continue with semantic analysis even if syntax errors have been
10410 found. This may enable the detection of more errors in a single run. On
10411 the other hand, the semantic analyzer is more likely to encounter some
10412 internal fatal error when given a syntactically invalid tree.
10415 @geindex -gnatQ (gcc)
10420 @item @code{-gnatQ}
10422 In normal operation mode, the @code{ALI} file is not generated if any
10423 illegalities are detected in the program. The use of @emph{-gnatQ} forces
10424 generation of the @code{ALI} file. This file is marked as being in
10425 error, so it cannot be used for binding purposes, but it does contain
10426 reasonably complete cross-reference information, and thus may be useful
10427 for use by tools (e.g., semantic browsing tools or integrated development
10428 environments) that are driven from the @code{ALI} file. This switch
10429 implies @emph{-gnatq}, since the semantic phase must be run to get a
10430 meaningful ALI file.
10432 In addition, if @emph{-gnatt} is also specified, then the tree file is
10433 generated even if there are illegalities. It may be useful in this case
10434 to also specify @emph{-gnatq} to ensure that full semantic processing
10435 occurs. The resulting tree file can be processed by ASIS, for the purpose
10436 of providing partial information about illegal units, but if the error
10437 causes the tree to be badly malformed, then ASIS may crash during the
10440 When @emph{-gnatQ} is used and the generated @code{ALI} file is marked as
10441 being in error, @emph{gnatmake} will attempt to recompile the source when it
10442 finds such an @code{ALI} file, including with switch @emph{-gnatc}.
10444 Note that @emph{-gnatQ} has no effect if @emph{-gnats} is specified,
10445 since ALI files are never generated if @emph{-gnats} is set.
10448 @node Warning Message Control,Debugging and Assertion Control,Output and Error Message Control,Compiler Switches
10449 @anchor{gnat_ugn/building_executable_programs_with_gnat warning-message-control}@anchor{ff}@anchor{gnat_ugn/building_executable_programs_with_gnat id15}@anchor{104}
10450 @subsection Warning Message Control
10453 @geindex Warning messages
10455 In addition to error messages, which correspond to illegalities as defined
10456 in the Ada Reference Manual, the compiler detects two kinds of warning
10459 First, the compiler considers some constructs suspicious and generates a
10460 warning message to alert you to a possible error. Second, if the
10461 compiler detects a situation that is sure to raise an exception at
10462 run time, it generates a warning message. The following shows an example
10463 of warning messages:
10466 e.adb:4:24: warning: creation of object may raise Storage_Error
10467 e.adb:10:17: warning: static value out of range
10468 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
10471 GNAT considers a large number of situations as appropriate
10472 for the generation of warning messages. As always, warnings are not
10473 definite indications of errors. For example, if you do an out-of-range
10474 assignment with the deliberate intention of raising a
10475 @cite{Constraint_Error} exception, then the warning that may be
10476 issued does not indicate an error. Some of the situations for which GNAT
10477 issues warnings (at least some of the time) are given in the following
10478 list. This list is not complete, and new warnings are often added to
10479 subsequent versions of GNAT. The list is intended to give a general idea
10480 of the kinds of warnings that are generated.
10486 Possible infinitely recursive calls
10489 Out-of-range values being assigned
10492 Possible order of elaboration problems
10495 Size not a multiple of alignment for a record type
10498 Assertions (pragma Assert) that are sure to fail
10504 Address clauses with possibly unaligned values, or where an attempt is
10505 made to overlay a smaller variable with a larger one.
10508 Fixed-point type declarations with a null range
10511 Direct_IO or Sequential_IO instantiated with a type that has access values
10514 Variables that are never assigned a value
10517 Variables that are referenced before being initialized
10520 Task entries with no corresponding @cite{accept} statement
10523 Duplicate accepts for the same task entry in a @cite{select}
10526 Objects that take too much storage
10529 Unchecked conversion between types of differing sizes
10532 Missing @cite{return} statement along some execution path in a function
10535 Incorrect (unrecognized) pragmas
10538 Incorrect external names
10541 Allocation from empty storage pool
10544 Potentially blocking operation in protected type
10547 Suspicious parenthesization of expressions
10550 Mismatching bounds in an aggregate
10553 Attempt to return local value by reference
10556 Premature instantiation of a generic body
10559 Attempt to pack aliased components
10562 Out of bounds array subscripts
10565 Wrong length on string assignment
10568 Violations of style rules if style checking is enabled
10571 Unused @emph{with} clauses
10574 @cite{Bit_Order} usage that does not have any effect
10577 @cite{Standard.Duration} used to resolve universal fixed expression
10580 Dereference of possibly null value
10583 Declaration that is likely to cause storage error
10586 Internal GNAT unit @emph{with}ed by application unit
10589 Values known to be out of range at compile time
10592 Unreferenced or unmodified variables. Note that a special
10593 exemption applies to variables which contain any of the substrings
10594 @cite{DISCARD@comma{} DUMMY@comma{} IGNORE@comma{} JUNK@comma{} UNUSED}, in any casing. Such variables
10595 are considered likely to be intentionally used in a situation where
10596 otherwise a warning would be given, so warnings of this kind are
10597 always suppressed for such variables.
10600 Address overlays that could clobber memory
10603 Unexpected initialization when address clause present
10606 Bad alignment for address clause
10609 Useless type conversions
10612 Redundant assignment statements and other redundant constructs
10615 Useless exception handlers
10618 Accidental hiding of name by child unit
10621 Access before elaboration detected at compile time
10624 A range in a @cite{for} loop that is known to be null or might be null
10627 The following section lists compiler switches that are available
10628 to control the handling of warning messages. It is also possible
10629 to exercise much finer control over what warnings are issued and
10630 suppressed using the GNAT pragma Warnings (see the description
10631 of the pragma in the @cite{GNAT_Reference_manual}).
10633 @geindex -gnatwa (gcc)
10638 @item @code{-gnatwa}
10640 @emph{Activate most optional warnings.}
10642 This switch activates most optional warning messages. See the remaining list
10643 in this section for details on optional warning messages that can be
10644 individually controlled. The warnings that are not turned on by this
10651 @code{-gnatwd} (implicit dereferencing)
10654 @code{-gnatw.d} (tag warnings with -gnatw switch)
10657 @code{-gnatwh} (hiding)
10660 @code{-gnatw.h} (holes in record layouts)
10663 @code{-gnatw.k} (redefinition of names in standard)
10666 @code{-gnatwl} (elaboration warnings)
10669 @code{-gnatw.l} (inherited aspects)
10672 @code{-gnatw.n} (atomic synchronization)
10675 @code{-gnatwo} (address clause overlay)
10678 @code{-gnatw.o} (values set by out parameters ignored)
10681 @code{-gnatw.s} (overridden size clause)
10684 @code{-gnatwt} (tracking of deleted conditional code)
10687 @code{-gnatw.u} (unordered enumeration)
10690 @code{-gnatw.w} (use of Warnings Off)
10693 @code{-gnatw.y} (reasons for package needing body)
10696 All other optional warnings are turned on.
10699 @geindex -gnatwA (gcc)
10704 @item @code{-gnatwA}
10706 @emph{Suppress all optional errors.}
10708 This switch suppresses all optional warning messages, see remaining list
10709 in this section for details on optional warning messages that can be
10710 individually controlled. Note that unlike switch @emph{-gnatws}, the
10711 use of switch @emph{-gnatwA} does not suppress warnings that are
10712 normally given unconditionally and cannot be individually controlled
10713 (for example, the warning about a missing exit path in a function).
10714 Also, again unlike switch @emph{-gnatws}, warnings suppressed by
10715 the use of switch @emph{-gnatwA} can be individually turned back
10716 on. For example the use of switch @emph{-gnatwA} followed by
10717 switch @emph{-gnatwd} will suppress all optional warnings except
10718 the warnings for implicit dereferencing.
10721 @geindex -gnatw.a (gcc)
10726 @item @code{-gnatw.a}
10728 @emph{Activate warnings on failing assertions.}
10730 @geindex Assert failures
10732 This switch activates warnings for assertions where the compiler can tell at
10733 compile time that the assertion will fail. Note that this warning is given
10734 even if assertions are disabled. The default is that such warnings are
10738 @geindex -gnatw.A (gcc)
10743 @item @code{-gnatw.A}
10745 @emph{Suppress warnings on failing assertions.}
10747 @geindex Assert failures
10749 This switch suppresses warnings for assertions where the compiler can tell at
10750 compile time that the assertion will fail.
10753 @geindex -gnatwb (gcc)
10758 @item @code{-gnatwb}
10760 @emph{Activate warnings on bad fixed values.}
10762 @geindex Bad fixed values
10764 @geindex Fixed-point Small value
10766 @geindex Small value
10768 This switch activates warnings for static fixed-point expressions whose
10769 value is not an exact multiple of Small. Such values are implementation
10770 dependent, since an implementation is free to choose either of the multiples
10771 that surround the value. GNAT always chooses the closer one, but this is not
10772 required behavior, and it is better to specify a value that is an exact
10773 multiple, ensuring predictable execution. The default is that such warnings
10777 @geindex -gnatwB (gcc)
10782 @item @code{-gnatwB}
10784 @emph{Suppress warnings on bad fixed values.}
10786 This switch suppresses warnings for static fixed-point expressions whose
10787 value is not an exact multiple of Small.
10790 @geindex -gnatw.b (gcc)
10795 @item @code{-gnatw.b}
10797 @emph{Activate warnings on biased representation.}
10799 @geindex Biased representation
10801 This switch activates warnings when a size clause, value size clause, component
10802 clause, or component size clause forces the use of biased representation for an
10803 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
10804 to represent 10/11). The default is that such warnings are generated.
10807 @geindex -gnatwB (gcc)
10812 @item @code{-gnatw.B}
10814 @emph{Suppress warnings on biased representation.}
10816 This switch suppresses warnings for representation clauses that force the use
10817 of biased representation.
10820 @geindex -gnatwc (gcc)
10825 @item @code{-gnatwc}
10827 @emph{Activate warnings on conditionals.}
10829 @geindex Conditionals
10832 This switch activates warnings for conditional expressions used in
10833 tests that are known to be True or False at compile time. The default
10834 is that such warnings are not generated.
10835 Note that this warning does
10836 not get issued for the use of boolean variables or constants whose
10837 values are known at compile time, since this is a standard technique
10838 for conditional compilation in Ada, and this would generate too many
10839 false positive warnings.
10841 This warning option also activates a special test for comparisons using
10842 the operators '>=' and' <='.
10843 If the compiler can tell that only the equality condition is possible,
10844 then it will warn that the '>' or '<' part of the test
10845 is useless and that the operator could be replaced by '='.
10846 An example would be comparing a @cite{Natural} variable <= 0.
10848 This warning option also generates warnings if
10849 one or both tests is optimized away in a membership test for integer
10850 values if the result can be determined at compile time. Range tests on
10851 enumeration types are not included, since it is common for such tests
10852 to include an end point.
10854 This warning can also be turned on using @emph{-gnatwa}.
10857 @geindex -gnatwC (gcc)
10862 @item @code{-gnatwC}
10864 @emph{Suppress warnings on conditionals.}
10866 This switch suppresses warnings for conditional expressions used in
10867 tests that are known to be True or False at compile time.
10870 @geindex -gnatw.c (gcc)
10875 @item @code{-gnatw.c}
10877 @emph{Activate warnings on missing component clauses.}
10879 @geindex Component clause
10882 This switch activates warnings for record components where a record
10883 representation clause is present and has component clauses for the
10884 majority, but not all, of the components. A warning is given for each
10885 component for which no component clause is present.
10888 @geindex -gnatwC (gcc)
10893 @item @code{-gnatw.C}
10895 @emph{Suppress warnings on missing component clauses.}
10897 This switch suppresses warnings for record components that are
10898 missing a component clause in the situation described above.
10901 @geindex -gnatwd (gcc)
10906 @item @code{-gnatwd}
10908 @emph{Activate warnings on implicit dereferencing.}
10910 If this switch is set, then the use of a prefix of an access type
10911 in an indexed component, slice, or selected component without an
10912 explicit @cite{.all} will generate a warning. With this warning
10913 enabled, access checks occur only at points where an explicit
10914 @cite{.all} appears in the source code (assuming no warnings are
10915 generated as a result of this switch). The default is that such
10916 warnings are not generated.
10919 @geindex -gnatwD (gcc)
10924 @item @code{-gnatwD}
10926 @emph{Suppress warnings on implicit dereferencing.}
10928 @geindex Implicit dereferencing
10930 @geindex Dereferencing
10933 This switch suppresses warnings for implicit dereferences in
10934 indexed components, slices, and selected components.
10937 @geindex -gnatw.d (gcc)
10942 @item @code{-gnatw.d}
10944 @emph{Activate tagging of warning and info messages.}
10946 If this switch is set, then warning messages are tagged, with one of the
10956 Used to tag warnings controlled by the switch @emph{-gnatwx} where x
10961 Used to tag warnings controlled by the switch @emph{-gnatw.x} where x
10966 Used to tag elaboration information (info) messages generated when the
10967 static model of elaboration is used and the @emph{-gnatel} switch is set.
10970 @emph{[restriction warning]}
10971 Used to tag warning messages for restriction violations, activated by use
10972 of the pragma @emph{Restriction_Warnings}.
10975 @emph{[warning-as-error]}
10976 Used to tag warning messages that have been converted to error messages by
10977 use of the pragma Warning_As_Error. Note that such warnings are prefixed by
10978 the string "error: " rather than "warning: ".
10981 @emph{[enabled by default]}
10982 Used to tag all other warnings that are always given by default, unless
10983 warnings are completely suppressed using pragma @emph{Warnings(Off)} or
10984 the switch @emph{-gnatws}.
10989 @geindex -gnatw.d (gcc)
10994 @item @code{-gnatw.D}
10996 @emph{Deactivate tagging of warning and info messages messages.}
10998 If this switch is set, then warning messages return to the default
10999 mode in which warnings and info messages are not tagged as described above for
11003 @geindex -gnatwe (gcc)
11006 @geindex treat as error
11011 @item @code{-gnatwe}
11013 @emph{Treat warnings and style checks as errors.}
11015 This switch causes warning messages and style check messages to be
11017 The warning string still appears, but the warning messages are counted
11018 as errors, and prevent the generation of an object file. Note that this
11019 is the only -gnatw switch that affects the handling of style check messages.
11020 Note also that this switch has no effect on info (information) messages, which
11021 are not treated as errors if this switch is present.
11024 @geindex -gnatw.e (gcc)
11029 @item @code{-gnatw.e}
11031 @emph{Activate every optional warning}
11034 @geindex activate every optional warning
11036 This switch activates all optional warnings, including those which
11037 are not activated by @cite{-gnatwa}. The use of this switch is not
11038 recommended for normal use. If you turn this switch on, it is almost
11039 certain that you will get large numbers of useless warnings. The
11040 warnings that are excluded from @cite{-gnatwa} are typically highly
11041 specialized warnings that are suitable for use only in code that has
11042 been specifically designed according to specialized coding rules.
11045 @geindex -gnatwf (gcc)
11050 @item @code{-gnatwf}
11052 @emph{Activate warnings on unreferenced formals.}
11055 @geindex unreferenced
11057 This switch causes a warning to be generated if a formal parameter
11058 is not referenced in the body of the subprogram. This warning can
11059 also be turned on using @emph{-gnatwu}. The
11060 default is that these warnings are not generated.
11063 @geindex -gnatwF (gcc)
11068 @item @code{-gnatwF}
11070 @emph{Suppress warnings on unreferenced formals.}
11072 This switch suppresses warnings for unreferenced formal
11073 parameters. Note that the
11074 combination @emph{-gnatwu} followed by @emph{-gnatwF} has the
11075 effect of warning on unreferenced entities other than subprogram
11079 @geindex -gnatwg (gcc)
11084 @item @code{-gnatwg}
11086 @emph{Activate warnings on unrecognized pragmas.}
11089 @geindex unrecognized
11091 This switch causes a warning to be generated if an unrecognized
11092 pragma is encountered. Apart from issuing this warning, the
11093 pragma is ignored and has no effect. The default
11094 is that such warnings are issued (satisfying the Ada Reference
11095 Manual requirement that such warnings appear).
11098 @geindex -gnatwG (gcc)
11103 @item @code{-gnatwG}
11105 @emph{Suppress warnings on unrecognized pragmas.}
11107 This switch suppresses warnings for unrecognized pragmas.
11110 @geindex -gnatw.g (gcc)
11115 @item @code{-gnatw.g}
11117 @emph{Warnings used for GNAT sources}
11119 This switch sets the warning categories that are used by the standard
11120 GNAT style. Currently this is equivalent to
11121 @emph{-gnatwAao.sI.C.V.X}
11122 but more warnings may be added in the future without advanced notice.
11125 @geindex -gnatwh (gcc)
11130 @item @code{-gnatwh}
11132 @emph{Activate warnings on hiding.}
11134 @geindex Hiding of Declarations
11136 This switch activates warnings on hiding declarations.
11137 A declaration is considered hiding
11138 if it is for a non-overloadable entity, and it declares an entity with the
11139 same name as some other entity that is directly or use-visible. The default
11140 is that such warnings are not generated.
11143 @geindex -gnatwH (gcc)
11148 @item @code{-gnatwH}
11150 @emph{Suppress warnings on hiding.}
11152 This switch suppresses warnings on hiding declarations.
11155 @geindex -gnatw.h (gcc)
11160 @item @code{-gnatw.h}
11162 @emph{Activate warnings on holes/gaps in records.}
11164 @geindex Record Representation (gaps)
11166 This switch activates warnings on component clauses in record
11167 representation clauses that leave holes (gaps) in the record layout.
11168 If this warning option is active, then record representation clauses
11169 should specify a contiguous layout, adding unused fill fields if needed.
11172 @geindex -gnatw.H (gcc)
11177 @item @code{-gnatw.H}
11179 @emph{Suppress warnings on holes/gaps in records.}
11181 This switch suppresses warnings on component clauses in record
11182 representation clauses that leave holes (haps) in the record layout.
11185 @geindex -gnatwi (gcc)
11190 @item @code{-gnatwi}
11192 @emph{Activate warnings on implementation units.}
11194 This switch activates warnings for a @emph{with} of an internal GNAT
11195 implementation unit, defined as any unit from the @cite{Ada},
11196 @cite{Interfaces}, @cite{GNAT},
11198 hierarchies that is not
11199 documented in either the Ada Reference Manual or the GNAT
11200 Programmer's Reference Manual. Such units are intended only
11201 for internal implementation purposes and should not be @emph{with}ed
11202 by user programs. The default is that such warnings are generated
11205 @geindex -gnatwI (gcc)
11210 @item @code{-gnatwI}
11212 @emph{Disable warnings on implementation units.}
11214 This switch disables warnings for a @emph{with} of an internal GNAT
11215 implementation unit.
11218 @geindex -gnatw.i (gcc)
11223 @item @code{-gnatw.i}
11225 @emph{Activate warnings on overlapping actuals.}
11227 This switch enables a warning on statically detectable overlapping actuals in
11228 a subprogram call, when one of the actuals is an in-out parameter, and the
11229 types of the actuals are not by-copy types. This warning is off by default.
11232 @geindex -gnatw.I (gcc)
11237 @item @code{-gnatw.I}
11239 @emph{Disable warnings on overlapping actuals.}
11241 This switch disables warnings on overlapping actuals in a call..
11244 @geindex -gnatwj (gcc)
11249 @item @code{-gnatwj}
11251 @emph{Activate warnings on obsolescent features (Annex J).}
11254 @geindex obsolescent
11256 @geindex Obsolescent features
11258 If this warning option is activated, then warnings are generated for
11259 calls to subprograms marked with @cite{pragma Obsolescent} and
11260 for use of features in Annex J of the Ada Reference Manual. In the
11261 case of Annex J, not all features are flagged. In particular use
11262 of the renamed packages (like @cite{Text_IO}) and use of package
11263 @cite{ASCII} are not flagged, since these are very common and
11264 would generate many annoying positive warnings. The default is that
11265 such warnings are not generated.
11267 In addition to the above cases, warnings are also generated for
11268 GNAT features that have been provided in past versions but which
11269 have been superseded (typically by features in the new Ada standard).
11270 For example, @cite{pragma Ravenscar} will be flagged since its
11271 function is replaced by @cite{pragma Profile(Ravenscar)}, and
11272 @cite{pragma Interface_Name} will be flagged since its function
11273 is replaced by @cite{pragma Import}.
11275 Note that this warning option functions differently from the
11276 restriction @cite{No_Obsolescent_Features} in two respects.
11277 First, the restriction applies only to annex J features.
11278 Second, the restriction does flag uses of package @cite{ASCII}.
11280 @item @code{-gnatwJ}
11282 @emph{Suppress warnings on obsolescent features (Annex J).}
11283 .. index:: -gnatwJ (gcc)
11285 This switch disables warnings on use of obsolescent features.
11287 @item @code{-gnatwk}
11289 @emph{Activate warnings on variables that could be constants.}
11290 .. index:: -gnatwk (gcc)
11292 This switch activates warnings for variables that are initialized but
11293 never modified, and then could be declared constants. The default is that
11294 such warnings are not given.
11297 @geindex -gnatwK (gcc)
11302 @item @code{-gnatwK}
11304 @emph{Suppress warnings on variables that could be constants.}
11306 This switch disables warnings on variables that could be declared constants.
11309 @geindex -gnatw.k (gcc)
11314 @item @code{-gnatw.k}
11316 @emph{Activate warnings on redefinition of names in standard.}
11318 This switch activates warnings for declarations that declare a name that
11319 is defined in package Standard. Such declarations can be confusing,
11320 especially since the names in package Standard continue to be directly
11321 visible, meaning that use visibiliy on such redeclared names does not
11322 work as expected. Names of discriminants and components in records are
11323 not included in this check.
11326 @geindex -gnatwK (gcc)
11331 @item @code{-gnatw.K}
11333 @emph{Suppress warnings on redefinition of names in standard.}
11335 This switch activates warnings for declarations that declare a name that
11336 is defined in package Standard.
11339 @geindex -gnatwl (gcc)
11344 @item @code{-gnatwl}
11346 @emph{Activate warnings for elaboration pragmas.}
11348 @geindex Elaboration
11351 This switch activates warnings for possible elaboration problems,
11352 including suspicious use
11353 of @cite{Elaborate} pragmas, when using the static elaboration model, and
11354 possible situations that may raise @cite{Program_Error} when using the
11355 dynamic elaboration model.
11356 See the section in this guide on elaboration checking for further details.
11357 The default is that such warnings
11361 @geindex -gnatwL (gcc)
11366 @item @code{-gnatwL}
11368 @emph{Suppress warnings for elaboration pragmas.}
11370 This switch suppresses warnings for possible elaboration problems.
11373 @geindex -gnatw.l (gcc)
11378 @item @code{-gnatw.l}
11380 @emph{List inherited aspects.}
11382 This switch causes the compiler to list inherited invariants,
11383 preconditions, and postconditions from Type_Invariant'Class, Invariant'Class,
11384 Pre'Class, and Post'Class aspects. Also list inherited subtype predicates.
11387 @geindex -gnatw.L (gcc)
11392 @item @code{-gnatw.L}
11394 @emph{Suppress listing of inherited aspects.}
11396 This switch suppresses listing of inherited aspects.
11399 @geindex -gnatwm (gcc)
11404 @item @code{-gnatwm}
11406 @emph{Activate warnings on modified but unreferenced variables.}
11408 This switch activates warnings for variables that are assigned (using
11409 an initialization value or with one or more assignment statements) but
11410 whose value is never read. The warning is suppressed for volatile
11411 variables and also for variables that are renamings of other variables
11412 or for which an address clause is given.
11413 The default is that these warnings are not given.
11416 @geindex -gnatwM (gcc)
11421 @item @code{-gnatwM}
11423 @emph{Disable warnings on modified but unreferenced variables.}
11425 This switch disables warnings for variables that are assigned or
11426 initialized, but never read.
11429 @geindex -gnatw.m (gcc)
11434 @item @code{-gnatw.m}
11436 @emph{Activate warnings on suspicious modulus values.}
11438 This switch activates warnings for modulus values that seem suspicious.
11439 The cases caught are where the size is the same as the modulus (e.g.
11440 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
11441 with no size clause. The guess in both cases is that 2**x was intended
11442 rather than x. In addition expressions of the form 2*x for small x
11443 generate a warning (the almost certainly accurate guess being that
11444 2**x was intended). The default is that these warnings are given.
11447 @geindex -gnatw.M (gcc)
11452 @item @code{-gnatw.M}
11454 @emph{Disable warnings on suspicious modulus values.}
11456 This switch disables warnings for suspicious modulus values.
11459 @geindex -gnatwn (gcc)
11464 @item @code{-gnatwn}
11466 @emph{Set normal warnings mode.}
11468 This switch sets normal warning mode, in which enabled warnings are
11469 issued and treated as warnings rather than errors. This is the default
11470 mode. the switch @emph{-gnatwn} can be used to cancel the effect of
11471 an explicit @emph{-gnatws} or
11472 @emph{-gnatwe}. It also cancels the effect of the
11473 implicit @emph{-gnatwe} that is activated by the
11474 use of @emph{-gnatg}.
11477 @geindex -gnatw.n (gcc)
11479 @geindex Atomic Synchronization
11485 @item @code{-gnatw.n}
11487 @emph{Activate warnings on atomic synchronization.}
11489 This switch actives warnings when an access to an atomic variable
11490 requires the generation of atomic synchronization code. These
11491 warnings are off by default.
11494 @geindex -gnatw.N (gcc)
11499 @item @code{-gnatw.N}
11501 @emph{Suppress warnings on atomic synchronization.}
11503 @geindex Atomic Synchronization
11506 This switch suppresses warnings when an access to an atomic variable
11507 requires the generation of atomic synchronization code.
11510 @geindex -gnatwo (gcc)
11512 @geindex Address Clauses
11518 @item @code{-gnatwo}
11520 @emph{Activate warnings on address clause overlays.}
11522 This switch activates warnings for possibly unintended initialization
11523 effects of defining address clauses that cause one variable to overlap
11524 another. The default is that such warnings are generated.
11527 @geindex -gnatwO (gcc)
11532 @item @code{-gnatwO}
11534 @emph{Suppress warnings on address clause overlays.}
11536 This switch suppresses warnings on possibly unintended initialization
11537 effects of defining address clauses that cause one variable to overlap
11541 @geindex -gnatw.o (gcc)
11546 @item @code{-gnatw.o}
11548 @emph{Activate warnings on modified but unreferenced out parameters.}
11550 This switch activates warnings for variables that are modified by using
11551 them as actuals for a call to a procedure with an out mode formal, where
11552 the resulting assigned value is never read. It is applicable in the case
11553 where there is more than one out mode formal. If there is only one out
11554 mode formal, the warning is issued by default (controlled by -gnatwu).
11555 The warning is suppressed for volatile
11556 variables and also for variables that are renamings of other variables
11557 or for which an address clause is given.
11558 The default is that these warnings are not given.
11561 @geindex -gnatw.O (gcc)
11566 @item @code{-gnatw.O}
11568 @emph{Disable warnings on modified but unreferenced out parameters.}
11570 This switch suppresses warnings for variables that are modified by using
11571 them as actuals for a call to a procedure with an out mode formal, where
11572 the resulting assigned value is never read.
11575 @geindex -gnatwp (gcc)
11583 @item @code{-gnatwp}
11585 @emph{Activate warnings on ineffective pragma Inlines.}
11587 This switch activates warnings for failure of front end inlining
11588 (activated by @emph{-gnatN}) to inline a particular call. There are
11589 many reasons for not being able to inline a call, including most
11590 commonly that the call is too complex to inline. The default is
11591 that such warnings are not given.
11592 Warnings on ineffective inlining by the gcc back-end can be activated
11593 separately, using the gcc switch -Winline.
11596 @geindex -gnatwP (gcc)
11601 @item @code{-gnatwP}
11603 @emph{Suppress warnings on ineffective pragma Inlines.}
11605 This switch suppresses warnings on ineffective pragma Inlines. If the
11606 inlining mechanism cannot inline a call, it will simply ignore the
11610 @geindex -gnatw.p (gcc)
11612 @geindex Parameter order
11618 @item @code{-gnatw.p}
11620 @emph{Activate warnings on parameter ordering.}
11622 This switch activates warnings for cases of suspicious parameter
11623 ordering when the list of arguments are all simple identifiers that
11624 match the names of the formals, but are in a different order. The
11625 warning is suppressed if any use of named parameter notation is used,
11626 so this is the appropriate way to suppress a false positive (and
11627 serves to emphasize that the "misordering" is deliberate). The
11628 default is that such warnings are not given.
11631 @geindex -gnatw.P (gcc)
11636 @item @code{-gnatw.P}
11638 @emph{Suppress warnings on parameter ordering.}
11640 This switch suppresses warnings on cases of suspicious parameter
11644 @geindex -gnatwq (gcc)
11646 @geindex Parentheses
11652 @item @code{-gnatwq}
11654 @emph{Activate warnings on questionable missing parentheses.}
11656 This switch activates warnings for cases where parentheses are not used and
11657 the result is potential ambiguity from a readers point of view. For example
11658 (not a > b) when a and b are modular means ((not a) > b) and very likely the
11659 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
11660 quite likely ((-x) mod 5) was intended. In such situations it seems best to
11661 follow the rule of always parenthesizing to make the association clear, and
11662 this warning switch warns if such parentheses are not present. The default
11663 is that these warnings are given.
11666 @geindex -gnatwQ (gcc)
11671 @item @code{-gnatwQ}
11673 @emph{Suppress warnings on questionable missing parentheses.}
11675 This switch suppresses warnings for cases where the association is not
11676 clear and the use of parentheses is preferred.
11679 @geindex -gnatwr (gcc)
11684 @item @code{-gnatwr}
11686 @emph{Activate warnings on redundant constructs.}
11688 This switch activates warnings for redundant constructs. The following
11689 is the current list of constructs regarded as redundant:
11695 Assignment of an item to itself.
11698 Type conversion that converts an expression to its own type.
11701 Use of the attribute @cite{Base} where @cite{typ'Base} is the same
11705 Use of pragma @cite{Pack} when all components are placed by a record
11706 representation clause.
11709 Exception handler containing only a reraise statement (raise with no
11710 operand) which has no effect.
11713 Use of the operator abs on an operand that is known at compile time
11717 Comparison of boolean expressions to an explicit True value.
11720 The default is that warnings for redundant constructs are not given.
11723 @geindex -gnatwR (gcc)
11728 @item @code{-gnatwR}
11730 @emph{Suppress warnings on redundant constructs.}
11732 This switch suppresses warnings for redundant constructs.
11735 @geindex -gnatw.r (gcc)
11740 @item @code{-gnatw.r}
11742 @emph{Activate warnings for object renaming function.}
11744 This switch activates warnings for an object renaming that renames a
11745 function call, which is equivalent to a constant declaration (as
11746 opposed to renaming the function itself). The default is that these
11747 warnings are given.
11750 @geindex -gnatwT (gcc)
11755 @item @code{-gnatw.R}
11757 @emph{Suppress warnings for object renaming function.}
11759 This switch suppresses warnings for object renaming function.
11762 @geindex -gnatws (gcc)
11767 @item @code{-gnatws}
11769 @emph{Suppress all warnings.}
11771 This switch completely suppresses the
11772 output of all warning messages from the GNAT front end, including
11773 both warnings that can be controlled by switches described in this
11774 section, and those that are normally given unconditionally. The
11775 effect of this suppress action can only be cancelled by a subsequent
11776 use of the switch @emph{-gnatwn}.
11778 Note that switch @emph{-gnatws} does not suppress
11779 warnings from the @emph{gcc} back end.
11780 To suppress these back end warnings as well, use the switch @emph{-w}
11781 in addition to @emph{-gnatws}. Also this switch has no effect on the
11782 handling of style check messages.
11785 @geindex -gnatw.s (gcc)
11787 @geindex Record Representation (component sizes)
11792 @item @code{-gnatw.s}
11794 @emph{Activate warnings on overridden size clauses.}
11796 This switch activates warnings on component clauses in record
11797 representation clauses where the length given overrides that
11798 specified by an explicit size clause for the component type. A
11799 warning is similarly given in the array case if a specified
11800 component size overrides an explicit size clause for the array
11804 @geindex -gnatw.S (gcc)
11809 @item @code{-gnatw.S}
11811 @emph{Suppress warnings on overridden size clauses.}
11813 This switch suppresses warnings on component clauses in record
11814 representation clauses that override size clauses, and similar
11815 warnings when an array component size overrides a size clause.
11818 @geindex -gnatwt (gcc)
11820 @geindex Deactivated code
11823 @geindex Deleted code
11829 @item @code{-gnatwt}
11831 @emph{Activate warnings for tracking of deleted conditional code.}
11833 This switch activates warnings for tracking of code in conditionals (IF and
11834 CASE statements) that is detected to be dead code which cannot be executed, and
11835 which is removed by the front end. This warning is off by default. This may be
11836 useful for detecting deactivated code in certified applications.
11839 @geindex -gnatwT (gcc)
11844 @item @code{-gnatwT}
11846 @emph{Suppress warnings for tracking of deleted conditional code.}
11848 This switch suppresses warnings for tracking of deleted conditional code.
11851 @geindex -gnatw.t (gcc)
11856 @item @code{-gnatw.t}
11858 @emph{Activate warnings on suspicious contracts.}
11860 This switch activates warnings on suspicious contracts. This includes
11861 warnings on suspicious postconditions (whether a pragma @cite{Postcondition} or a
11862 @cite{Post} aspect in Ada 2012) and suspicious contract cases (pragma or aspect
11863 @cite{Contract_Cases}). A function postcondition or contract case is suspicious
11864 when no postcondition or contract case for this function mentions the result
11865 of the function. A procedure postcondition or contract case is suspicious
11866 when it only refers to the pre-state of the procedure, because in that case
11867 it should rather be expressed as a precondition. This switch also controls
11868 warnings on suspicious cases of expressions typically found in contracts like
11869 quantified expressions and uses of Update attribute. The default is that such
11870 warnings are generated.
11873 @geindex -gnatw.T (gcc)
11878 @item @code{-gnatw.T}
11880 @emph{Suppress warnings on suspicious contracts.}
11882 This switch suppresses warnings on suspicious contracts.
11885 @geindex -gnatwu (gcc)
11890 @item @code{-gnatwu}
11892 @emph{Activate warnings on unused entities.}
11894 This switch activates warnings to be generated for entities that
11895 are declared but not referenced, and for units that are @emph{with}ed
11897 referenced. In the case of packages, a warning is also generated if
11898 no entities in the package are referenced. This means that if a with'ed
11899 package is referenced but the only references are in @cite{use}
11900 clauses or @cite{renames}
11901 declarations, a warning is still generated. A warning is also generated
11902 for a generic package that is @emph{with}ed but never instantiated.
11903 In the case where a package or subprogram body is compiled, and there
11904 is a @emph{with} on the corresponding spec
11905 that is only referenced in the body,
11906 a warning is also generated, noting that the
11907 @emph{with} can be moved to the body. The default is that
11908 such warnings are not generated.
11909 This switch also activates warnings on unreferenced formals
11910 (it includes the effect of @emph{-gnatwf}).
11913 @geindex -gnatwU (gcc)
11918 @item @code{-gnatwU}
11920 @emph{Suppress warnings on unused entities.}
11922 This switch suppresses warnings for unused entities and packages.
11923 It also turns off warnings on unreferenced formals (and thus includes
11924 the effect of @emph{-gnatwF}).
11927 @geindex -gnatw.u (gcc)
11932 @item @code{-gnatw.u}
11934 @emph{Activate warnings on unordered enumeration types.}
11936 This switch causes enumeration types to be considered as conceptually
11937 unordered, unless an explicit pragma @cite{Ordered} is given for the type.
11938 The effect is to generate warnings in clients that use explicit comparisons
11939 or subranges, since these constructs both treat objects of the type as
11940 ordered. (A @emph{client} is defined as a unit that is other than the unit in
11941 which the type is declared, or its body or subunits.) Please refer to
11942 the description of pragma @cite{Ordered} in the
11943 @cite{GNAT Reference Manual} for further details.
11944 The default is that such warnings are not generated.
11947 @geindex -gnatw.U (gcc)
11952 @item @code{-gnatw.U}
11954 @emph{Deactivate warnings on unordered enumeration types.}
11956 This switch causes all enumeration types to be considered as ordered, so
11957 that no warnings are given for comparisons or subranges for any type.
11960 @geindex -gnatwv (gcc)
11962 @geindex Unassigned variable warnings
11967 @item @code{-gnatwv}
11969 @emph{Activate warnings on unassigned variables.}
11971 This switch activates warnings for access to variables which
11972 may not be properly initialized. The default is that
11973 such warnings are generated.
11976 @geindex -gnatwV (gcc)
11981 @item @code{-gnatwV}
11983 @emph{Suppress warnings on unassigned variables.}
11985 This switch suppresses warnings for access to variables which
11986 may not be properly initialized.
11987 For variables of a composite type, the warning can also be suppressed in
11988 Ada 2005 by using a default initialization with a box. For example, if
11989 Table is an array of records whose components are only partially uninitialized,
11990 then the following code:
11993 Tab : Table := (others => <>);
11996 will suppress warnings on subsequent statements that access components
12000 @geindex -gnatw.v (gcc)
12002 @geindex bit order warnings
12007 @item @code{-gnatw.v}
12009 @emph{Activate info messages for non-default bit order.}
12011 This switch activates messages (labeled "info", they are not warnings,
12012 just informational messages) about the effects of non-default bit-order
12013 on records to which a component clause is applied. The effect of specifying
12014 non-default bit ordering is a bit subtle (and changed with Ada 2005), so
12015 these messages, which are given by default, are useful in understanding the
12016 exact consequences of using this feature.
12019 @geindex -gnatw.V (gcc)
12024 @item @code{-gnatw.V}
12026 @emph{Suppress info messages for non-default bit order.}
12028 This switch suppresses information messages for the effects of specifying
12029 non-default bit order on record components with component clauses.
12032 @geindex -gnatww (gcc)
12034 @geindex String indexing warnings
12039 @item @code{-gnatww}
12041 @emph{Activate warnings on wrong low bound assumption.}
12043 This switch activates warnings for indexing an unconstrained string parameter
12044 with a literal or S'Length. This is a case where the code is assuming that the
12045 low bound is one, which is in general not true (for example when a slice is
12046 passed). The default is that such warnings are generated.
12049 @geindex -gnatwW (gcc)
12054 @item @code{-gnatwW}
12056 @emph{Suppress warnings on wrong low bound assumption.}
12058 This switch suppresses warnings for indexing an unconstrained string parameter
12059 with a literal or S'Length. Note that this warning can also be suppressed
12060 in a particular case by adding an assertion that the lower bound is 1,
12061 as shown in the following example:
12064 procedure K (S : String) is
12065 pragma Assert (S'First = 1);
12070 @geindex -gnatw.w (gcc)
12072 @geindex Warnings Off control
12077 @item @code{-gnatw.w}
12079 @emph{Activate warnings on Warnings Off pragmas}
12081 This switch activates warnings for use of @cite{pragma Warnings (Off@comma{} entity)}
12082 where either the pragma is entirely useless (because it suppresses no
12083 warnings), or it could be replaced by @cite{pragma Unreferenced} or
12084 @cite{pragma Unmodified}.
12085 Also activates warnings for the case of
12086 Warnings (Off, String), where either there is no matching
12087 Warnings (On, String), or the Warnings (Off) did not suppress any warning.
12088 The default is that these warnings are not given.
12091 @geindex -gnatw.W (gcc)
12096 @item @code{-gnatw.W}
12098 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
12100 This switch suppresses warnings for use of @cite{pragma Warnings (Off@comma{} ...)}.
12103 @geindex -gnatwx (gcc)
12105 @geindex Export/Import pragma warnings
12110 @item @code{-gnatwx}
12112 @emph{Activate warnings on Export/Import pragmas.}
12114 This switch activates warnings on Export/Import pragmas when
12115 the compiler detects a possible conflict between the Ada and
12116 foreign language calling sequences. For example, the use of
12117 default parameters in a convention C procedure is dubious
12118 because the C compiler cannot supply the proper default, so
12119 a warning is issued. The default is that such warnings are
12123 @geindex -gnatwX (gcc)
12128 @item @code{-gnatwX}
12130 @emph{Suppress warnings on Export/Import pragmas.}
12132 This switch suppresses warnings on Export/Import pragmas.
12133 The sense of this is that you are telling the compiler that
12134 you know what you are doing in writing the pragma, and it
12135 should not complain at you.
12138 @geindex -gnatwm (gcc)
12143 @item @code{-gnatw.x}
12145 @emph{Activate warnings for No_Exception_Propagation mode.}
12147 This switch activates warnings for exception usage when pragma Restrictions
12148 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
12149 explicit exception raises which are not covered by a local handler, and for
12150 exception handlers which do not cover a local raise. The default is that these
12151 warnings are not given.
12153 @item @code{-gnatw.X}
12155 @emph{Disable warnings for No_Exception_Propagation mode.}
12157 This switch disables warnings for exception usage when pragma Restrictions
12158 (No_Exception_Propagation) is in effect.
12161 @geindex -gnatwy (gcc)
12163 @geindex Ada compatibility issues warnings
12168 @item @code{-gnatwy}
12170 @emph{Activate warnings for Ada compatibility issues.}
12172 For the most part, newer versions of Ada are upwards compatible
12173 with older versions. For example, Ada 2005 programs will almost
12174 always work when compiled as Ada 2012.
12175 However there are some exceptions (for example the fact that
12176 @cite{some} is now a reserved word in Ada 2012). This
12177 switch activates several warnings to help in identifying
12178 and correcting such incompatibilities. The default is that
12179 these warnings are generated. Note that at one point Ada 2005
12180 was called Ada 0Y, hence the choice of character.
12183 @geindex -gnatwY (gcc)
12185 @geindex Ada compatibility issues warnings
12190 @item @code{-gnatwY}
12192 @emph{Disable warnings for Ada compatibility issues.}
12194 This switch suppresses the warnings intended to help in identifying
12195 incompatibilities between Ada language versions.
12198 @geindex -gnatw.y (gcc)
12200 @geindex Package spec needing body
12205 @item @code{-gnatw.y}
12207 @emph{Activate information messages for why package spec needs body}
12209 There are a number of cases in which a package spec needs a body.
12210 For example, the use of pragma Elaborate_Body, or the declaration
12211 of a procedure specification requiring a completion. This switch
12212 causes information messages to be output showing why a package
12213 specification requires a body. This can be useful in the case of
12214 a large package specification which is unexpectedly requiring a
12215 body. The default is that such information messages are not output.
12218 @geindex -gnatw.Y (gcc)
12220 @geindex No information messages for why package spec needs body
12225 @item @code{-gnatw.Y}
12227 @emph{Disable information messages for why package spec needs body}
12229 This switch suppresses the output of information messages showing why
12230 a package specification needs a body.
12233 @geindex -gnatwz (gcc)
12235 @geindex Unchecked_Conversion warnings
12240 @item @code{-gnatwz}
12242 @emph{Activate warnings on unchecked conversions.}
12244 This switch activates warnings for unchecked conversions
12245 where the types are known at compile time to have different
12246 sizes. The default is that such warnings are generated. Warnings are also
12247 generated for subprogram pointers with different conventions.
12250 @geindex -gnatwZ (gcc)
12255 @item @code{-gnatwZ}
12257 @emph{Suppress warnings on unchecked conversions.}
12259 This switch suppresses warnings for unchecked conversions
12260 where the types are known at compile time to have different
12261 sizes or conventions.
12264 @geindex -gnatw.z (gcc)
12266 @geindex Size/Alignment warnings
12271 @item @code{-gnatw.z}
12273 @emph{Activate warnings for size not a multiple of alignment.}
12275 This switch activates warnings for cases of record types with
12276 specified @cite{Size} and @cite{Alignment} attributes where the
12277 size is not a multiple of the alignment, resulting in an object
12278 size that is greater than the specified size. The default
12279 is that such warnings are generated.
12282 @geindex -gnatw.Z (gcc)
12284 @geindex Size/Alignment warnings
12289 @item @code{-gnatw.Z}
12291 @emph{Suppress warnings for size not a multiple of alignment.}
12293 This switch suppresses warnings for cases of record types with
12294 specified @cite{Size} and @cite{Alignment} attributes where the
12295 size is not a multiple of the alignment, resulting in an object
12296 size that is greater than the specified size.
12297 The warning can also be
12298 suppressed by giving an explicit @cite{Object_Size} value.
12301 @geindex -Wunused (gcc)
12306 @item @code{-Wunused}
12308 The warnings controlled by the @emph{-gnatw} switch are generated by
12309 the front end of the compiler. The @emph{GCC} back end can provide
12310 additional warnings and they are controlled by the @emph{-W} switch.
12311 For example, @emph{-Wunused} activates back end
12312 warnings for entities that are declared but not referenced.
12315 @geindex -Wuninitialized (gcc)
12320 @item @code{-Wuninitialized}
12322 Similarly, @emph{-Wuninitialized} activates
12323 the back end warning for uninitialized variables. This switch must be
12324 used in conjunction with an optimization level greater than zero.
12327 @geindex -Wstack-usage (gcc)
12332 @item @code{-Wstack-usage=@emph{len}}
12334 Warn if the stack usage of a subprogram might be larger than @cite{len} bytes.
12335 See @ref{fa,,Static Stack Usage Analysis} for details.
12338 @geindex -Wall (gcc)
12345 This switch enables most warnings from the @emph{GCC} back end.
12346 The code generator detects a number of warning situations that are missed
12347 by the @emph{GNAT} front end, and this switch can be used to activate them.
12348 The use of this switch also sets the default front end warning mode to
12349 @emph{-gnatwa}, that is, most front end warnings activated as well.
12359 Conversely, this switch suppresses warnings from the @emph{GCC} back end.
12360 The use of this switch also sets the default front end warning mode to
12361 @emph{-gnatws}, that is, front end warnings suppressed as well.
12364 @geindex -Werror (gcc)
12369 @item @code{-Werror}
12371 This switch causes warnings from the @emph{GCC} back end to be treated as
12372 errors. The warning string still appears, but the warning messages are
12373 counted as errors, and prevent the generation of an object file.
12376 A string of warning parameters can be used in the same parameter. For example:
12382 will turn on all optional warnings except for unrecognized pragma warnings,
12383 and also specify that warnings should be treated as errors.
12385 When no switch @emph{-gnatw} is used, this is equivalent to:
12502 @node Debugging and Assertion Control,Validity Checking,Warning Message Control,Compiler Switches
12503 @anchor{gnat_ugn/building_executable_programs_with_gnat debugging-and-assertion-control}@anchor{105}@anchor{gnat_ugn/building_executable_programs_with_gnat id16}@anchor{106}
12504 @subsection Debugging and Assertion Control
12507 @geindex -gnata (gcc)
12512 @item @code{-gnata}
12518 @geindex Assertions
12520 The pragmas @cite{Assert} and @cite{Debug} normally have no effect and
12521 are ignored. This switch, where @code{a} stands for assert, causes
12522 @cite{Assert} and @cite{Debug} pragmas to be activated.
12524 The pragmas have the form:
12527 pragma Assert (<Boolean-expression> [, <static-string-expression>])
12528 pragma Debug (<procedure call>)
12531 The @cite{Assert} pragma causes @cite{Boolean-expression} to be tested.
12532 If the result is @cite{True}, the pragma has no effect (other than
12533 possible side effects from evaluating the expression). If the result is
12534 @cite{False}, the exception @cite{Assert_Failure} declared in the package
12535 @cite{System.Assertions} is
12536 raised (passing @cite{static-string-expression}, if present, as the
12537 message associated with the exception). If no string expression is
12538 given the default is a string giving the file name and line number
12541 The @cite{Debug} pragma causes @cite{procedure} to be called. Note that
12542 @cite{pragma Debug} may appear within a declaration sequence, allowing
12543 debugging procedures to be called between declarations.
12546 @node Validity Checking,Style Checking,Debugging and Assertion Control,Compiler Switches
12547 @anchor{gnat_ugn/building_executable_programs_with_gnat validity-checking}@anchor{fb}@anchor{gnat_ugn/building_executable_programs_with_gnat id17}@anchor{107}
12548 @subsection Validity Checking
12551 @geindex Validity Checking
12553 The Ada Reference Manual defines the concept of invalid values (see
12554 RM 13.9.1). The primary source of invalid values is uninitialized
12555 variables. A scalar variable that is left uninitialized may contain
12556 an invalid value; the concept of invalid does not apply to access or
12559 It is an error to read an invalid value, but the RM does not require
12560 run-time checks to detect such errors, except for some minimal
12561 checking to prevent erroneous execution (i.e. unpredictable
12562 behavior). This corresponds to the @emph{-gnatVd} switch below,
12563 which is the default. For example, by default, if the expression of a
12564 case statement is invalid, it will raise Constraint_Error rather than
12565 causing a wild jump, and if an array index on the left-hand side of an
12566 assignment is invalid, it will raise Constraint_Error rather than
12567 overwriting an arbitrary memory location.
12569 The @emph{-gnatVa} may be used to enable additional validity checks,
12570 which are not required by the RM. These checks are often very
12571 expensive (which is why the RM does not require them). These checks
12572 are useful in tracking down uninitialized variables, but they are
12573 not usually recommended for production builds, and in particular
12574 we do not recommend using these extra validity checking options in
12575 combination with optimization, since this can confuse the optimizer.
12576 If performance is a consideration, leading to the need to optimize,
12577 then the validity checking options should not be used.
12579 The other @emph{-gnatV}@code{x} switches below allow finer-grained
12580 control; you can enable whichever validity checks you desire. However,
12581 for most debugging purposes, @emph{-gnatVa} is sufficient, and the
12582 default @emph{-gnatVd} (i.e. standard Ada behavior) is usually
12583 sufficient for non-debugging use.
12585 The @emph{-gnatB} switch tells the compiler to assume that all
12586 values are valid (that is, within their declared subtype range)
12587 except in the context of a use of the Valid attribute. This means
12588 the compiler can generate more efficient code, since the range
12589 of values is better known at compile time. However, an uninitialized
12590 variable can cause wild jumps and memory corruption in this mode.
12592 The @emph{-gnatV}@code{x} switch allows control over the validity
12593 checking mode as described below.
12594 The @code{x} argument is a string of letters that
12595 indicate validity checks that are performed or not performed in addition
12596 to the default checks required by Ada as described above.
12598 @geindex -gnatVa (gcc)
12603 @item @code{-gnatVa}
12605 @emph{All validity checks.}
12607 All validity checks are turned on.
12608 That is, @emph{-gnatVa} is
12609 equivalent to @emph{gnatVcdfimorst}.
12612 @geindex -gnatVc (gcc)
12617 @item @code{-gnatVc}
12619 @emph{Validity checks for copies.}
12621 The right hand side of assignments, and the initializing values of
12622 object declarations are validity checked.
12625 @geindex -gnatVd (gcc)
12630 @item @code{-gnatVd}
12632 @emph{Default (RM) validity checks.}
12634 Some validity checks are done by default following normal Ada semantics
12635 (RM 13.9.1 (9-11)).
12636 A check is done in case statements that the expression is within the range
12637 of the subtype. If it is not, Constraint_Error is raised.
12638 For assignments to array components, a check is done that the expression used
12639 as index is within the range. If it is not, Constraint_Error is raised.
12640 Both these validity checks may be turned off using switch @emph{-gnatVD}.
12641 They are turned on by default. If @emph{-gnatVD} is specified, a subsequent
12642 switch @emph{-gnatVd} will leave the checks turned on.
12643 Switch @emph{-gnatVD} should be used only if you are sure that all such
12644 expressions have valid values. If you use this switch and invalid values
12645 are present, then the program is erroneous, and wild jumps or memory
12646 overwriting may occur.
12649 @geindex -gnatVe (gcc)
12654 @item @code{-gnatVe}
12656 @emph{Validity checks for elementary components.}
12658 In the absence of this switch, assignments to record or array components are
12659 not validity checked, even if validity checks for assignments generally
12660 (@emph{-gnatVc}) are turned on. In Ada, assignment of composite values do not
12661 require valid data, but assignment of individual components does. So for
12662 example, there is a difference between copying the elements of an array with a
12663 slice assignment, compared to assigning element by element in a loop. This
12664 switch allows you to turn off validity checking for components, even when they
12665 are assigned component by component.
12668 @geindex -gnatVf (gcc)
12673 @item @code{-gnatVf}
12675 @emph{Validity checks for floating-point values.}
12677 In the absence of this switch, validity checking occurs only for discrete
12678 values. If @emph{-gnatVf} is specified, then validity checking also applies
12679 for floating-point values, and NaNs and infinities are considered invalid,
12680 as well as out of range values for constrained types. Note that this means
12681 that standard IEEE infinity mode is not allowed. The exact contexts
12682 in which floating-point values are checked depends on the setting of other
12683 options. For example, @emph{-gnatVif} or @emph{-gnatVfi}
12684 (the order does not matter) specifies that floating-point parameters of mode
12685 @cite{in} should be validity checked.
12688 @geindex -gnatVi (gcc)
12693 @item @code{-gnatVi}
12695 @emph{Validity checks for `in} mode parameters`
12697 Arguments for parameters of mode @cite{in} are validity checked in function
12698 and procedure calls at the point of call.
12701 @geindex -gnatVm (gcc)
12706 @item @code{-gnatVm}
12708 @emph{Validity checks for `in out} mode parameters.`
12710 Arguments for parameters of mode @cite{in out} are validity checked in
12711 procedure calls at the point of call. The @cite{'m'} here stands for
12712 modify, since this concerns parameters that can be modified by the call.
12713 Note that there is no specific option to test @cite{out} parameters,
12714 but any reference within the subprogram will be tested in the usual
12715 manner, and if an invalid value is copied back, any reference to it
12716 will be subject to validity checking.
12719 @geindex -gnatVn (gcc)
12724 @item @code{-gnatVn}
12726 @emph{No validity checks.}
12728 This switch turns off all validity checking, including the default checking
12729 for case statements and left hand side subscripts. Note that the use of
12730 the switch @emph{-gnatp} suppresses all run-time checks, including
12731 validity checks, and thus implies @emph{-gnatVn}. When this switch
12732 is used, it cancels any other @emph{-gnatV} previously issued.
12734 @item @code{-gnatVo}
12736 @emph{Validity checks for operator and attribute operands.}
12737 .. index:: -gnatVo (gcc)
12739 Arguments for predefined operators and attributes are validity checked.
12740 This includes all operators in package @cite{Standard},
12741 the shift operators defined as intrinsic in package @cite{Interfaces}
12742 and operands for attributes such as @cite{Pos}. Checks are also made
12743 on individual component values for composite comparisons, and on the
12744 expressions in type conversions and qualified expressions. Checks are
12745 also made on explicit ranges using @code{..} (e.g., slices, loops etc).
12748 @geindex -gnatVp (gcc)
12753 @item @code{-gnatVp}
12755 @emph{Validity checks for parameters.}
12757 This controls the treatment of parameters within a subprogram (as opposed
12758 to @emph{-gnatVi} and @emph{-gnatVm} which control validity testing
12759 of parameters on a call. If either of these call options is used, then
12760 normally an assumption is made within a subprogram that the input arguments
12761 have been validity checking at the point of call, and do not need checking
12762 again within a subprogram). If @emph{-gnatVp} is set, then this assumption
12763 is not made, and parameters are not assumed to be valid, so their validity
12764 will be checked (or rechecked) within the subprogram.
12767 @geindex -gnatVr (gcc)
12772 @item @code{-gnatVr}
12774 @emph{Validity checks for function returns.}
12776 The expression in @cite{return} statements in functions is validity
12780 @geindex -gnatVs (gcc)
12785 @item @code{-gnatVs}
12787 @emph{Validity checks for subscripts.}
12789 All subscripts expressions are checked for validity, whether they appear
12790 on the right side or left side (in default mode only left side subscripts
12791 are validity checked).
12794 @geindex -gnatVt (gcc)
12799 @item @code{-gnatVt}
12801 @emph{Validity checks for tests.}
12803 Expressions used as conditions in @cite{if}, @cite{while} or @cite{exit}
12804 statements are checked, as well as guard expressions in entry calls.
12807 The @emph{-gnatV} switch may be followed by a string of letters
12808 to turn on a series of validity checking options.
12809 For example, @code{-gnatVcr}
12810 specifies that in addition to the default validity checking, copies and
12811 function return expressions are to be validity checked.
12812 In order to make it easier to specify the desired combination of effects,
12813 the upper case letters @cite{CDFIMORST} may
12814 be used to turn off the corresponding lower case option.
12815 Thus @code{-gnatVaM} turns on all validity checking options except for
12816 checking of @cite{**in out**} procedure arguments.
12818 The specification of additional validity checking generates extra code (and
12819 in the case of @emph{-gnatVa} the code expansion can be substantial).
12820 However, these additional checks can be very useful in detecting
12821 uninitialized variables, incorrect use of unchecked conversion, and other
12822 errors leading to invalid values. The use of pragma @cite{Initialize_Scalars}
12823 is useful in conjunction with the extra validity checking, since this
12824 ensures that wherever possible uninitialized variables have invalid values.
12826 See also the pragma @cite{Validity_Checks} which allows modification of
12827 the validity checking mode at the program source level, and also allows for
12828 temporary disabling of validity checks.
12830 @node Style Checking,Run-Time Checks,Validity Checking,Compiler Switches
12831 @anchor{gnat_ugn/building_executable_programs_with_gnat id18}@anchor{108}@anchor{gnat_ugn/building_executable_programs_with_gnat style-checking}@anchor{100}
12832 @subsection Style Checking
12835 @geindex Style checking
12837 @geindex -gnaty (gcc)
12839 The @emph{-gnatyx} switch causes the compiler to
12840 enforce specified style rules. A limited set of style rules has been used
12841 in writing the GNAT sources themselves. This switch allows user programs
12842 to activate all or some of these checks. If the source program fails a
12843 specified style check, an appropriate message is given, preceded by
12844 the character sequence '(style)'. This message does not prevent
12845 successful compilation (unless the @emph{-gnatwe} switch is used).
12847 Note that this is by no means intended to be a general facility for
12848 checking arbitrary coding standards. It is simply an embedding of the
12849 style rules we have chosen for the GNAT sources. If you are starting
12850 a project which does not have established style standards, you may
12851 find it useful to adopt the entire set of GNAT coding standards, or
12852 some subset of them.
12855 The string @cite{x} is a sequence of letters or digits
12856 indicating the particular style
12857 checks to be performed. The following checks are defined:
12859 @geindex -gnaty[0-9] (gcc)
12864 @item @code{-gnaty0}
12866 @emph{Specify indentation level.}
12868 If a digit from 1-9 appears
12869 in the string after @emph{-gnaty}
12870 then proper indentation is checked, with the digit indicating the
12871 indentation level required. A value of zero turns off this style check.
12872 The general style of required indentation is as specified by
12873 the examples in the Ada Reference Manual. Full line comments must be
12874 aligned with the @cite{--} starting on a column that is a multiple of
12875 the alignment level, or they may be aligned the same way as the following
12876 non-blank line (this is useful when full line comments appear in the middle
12877 of a statement, or they may be aligned with the source line on the previous
12881 @geindex -gnatya (gcc)
12886 @item @code{-gnatya}
12888 @emph{Check attribute casing.}
12890 Attribute names, including the case of keywords such as @cite{digits}
12891 used as attributes names, must be written in mixed case, that is, the
12892 initial letter and any letter following an underscore must be uppercase.
12893 All other letters must be lowercase.
12896 @geindex -gnatyA (gcc)
12901 @item @code{-gnatyA}
12903 @emph{Use of array index numbers in array attributes.}
12905 When using the array attributes First, Last, Range,
12906 or Length, the index number must be omitted for one-dimensional arrays
12907 and is required for multi-dimensional arrays.
12910 @geindex -gnatyb (gcc)
12915 @item @code{-gnatyb}
12917 @emph{Blanks not allowed at statement end.}
12919 Trailing blanks are not allowed at the end of statements. The purpose of this
12920 rule, together with h (no horizontal tabs), is to enforce a canonical format
12921 for the use of blanks to separate source tokens.
12924 @geindex -gnatyB (gcc)
12929 @item @code{-gnatyB}
12931 @emph{Check Boolean operators.}
12933 The use of AND/OR operators is not permitted except in the cases of modular
12934 operands, array operands, and simple stand-alone boolean variables or
12935 boolean constants. In all other cases @cite{and then}/@cite{or else} are
12939 @geindex -gnatyc (gcc)
12944 @item @code{-gnatyc}
12946 @emph{Check comments, double space.}
12948 Comments must meet the following set of rules:
12954 The '@cite{--}' that starts the column must either start in column one,
12955 or else at least one blank must precede this sequence.
12958 Comments that follow other tokens on a line must have at least one blank
12959 following the '@cite{--}' at the start of the comment.
12962 Full line comments must have at least two blanks following the
12963 '@cite{--}' that starts the comment, with the following exceptions.
12966 A line consisting only of the '@cite{--}' characters, possibly preceded
12967 by blanks is permitted.
12970 A comment starting with '@cite{--x}' where @cite{x} is a special character
12972 This allows proper processing of the output generated by specialized tools
12973 including @emph{gnatprep} (where '@cite{--!}' is used) and the SPARK
12975 language (where '@cite{--#}' is used). For the purposes of this rule, a
12976 special character is defined as being in one of the ASCII ranges
12977 @cite{16#21#...16#2F#} or @cite{16#3A#...16#3F#}.
12978 Note that this usage is not permitted
12979 in GNAT implementation units (i.e., when @emph{-gnatg} is used).
12982 A line consisting entirely of minus signs, possibly preceded by blanks, is
12983 permitted. This allows the construction of box comments where lines of minus
12984 signs are used to form the top and bottom of the box.
12987 A comment that starts and ends with '@cite{--}' is permitted as long as at
12988 least one blank follows the initial '@cite{--}'. Together with the preceding
12989 rule, this allows the construction of box comments, as shown in the following
12993 ---------------------------
12994 -- This is a box comment --
12995 -- with two text lines. --
12996 ---------------------------
13001 @geindex -gnatyC (gcc)
13006 @item @code{-gnatyC}
13008 @emph{Check comments, single space.}
13010 This is identical to @cite{c} except that only one space
13011 is required following the @cite{--} of a comment instead of two.
13014 @geindex -gnatyd (gcc)
13019 @item @code{-gnatyd}
13021 @emph{Check no DOS line terminators present.}
13023 All lines must be terminated by a single ASCII.LF
13024 character (in particular the DOS line terminator sequence CR/LF is not
13028 @geindex -gnatye (gcc)
13033 @item @code{-gnatye}
13035 @emph{Check end/exit labels.}
13037 Optional labels on @cite{end} statements ending subprograms and on
13038 @cite{exit} statements exiting named loops, are required to be present.
13041 @geindex -gnatyf (gcc)
13046 @item @code{-gnatyf}
13048 @emph{No form feeds or vertical tabs.}
13050 Neither form feeds nor vertical tab characters are permitted
13051 in the source text.
13054 @geindex -gnatyg (gcc)
13059 @item @code{-gnatyg}
13061 @emph{GNAT style mode.}
13063 The set of style check switches is set to match that used by the GNAT sources.
13064 This may be useful when developing code that is eventually intended to be
13065 incorporated into GNAT. Currently this is equivalent to @emph{-gnatwydISux})
13066 but additional style switches may be added to this set in the future without
13070 @geindex -gnatyh (gcc)
13075 @item @code{-gnatyh}
13077 @emph{No horizontal tabs.}
13079 Horizontal tab characters are not permitted in the source text.
13080 Together with the b (no blanks at end of line) check, this
13081 enforces a canonical form for the use of blanks to separate
13085 @geindex -gnatyi (gcc)
13090 @item @code{-gnatyi}
13092 @emph{Check if-then layout.}
13094 The keyword @cite{then} must appear either on the same
13095 line as corresponding @cite{if}, or on a line on its own, lined
13096 up under the @cite{if}.
13099 @geindex -gnatyI (gcc)
13104 @item @code{-gnatyI}
13106 @emph{check mode IN keywords.}
13108 Mode @cite{in} (the default mode) is not
13109 allowed to be given explicitly. @cite{in out} is fine,
13110 but not @cite{in} on its own.
13113 @geindex -gnatyk (gcc)
13118 @item @code{-gnatyk}
13120 @emph{Check keyword casing.}
13122 All keywords must be in lower case (with the exception of keywords
13123 such as @cite{digits} used as attribute names to which this check
13127 @geindex -gnatyl (gcc)
13132 @item @code{-gnatyl}
13134 @emph{Check layout.}
13136 Layout of statement and declaration constructs must follow the
13137 recommendations in the Ada Reference Manual, as indicated by the
13138 form of the syntax rules. For example an @cite{else} keyword must
13139 be lined up with the corresponding @cite{if} keyword.
13141 There are two respects in which the style rule enforced by this check
13142 option are more liberal than those in the Ada Reference Manual. First
13143 in the case of record declarations, it is permissible to put the
13144 @cite{record} keyword on the same line as the @cite{type} keyword, and
13145 then the @cite{end} in @cite{end record} must line up under @cite{type}.
13146 This is also permitted when the type declaration is split on two lines.
13147 For example, any of the following three layouts is acceptable:
13168 Second, in the case of a block statement, a permitted alternative
13169 is to put the block label on the same line as the @cite{declare} or
13170 @cite{begin} keyword, and then line the @cite{end} keyword up under
13171 the block label. For example both the following are permitted:
13188 The same alternative format is allowed for loops. For example, both of
13189 the following are permitted:
13192 Clear : while J < 10 loop
13203 @geindex -gnatyLnnn (gcc)
13208 @item @code{-gnatyL}
13210 @emph{Set maximum nesting level.}
13212 The maximum level of nesting of constructs (including subprograms, loops,
13213 blocks, packages, and conditionals) may not exceed the given value
13214 @emph{nnn}. A value of zero disconnects this style check.
13217 @geindex -gnatym (gcc)
13222 @item @code{-gnatym}
13224 @emph{Check maximum line length.}
13226 The length of source lines must not exceed 79 characters, including
13227 any trailing blanks. The value of 79 allows convenient display on an
13228 80 character wide device or window, allowing for possible special
13229 treatment of 80 character lines. Note that this count is of
13230 characters in the source text. This means that a tab character counts
13231 as one character in this count and a wide character sequence counts as
13232 a single character (however many bytes are needed in the encoding).
13235 @geindex -gnatyMnnn (gcc)
13240 @item @code{-gnatyM}
13242 @emph{Set maximum line length.}
13244 The length of lines must not exceed the
13245 given value @emph{nnn}. The maximum value that can be specified is 32767.
13246 If neither style option for setting the line length is used, then the
13247 default is 255. This also controls the maximum length of lexical elements,
13248 where the only restriction is that they must fit on a single line.
13251 @geindex -gnatyn (gcc)
13256 @item @code{-gnatyn}
13258 @emph{Check casing of entities in Standard.}
13260 Any identifier from Standard must be cased
13261 to match the presentation in the Ada Reference Manual (for example,
13262 @cite{Integer} and @cite{ASCII.NUL}).
13265 @geindex -gnatyN (gcc)
13270 @item @code{-gnatyN}
13272 @emph{Turn off all style checks.}
13274 All style check options are turned off.
13277 @geindex -gnatyo (gcc)
13282 @item @code{-gnatyo}
13284 @emph{Check order of subprogram bodies.}
13286 All subprogram bodies in a given scope
13287 (e.g., a package body) must be in alphabetical order. The ordering
13288 rule uses normal Ada rules for comparing strings, ignoring casing
13289 of letters, except that if there is a trailing numeric suffix, then
13290 the value of this suffix is used in the ordering (e.g., Junk2 comes
13294 @geindex -gnatyO (gcc)
13299 @item @code{-gnatyO}
13301 @emph{Check that overriding subprograms are explicitly marked as such.}
13303 This applies to all subprograms of a derived type that override a primitive
13304 operation of the type, for both tagged and untagged types. In particular,
13305 the declaration of a primitive operation of a type extension that overrides
13306 an inherited operation must carry an overriding indicator. Another case is
13307 the declaration of a function that overrides a predefined operator (such
13308 as an equality operator).
13311 @geindex -gnatyp (gcc)
13316 @item @code{-gnatyp}
13318 @emph{Check pragma casing.}
13320 Pragma names must be written in mixed case, that is, the
13321 initial letter and any letter following an underscore must be uppercase.
13322 All other letters must be lowercase. An exception is that SPARK_Mode is
13323 allowed as an alternative for Spark_Mode.
13326 @geindex -gnatyr (gcc)
13331 @item @code{-gnatyr}
13333 @emph{Check references.}
13335 All identifier references must be cased in the same way as the
13336 corresponding declaration. No specific casing style is imposed on
13337 identifiers. The only requirement is for consistency of references
13341 @geindex -gnatys (gcc)
13346 @item @code{-gnatys}
13348 @emph{Check separate specs.}
13350 Separate declarations ('specs') are required for subprograms (a
13351 body is not allowed to serve as its own declaration). The only
13352 exception is that parameterless library level procedures are
13353 not required to have a separate declaration. This exception covers
13354 the most frequent form of main program procedures.
13357 @geindex -gnatyS (gcc)
13362 @item @code{-gnatyS}
13364 @emph{Check no statements after then/else.}
13366 No statements are allowed
13367 on the same line as a @cite{then} or @cite{else} keyword following the
13368 keyword in an @cite{if} statement. @cite{or else} and @cite{and then} are not
13369 affected, and a special exception allows a pragma to appear after @cite{else}.
13372 @geindex -gnatyt (gcc)
13377 @item @code{-gnatyt}
13379 @emph{Check token spacing.}
13381 The following token spacing rules are enforced:
13387 The keywords @cite{abs} and @cite{not} must be followed by a space.
13390 The token @cite{=>} must be surrounded by spaces.
13393 The token @cite{<>} must be preceded by a space or a left parenthesis.
13396 Binary operators other than @cite{**} must be surrounded by spaces.
13397 There is no restriction on the layout of the @cite{**} binary operator.
13400 Colon must be surrounded by spaces.
13403 Colon-equal (assignment, initialization) must be surrounded by spaces.
13406 Comma must be the first non-blank character on the line, or be
13407 immediately preceded by a non-blank character, and must be followed
13411 If the token preceding a left parenthesis ends with a letter or digit, then
13412 a space must separate the two tokens.
13415 If the token following a right parenthesis starts with a letter or digit, then
13416 a space must separate the two tokens.
13419 A right parenthesis must either be the first non-blank character on
13420 a line, or it must be preceded by a non-blank character.
13423 A semicolon must not be preceded by a space, and must not be followed by
13424 a non-blank character.
13427 A unary plus or minus may not be followed by a space.
13430 A vertical bar must be surrounded by spaces.
13433 Exactly one blank (and no other white space) must appear between
13434 a @cite{not} token and a following @cite{in} token.
13437 @geindex -gnatyu (gcc)
13442 @item @code{-gnatyu}
13444 @emph{Check unnecessary blank lines.}
13446 Unnecessary blank lines are not allowed. A blank line is considered
13447 unnecessary if it appears at the end of the file, or if more than
13448 one blank line occurs in sequence.
13451 @geindex -gnatyx (gcc)
13456 @item @code{-gnatyx}
13458 @emph{Check extra parentheses.}
13460 Unnecessary extra level of parentheses (C-style) are not allowed
13461 around conditions in @cite{if} statements, @cite{while} statements and
13462 @cite{exit} statements.
13465 @geindex -gnatyy (gcc)
13470 @item @code{-gnatyy}
13472 @emph{Set all standard style check options}
13474 This is equivalent to @cite{gnaty3aAbcefhiklmnprst}, that is all checking
13475 options enabled with the exception of @emph{-gnatyB}, @emph{-gnatyd},
13476 @emph{-gnatyI}, @emph{-gnatyLnnn}, @emph{-gnatyo}, @emph{-gnatyO},
13477 @emph{-gnatyS}, @emph{-gnatyu}, and @emph{-gnatyx}.
13480 @geindex -gnaty- (gcc)
13485 @item @code{-gnaty-}
13487 @emph{Remove style check options}
13489 This causes any subsequent options in the string to act as canceling the
13490 corresponding style check option. To cancel maximum nesting level control,
13491 use @emph{L} parameter witout any integer value after that, because any
13492 digit following @emph{-} in the parameter string of the @emph{-gnaty}
13493 option will be threated as canceling indentation check. The same is true
13494 for @emph{M} parameter. @emph{y} and @emph{N} parameters are not
13495 allowed after @emph{-}.
13498 @geindex -gnaty+ (gcc)
13503 @item @code{-gnaty+}
13505 @emph{Enable style check options}
13507 This causes any subsequent options in the string to enable the corresponding
13508 style check option. That is, it cancels the effect of a previous -,
13512 @c end of switch description (leave this comment to ease automatic parsing for
13516 In the above rules, appearing in column one is always permitted, that is,
13517 counts as meeting either a requirement for a required preceding space,
13518 or as meeting a requirement for no preceding space.
13520 Appearing at the end of a line is also always permitted, that is, counts
13521 as meeting either a requirement for a following space, or as meeting
13522 a requirement for no following space.
13524 If any of these style rules is violated, a message is generated giving
13525 details on the violation. The initial characters of such messages are
13526 always '@cite{(style)}'. Note that these messages are treated as warning
13527 messages, so they normally do not prevent the generation of an object
13528 file. The @emph{-gnatwe} switch can be used to treat warning messages,
13529 including style messages, as fatal errors.
13531 The switch @code{-gnaty} on its own (that is not
13532 followed by any letters or digits) is equivalent
13533 to the use of @emph{-gnatyy} as described above, that is all
13534 built-in standard style check options are enabled.
13536 The switch @code{-gnatyN} clears any previously set style checks.
13538 @node Run-Time Checks,Using gcc for Syntax Checking,Style Checking,Compiler Switches
13539 @anchor{gnat_ugn/building_executable_programs_with_gnat run-time-checks}@anchor{fe}@anchor{gnat_ugn/building_executable_programs_with_gnat id19}@anchor{109}
13540 @subsection Run-Time Checks
13543 @geindex Division by zero
13545 @geindex Access before elaboration
13548 @geindex division by zero
13551 @geindex access before elaboration
13554 @geindex stack overflow checking
13556 By default, the following checks are suppressed: integer overflow
13557 checks, stack overflow checks, and checks for access before
13558 elaboration on subprogram calls. All other checks, including range
13559 checks and array bounds checks, are turned on by default. The
13560 following @emph{gcc} switches refine this default behavior.
13562 @geindex -gnatp (gcc)
13567 @item @code{-gnatp}
13569 @geindex Suppressing checks
13572 @geindex suppressing
13574 This switch causes the unit to be compiled
13575 as though @cite{pragma Suppress (All_checks)}
13576 had been present in the source. Validity checks are also eliminated (in
13577 other words @emph{-gnatp} also implies @emph{-gnatVn}.
13578 Use this switch to improve the performance
13579 of the code at the expense of safety in the presence of invalid data or
13582 Note that when checks are suppressed, the compiler is allowed, but not
13583 required, to omit the checking code. If the run-time cost of the
13584 checking code is zero or near-zero, the compiler will generate it even
13585 if checks are suppressed. In particular, if the compiler can prove
13586 that a certain check will necessarily fail, it will generate code to
13587 do an unconditional 'raise', even if checks are suppressed. The
13588 compiler warns in this case. Another case in which checks may not be
13589 eliminated is when they are embedded in certain run time routines such
13590 as math library routines.
13592 Of course, run-time checks are omitted whenever the compiler can prove
13593 that they will not fail, whether or not checks are suppressed.
13595 Note that if you suppress a check that would have failed, program
13596 execution is erroneous, which means the behavior is totally
13597 unpredictable. The program might crash, or print wrong answers, or
13598 do anything else. It might even do exactly what you wanted it to do
13599 (and then it might start failing mysteriously next week or next
13600 year). The compiler will generate code based on the assumption that
13601 the condition being checked is true, which can result in erroneous
13602 execution if that assumption is wrong.
13604 The checks subject to suppression include all the checks defined by
13605 the Ada standard, the additional implementation defined checks
13606 @cite{Alignment_Check},
13607 @cite{Duplicated_Tag_Check}, @cite{Predicate_Check}, and
13608 @cite{Validity_Check}, as well as any checks introduced using
13609 @cite{pragma Check_Name}. Note that @cite{Atomic_Synchronization}
13610 is not automatically suppressed by use of this option.
13612 If the code depends on certain checks being active, you can use
13613 pragma @cite{Unsuppress} either as a configuration pragma or as
13614 a local pragma to make sure that a specified check is performed
13615 even if @emph{gnatp} is specified.
13617 The @emph{-gnatp} switch has no effect if a subsequent
13618 @emph{-gnat-p} switch appears.
13621 @geindex -gnat-p (gcc)
13623 @geindex Suppressing checks
13626 @geindex suppressing
13633 @item @code{-gnat-p}
13635 This switch cancels the effect of a previous @emph{gnatp} switch.
13638 @geindex -gnato?? (gcc)
13640 @geindex Overflow checks
13642 @geindex Overflow mode
13650 @item @code{-gnato??}
13652 This switch controls the mode used for computing intermediate
13653 arithmetic integer operations, and also enables overflow checking.
13654 For a full description of overflow mode and checking control, see
13655 the 'Overflow Check Handling in GNAT' appendix in this
13658 Overflow checks are always enabled by this switch. The argument
13659 controls the mode, using the codes
13664 @item @emph{1 = STRICT}
13666 In STRICT mode, intermediate operations are always done using the
13667 base type, and overflow checking ensures that the result is within
13668 the base type range.
13670 @item @emph{2 = MINIMIZED}
13672 In MINIMIZED mode, overflows in intermediate operations are avoided
13673 where possible by using a larger integer type for the computation
13674 (typically @cite{Long_Long_Integer}). Overflow checking ensures that
13675 the result fits in this larger integer type.
13677 @item @emph{3 = ELIMINATED}
13679 In ELIMINATED mode, overflows in intermediate operations are avoided
13680 by using multi-precision arithmetic. In this case, overflow checking
13681 has no effect on intermediate operations (since overflow is impossible).
13684 If two digits are present after @emph{-gnato} then the first digit
13685 sets the mode for expressions outside assertions, and the second digit
13686 sets the mode for expressions within assertions. Here assertions is used
13687 in the technical sense (which includes for example precondition and
13688 postcondition expressions).
13690 If one digit is present, the corresponding mode is applicable to both
13691 expressions within and outside assertion expressions.
13693 If no digits are present, the default is to enable overflow checks
13694 and set STRICT mode for both kinds of expressions. This is compatible
13695 with the use of @emph{-gnato} in previous versions of GNAT.
13697 @geindex Machine_Overflows
13699 Note that the @emph{-gnato??} switch does not affect the code generated
13700 for any floating-point operations; it applies only to integer semantics.
13701 For floating-point, GNAT has the @cite{Machine_Overflows}
13702 attribute set to @cite{False} and the normal mode of operation is to
13703 generate IEEE NaN and infinite values on overflow or invalid operations
13704 (such as dividing 0.0 by 0.0).
13706 The reason that we distinguish overflow checking from other kinds of
13707 range constraint checking is that a failure of an overflow check, unlike
13708 for example the failure of a range check, can result in an incorrect
13709 value, but cannot cause random memory destruction (like an out of range
13710 subscript), or a wild jump (from an out of range case value). Overflow
13711 checking is also quite expensive in time and space, since in general it
13712 requires the use of double length arithmetic.
13714 Note again that the default is @emph{-gnato00},
13715 so overflow checking is not performed in default mode. This means that out of
13716 the box, with the default settings, GNAT does not do all the checks
13717 expected from the language description in the Ada Reference Manual.
13718 If you want all constraint checks to be performed, as described in this Manual,
13719 then you must explicitly use the @emph{-gnato??}
13720 switch either on the @emph{gnatmake} or @emph{gcc} command.
13723 @geindex -gnatE (gcc)
13725 @geindex Elaboration checks
13728 @geindex elaboration
13733 @item @code{-gnatE}
13735 Enables dynamic checks for access-before-elaboration
13736 on subprogram calls and generic instantiations.
13737 Note that @emph{-gnatE} is not necessary for safety, because in the
13738 default mode, GNAT ensures statically that the checks would not fail.
13739 For full details of the effect and use of this switch,
13740 @ref{1e,,Compiling with gcc}.
13743 @geindex -fstack-check (gcc)
13745 @geindex Stack Overflow Checking
13748 @geindex stack overflow checking
13753 @item @code{-fstack-check}
13755 Activates stack overflow checking. For full details of the effect and use of
13756 this switch see @ref{f9,,Stack Overflow Checking}.
13759 @geindex Unsuppress
13761 The setting of these switches only controls the default setting of the
13762 checks. You may modify them using either @cite{Suppress} (to remove
13763 checks) or @cite{Unsuppress} (to add back suppressed checks) pragmas in
13764 the program source.
13766 @node Using gcc for Syntax Checking,Using gcc for Semantic Checking,Run-Time Checks,Compiler Switches
13767 @anchor{gnat_ugn/building_executable_programs_with_gnat id20}@anchor{10a}@anchor{gnat_ugn/building_executable_programs_with_gnat using-gcc-for-syntax-checking}@anchor{10b}
13768 @subsection Using @emph{gcc} for Syntax Checking
13771 @geindex -gnats (gcc)
13776 @item @code{-gnats}
13778 The @cite{s} stands for 'syntax'.
13780 Run GNAT in syntax checking only mode. For
13781 example, the command
13784 $ gcc -c -gnats x.adb
13787 compiles file @code{x.adb} in syntax-check-only mode. You can check a
13788 series of files in a single command
13789 , and can use wild cards to specify such a group of files.
13790 Note that you must specify the @emph{-c} (compile
13791 only) flag in addition to the @emph{-gnats} flag.
13793 You may use other switches in conjunction with @emph{-gnats}. In
13794 particular, @emph{-gnatl} and @emph{-gnatv} are useful to control the
13795 format of any generated error messages.
13797 When the source file is empty or contains only empty lines and/or comments,
13798 the output is a warning:
13801 $ gcc -c -gnats -x ada toto.txt
13802 toto.txt:1:01: warning: empty file, contains no compilation units
13806 Otherwise, the output is simply the error messages, if any. No object file or
13807 ALI file is generated by a syntax-only compilation. Also, no units other
13808 than the one specified are accessed. For example, if a unit @cite{X}
13809 @emph{with}s a unit @cite{Y}, compiling unit @cite{X} in syntax
13810 check only mode does not access the source file containing unit
13813 @geindex Multiple units
13814 @geindex syntax checking
13816 Normally, GNAT allows only a single unit in a source file. However, this
13817 restriction does not apply in syntax-check-only mode, and it is possible
13818 to check a file containing multiple compilation units concatenated
13819 together. This is primarily used by the @cite{gnatchop} utility
13820 (@ref{38,,Renaming Files with gnatchop}).
13823 @node Using gcc for Semantic Checking,Compiling Different Versions of Ada,Using gcc for Syntax Checking,Compiler Switches
13824 @anchor{gnat_ugn/building_executable_programs_with_gnat id21}@anchor{10c}@anchor{gnat_ugn/building_executable_programs_with_gnat using-gcc-for-semantic-checking}@anchor{10d}
13825 @subsection Using @emph{gcc} for Semantic Checking
13828 @geindex -gnatc (gcc)
13833 @item @code{-gnatc}
13835 The @cite{c} stands for 'check'.
13836 Causes the compiler to operate in semantic check mode,
13837 with full checking for all illegalities specified in the
13838 Ada Reference Manual, but without generation of any object code
13839 (no object file is generated).
13841 Because dependent files must be accessed, you must follow the GNAT
13842 semantic restrictions on file structuring to operate in this mode:
13848 The needed source files must be accessible
13849 (see @ref{8e,,Search Paths and the Run-Time Library (RTL)}).
13852 Each file must contain only one compilation unit.
13855 The file name and unit name must match (@ref{54,,File Naming Rules}).
13858 The output consists of error messages as appropriate. No object file is
13859 generated. An @code{ALI} file is generated for use in the context of
13860 cross-reference tools, but this file is marked as not being suitable
13861 for binding (since no object file is generated).
13862 The checking corresponds exactly to the notion of
13863 legality in the Ada Reference Manual.
13865 Any unit can be compiled in semantics-checking-only mode, including
13866 units that would not normally be compiled (subunits,
13867 and specifications where a separate body is present).
13870 @node Compiling Different Versions of Ada,Character Set Control,Using gcc for Semantic Checking,Compiler Switches
13871 @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{10e}
13872 @subsection Compiling Different Versions of Ada
13875 The switches described in this section allow you to explicitly specify
13876 the version of the Ada language that your programs are written in.
13877 The default mode is Ada 2012,
13878 but you can also specify Ada 95, Ada 2005 mode, or
13879 indicate Ada 83 compatibility mode.
13881 @geindex Compatibility with Ada 83
13883 @geindex -gnat83 (gcc)
13886 @geindex Ada 83 tests
13888 @geindex Ada 83 mode
13893 @item @code{-gnat83 (Ada 83 Compatibility Mode)}
13895 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
13896 specifies that the program is to be compiled in Ada 83 mode. With
13897 @emph{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
13898 semantics where this can be done easily.
13899 It is not possible to guarantee this switch does a perfect
13900 job; some subtle tests, such as are
13901 found in earlier ACVC tests (and that have been removed from the ACATS suite
13902 for Ada 95), might not compile correctly.
13903 Nevertheless, this switch may be useful in some circumstances, for example
13904 where, due to contractual reasons, existing code needs to be maintained
13905 using only Ada 83 features.
13907 With few exceptions (most notably the need to use @cite{<>} on
13908 .. index:: Generic formal parameters
13910 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
13911 reserved words, and the use of packages
13912 with optional bodies), it is not necessary to specify the
13913 @emph{-gnat83} switch when compiling Ada 83 programs, because, with rare
13914 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
13915 a correct Ada 83 program is usually also a correct program
13916 in these later versions of the language standard. For further information
13917 please refer to the @cite{Compatibility_and_Porting_Guide} chapter in the
13918 @cite{GNAT Reference Manual}.
13921 @geindex -gnat95 (gcc)
13923 @geindex Ada 95 mode
13928 @item @code{-gnat95} (Ada 95 mode)
13930 This switch directs the compiler to implement the Ada 95 version of the
13932 Since Ada 95 is almost completely upwards
13933 compatible with Ada 83, Ada 83 programs may generally be compiled using
13934 this switch (see the description of the @emph{-gnat83} switch for further
13935 information about Ada 83 mode).
13936 If an Ada 2005 program is compiled in Ada 95 mode,
13937 uses of the new Ada 2005 features will cause error
13938 messages or warnings.
13940 This switch also can be used to cancel the effect of a previous
13941 @emph{-gnat83}, @emph{-gnat05/2005}, or @emph{-gnat12/2012}
13942 switch earlier in the command line.
13945 @geindex -gnat05 (gcc)
13947 @geindex -gnat2005 (gcc)
13949 @geindex Ada 2005 mode
13954 @item @code{-gnat05} or @code{-gnat2005} (Ada 2005 mode)
13956 This switch directs the compiler to implement the Ada 2005 version of the
13957 language, as documented in the official Ada standards document.
13958 Since Ada 2005 is almost completely upwards
13959 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
13960 may generally be compiled using this switch (see the description of the
13961 @emph{-gnat83} and @emph{-gnat95} switches for further
13965 @geindex -gnat12 (gcc)
13967 @geindex -gnat2012 (gcc)
13969 @geindex Ada 2012 mode
13974 @item @code{-gnat12} or @code{-gnat2012} (Ada 2012 mode)
13976 This switch directs the compiler to implement the Ada 2012 version of the
13977 language (also the default).
13978 Since Ada 2012 is almost completely upwards
13979 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
13980 Ada 83 and Ada 95 programs
13981 may generally be compiled using this switch (see the description of the
13982 @emph{-gnat83}, @emph{-gnat95}, and @emph{-gnat05/2005} switches
13983 for further information).
13986 @geindex -gnatX (gcc)
13988 @geindex Ada language extensions
13990 @geindex GNAT extensions
13995 @item @code{-gnatX} (Enable GNAT Extensions)
13997 This switch directs the compiler to implement the latest version of the
13998 language (currently Ada 2012) and also to enable certain GNAT implementation
13999 extensions that are not part of any Ada standard. For a full list of these
14000 extensions, see the GNAT reference manual.
14003 @node Character Set Control,File Naming Control,Compiling Different Versions of Ada,Compiler Switches
14004 @anchor{gnat_ugn/building_executable_programs_with_gnat id23}@anchor{10f}@anchor{gnat_ugn/building_executable_programs_with_gnat character-set-control}@anchor{4a}
14005 @subsection Character Set Control
14008 @geindex -gnati (gcc)
14013 @item @code{-gnati@emph{c}}
14015 Normally GNAT recognizes the Latin-1 character set in source program
14016 identifiers, as described in the Ada Reference Manual.
14018 GNAT to recognize alternate character sets in identifiers. @cite{c} is a
14019 single character indicating the character set, as follows:
14022 @multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
14029 ISO 8859-1 (Latin-1) identifiers
14037 ISO 8859-2 (Latin-2) letters allowed in identifiers
14045 ISO 8859-3 (Latin-3) letters allowed in identifiers
14053 ISO 8859-4 (Latin-4) letters allowed in identifiers
14061 ISO 8859-5 (Cyrillic) letters allowed in identifiers
14069 ISO 8859-15 (Latin-9) letters allowed in identifiers
14077 IBM PC letters (code page 437) allowed in identifiers
14085 IBM PC letters (code page 850) allowed in identifiers
14093 Full upper-half codes allowed in identifiers
14101 No upper-half codes allowed in identifiers
14109 Wide-character codes (that is, codes greater than 255)
14110 allowed in identifiers
14115 See @ref{40,,Foreign Language Representation} for full details on the
14116 implementation of these character sets.
14119 @geindex -gnatW (gcc)
14124 @item @code{-gnatW@emph{e}}
14126 Specify the method of encoding for wide characters.
14127 @cite{e} is one of the following:
14130 @multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
14137 Hex encoding (brackets coding also recognized)
14145 Upper half encoding (brackets encoding also recognized)
14153 Shift/JIS encoding (brackets encoding also recognized)
14161 EUC encoding (brackets encoding also recognized)
14169 UTF-8 encoding (brackets encoding also recognized)
14177 Brackets encoding only (default value)
14182 For full details on these encoding
14183 methods see @ref{50,,Wide_Character Encodings}.
14184 Note that brackets coding is always accepted, even if one of the other
14185 options is specified, so for example @emph{-gnatW8} specifies that both
14186 brackets and UTF-8 encodings will be recognized. The units that are
14187 with'ed directly or indirectly will be scanned using the specified
14188 representation scheme, and so if one of the non-brackets scheme is
14189 used, it must be used consistently throughout the program. However,
14190 since brackets encoding is always recognized, it may be conveniently
14191 used in standard libraries, allowing these libraries to be used with
14192 any of the available coding schemes.
14194 Note that brackets encoding only applies to program text. Within comments,
14195 brackets are considered to be normal graphic characters, and bracket sequences
14196 are never recognized as wide characters.
14198 If no @emph{-gnatW?} parameter is present, then the default
14199 representation is normally Brackets encoding only. However, if the
14200 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
14201 byte order mark or BOM for UTF-8), then these three characters are
14202 skipped and the default representation for the file is set to UTF-8.
14204 Note that the wide character representation that is specified (explicitly
14205 or by default) for the main program also acts as the default encoding used
14206 for Wide_Text_IO files if not specifically overridden by a WCEM form
14210 When no @emph{-gnatW?} is specified, then characters (other than wide
14211 characters represented using brackets notation) are treated as 8-bit
14212 Latin-1 codes. The codes recognized are the Latin-1 graphic characters,
14213 and ASCII format effectors (CR, LF, HT, VT). Other lower half control
14214 characters in the range 16#00#..16#1F# are not accepted in program text
14215 or in comments. Upper half control characters (16#80#..16#9F#) are rejected
14216 in program text, but allowed and ignored in comments. Note in particular
14217 that the Next Line (NEL) character whose encoding is 16#85# is not recognized
14218 as an end of line in this default mode. If your source program contains
14219 instances of the NEL character used as a line terminator,
14220 you must use UTF-8 encoding for the whole
14221 source program. In default mode, all lines must be ended by a standard
14222 end of line sequence (CR, CR/LF, or LF).
14224 Note that the convention of simply accepting all upper half characters in
14225 comments means that programs that use standard ASCII for program text, but
14226 UTF-8 encoding for comments are accepted in default mode, providing that the
14227 comments are ended by an appropriate (CR, or CR/LF, or LF) line terminator.
14228 This is a common mode for many programs with foreign language comments.
14230 @node File Naming Control,Subprogram Inlining Control,Character Set Control,Compiler Switches
14231 @anchor{gnat_ugn/building_executable_programs_with_gnat file-naming-control}@anchor{110}@anchor{gnat_ugn/building_executable_programs_with_gnat id24}@anchor{111}
14232 @subsection File Naming Control
14235 @geindex -gnatk (gcc)
14240 @item @code{-gnatk@emph{n}}
14242 Activates file name 'krunching'. @cite{n}, a decimal integer in the range
14243 1-999, indicates the maximum allowable length of a file name (not
14244 including the @code{.ads} or @code{.adb} extension). The default is not
14245 to enable file name krunching.
14247 For the source file naming rules, @ref{54,,File Naming Rules}.
14250 @node Subprogram Inlining Control,Auxiliary Output Control,File Naming Control,Compiler Switches
14251 @anchor{gnat_ugn/building_executable_programs_with_gnat subprogram-inlining-control}@anchor{112}@anchor{gnat_ugn/building_executable_programs_with_gnat id25}@anchor{113}
14252 @subsection Subprogram Inlining Control
14255 @geindex -gnatn (gcc)
14260 @item @code{-gnatn[12]}
14262 The @cite{n} here is intended to suggest the first syllable of the
14264 GNAT recognizes and processes @cite{Inline} pragmas. However, for the
14265 inlining to actually occur, optimization must be enabled and, in order
14266 to enable inlining of subprograms specified by pragma @cite{Inline},
14267 you must also specify this switch.
14268 In the absence of this switch, GNAT does not attempt
14269 inlining and does not need to access the bodies of
14270 subprograms for which @cite{pragma Inline} is specified if they are not
14271 in the current unit.
14273 You can optionally specify the inlining level: 1 for moderate inlining across
14274 modules, which is a good compromise between compilation times and performances
14275 at run time, or 2 for full inlining across modules, which may bring about
14276 longer compilation times. If no inlining level is specified, the compiler will
14277 pick it based on the optimization level: 1 for @emph{-O1}, @emph{-O2} or
14278 @emph{-Os} and 2 for @emph{-O3}.
14280 If you specify this switch the compiler will access these bodies,
14281 creating an extra source dependency for the resulting object file, and
14282 where possible, the call will be inlined.
14283 For further details on when inlining is possible
14284 see @ref{114,,Inlining of Subprograms}.
14287 @geindex -gnatN (gcc)
14292 @item @code{-gnatN}
14294 This switch activates front-end inlining which also
14295 generates additional dependencies.
14297 When using a gcc-based back end (in practice this means using any version
14298 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
14299 @emph{-gnatN} is deprecated, and the use of @emph{-gnatn} is preferred.
14300 Historically front end inlining was more extensive than the gcc back end
14301 inlining, but that is no longer the case.
14304 @node Auxiliary Output Control,Debugging Control,Subprogram Inlining Control,Compiler Switches
14305 @anchor{gnat_ugn/building_executable_programs_with_gnat auxiliary-output-control}@anchor{115}@anchor{gnat_ugn/building_executable_programs_with_gnat id26}@anchor{116}
14306 @subsection Auxiliary Output Control
14309 @geindex -gnatt (gcc)
14311 @geindex Writing internal trees
14313 @geindex Internal trees
14314 @geindex writing to file
14319 @item @code{-gnatt}
14321 Causes GNAT to write the internal tree for a unit to a file (with the
14322 extension @code{.adt}.
14323 This not normally required, but is used by separate analysis tools.
14325 these tools do the necessary compilations automatically, so you should
14326 not have to specify this switch in normal operation.
14327 Note that the combination of switches @emph{-gnatct}
14328 generates a tree in the form required by ASIS applications.
14331 @geindex -gnatu (gcc)
14336 @item @code{-gnatu}
14338 Print a list of units required by this compilation on @code{stdout}.
14339 The listing includes all units on which the unit being compiled depends
14340 either directly or indirectly.
14343 @geindex -pass-exit-codes (gcc)
14348 @item @code{-pass-exit-codes}
14350 If this switch is not used, the exit code returned by @emph{gcc} when
14351 compiling multiple files indicates whether all source files have
14352 been successfully used to generate object files or not.
14354 When @emph{-pass-exit-codes} is used, @emph{gcc} exits with an extended
14355 exit status and allows an integrated development environment to better
14356 react to a compilation failure. Those exit status are:
14359 @multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
14366 There was an error in at least one source file.
14374 At least one source file did not generate an object file.
14382 The compiler died unexpectedly (internal error for example).
14390 An object file has been generated for every source file.
14396 @node Debugging Control,Exception Handling Control,Auxiliary Output Control,Compiler Switches
14397 @anchor{gnat_ugn/building_executable_programs_with_gnat debugging-control}@anchor{117}@anchor{gnat_ugn/building_executable_programs_with_gnat id27}@anchor{118}
14398 @subsection Debugging Control
14403 @geindex Debugging options
14406 @geindex -gnatd (gcc)
14411 @item @code{-gnatd@emph{x}}
14413 Activate internal debugging switches. @cite{x} is a letter or digit, or
14414 string of letters or digits, which specifies the type of debugging
14415 outputs desired. Normally these are used only for internal development
14416 or system debugging purposes. You can find full documentation for these
14417 switches in the body of the @cite{Debug} unit in the compiler source
14418 file @code{debug.adb}.
14421 @geindex -gnatG (gcc)
14426 @item @code{-gnatG[=@emph{nn}]}
14428 This switch causes the compiler to generate auxiliary output containing
14429 a pseudo-source listing of the generated expanded code. Like most Ada
14430 compilers, GNAT works by first transforming the high level Ada code into
14431 lower level constructs. For example, tasking operations are transformed
14432 into calls to the tasking run-time routines. A unique capability of GNAT
14433 is to list this expanded code in a form very close to normal Ada source.
14434 This is very useful in understanding the implications of various Ada
14435 usage on the efficiency of the generated code. There are many cases in
14436 Ada (e.g., the use of controlled types), where simple Ada statements can
14437 generate a lot of run-time code. By using @emph{-gnatG} you can identify
14438 these cases, and consider whether it may be desirable to modify the coding
14439 approach to improve efficiency.
14441 The optional parameter @cite{nn} if present after -gnatG specifies an
14442 alternative maximum line length that overrides the normal default of 72.
14443 This value is in the range 40-999999, values less than 40 being silently
14444 reset to 40. The equal sign is optional.
14446 The format of the output is very similar to standard Ada source, and is
14447 easily understood by an Ada programmer. The following special syntactic
14448 additions correspond to low level features used in the generated code that
14449 do not have any exact analogies in pure Ada source form. The following
14450 is a partial list of these special constructions. See the spec
14451 of package @cite{Sprint} in file @code{sprint.ads} for a full list.
14453 @geindex -gnatL (gcc)
14455 If the switch @emph{-gnatL} is used in conjunction with
14456 @emph{-gnatG}, then the original source lines are interspersed
14457 in the expanded source (as comment lines with the original line number).
14462 @item @code{new @emph{xxx} [storage_pool = @emph{yyy}]}
14464 Shows the storage pool being used for an allocator.
14466 @item @code{at end @emph{procedure-name};}
14468 Shows the finalization (cleanup) procedure for a scope.
14470 @item @code{(if @emph{expr} then @emph{expr} else @emph{expr})}
14472 Conditional expression equivalent to the @cite{x?y:z} construction in C.
14474 @item @code{@emph{target}^(@emph{source})}
14476 A conversion with floating-point truncation instead of rounding.
14478 @item @code{@emph{target}?(@emph{source})}
14480 A conversion that bypasses normal Ada semantic checking. In particular
14481 enumeration types and fixed-point types are treated simply as integers.
14483 @item @code{@emph{target}?^(@emph{source})}
14485 Combines the above two cases.
14488 @code{@emph{x} #/ @emph{y}}
14490 @code{@emph{x} #mod @emph{y}}
14492 @code{@emph{x} # @emph{y}}
14497 @item @code{@emph{x} #rem @emph{y}}
14499 A division or multiplication of fixed-point values which are treated as
14500 integers without any kind of scaling.
14502 @item @code{free @emph{expr} [storage_pool = @emph{xxx}]}
14504 Shows the storage pool associated with a @cite{free} statement.
14506 @item @code{[subtype or type declaration]}
14508 Used to list an equivalent declaration for an internally generated
14509 type that is referenced elsewhere in the listing.
14511 @item @code{freeze @emph{type-name} [@emph{actions}]}
14513 Shows the point at which @cite{type-name} is frozen, with possible
14514 associated actions to be performed at the freeze point.
14516 @item @code{reference @emph{itype}}
14518 Reference (and hence definition) to internal type @cite{itype}.
14520 @item @code{@emph{function-name}! (@emph{arg}, @emph{arg}, @emph{arg})}
14522 Intrinsic function call.
14524 @item @code{@emph{label-name} : label}
14526 Declaration of label @cite{labelname}.
14528 @item @code{#$ @emph{subprogram-name}}
14530 An implicit call to a run-time support routine
14531 (to meet the requirement of H.3.1(9) in a
14532 convenient manner).
14534 @item @code{@emph{expr} && @emph{expr} && @emph{expr} ... && @emph{expr}}
14536 A multiple concatenation (same effect as @cite{expr} & @cite{expr} &
14537 @cite{expr}, but handled more efficiently).
14539 @item @code{[constraint_error]}
14541 Raise the @cite{Constraint_Error} exception.
14543 @item @code{@emph{expression}'reference}
14545 A pointer to the result of evaluating @{expression@}.
14547 @item @code{@emph{target-type}!(@emph{source-expression})}
14549 An unchecked conversion of @cite{source-expression} to @cite{target-type}.
14551 @item @code{[@emph{numerator}/@emph{denominator}]}
14553 Used to represent internal real literals (that) have no exact
14554 representation in base 2-16 (for example, the result of compile time
14555 evaluation of the expression 1.0/27.0).
14559 @geindex -gnatD (gcc)
14564 @item @code{-gnatD[=nn]}
14566 When used in conjunction with @emph{-gnatG}, this switch causes
14567 the expanded source, as described above for
14568 @emph{-gnatG} to be written to files with names
14569 @code{xxx.dg}, where @code{xxx} is the normal file name,
14570 instead of to the standard output file. For
14571 example, if the source file name is @code{hello.adb}, then a file
14572 @code{hello.adb.dg} will be written. The debugging
14573 information generated by the @emph{gcc} @emph{-g} switch
14574 will refer to the generated @code{xxx.dg} file. This allows
14575 you to do source level debugging using the generated code which is
14576 sometimes useful for complex code, for example to find out exactly
14577 which part of a complex construction raised an exception. This switch
14578 also suppress generation of cross-reference information (see
14579 @emph{-gnatx}) since otherwise the cross-reference information
14580 would refer to the @code{.dg} file, which would cause
14581 confusion since this is not the original source file.
14583 Note that @emph{-gnatD} actually implies @emph{-gnatG}
14584 automatically, so it is not necessary to give both options.
14585 In other words @emph{-gnatD} is equivalent to @emph{-gnatDG}).
14587 @geindex -gnatL (gcc)
14589 If the switch @emph{-gnatL} is used in conjunction with
14590 @emph{-gnatDG}, then the original source lines are interspersed
14591 in the expanded source (as comment lines with the original line number).
14593 The optional parameter @cite{nn} if present after -gnatD specifies an
14594 alternative maximum line length that overrides the normal default of 72.
14595 This value is in the range 40-999999, values less than 40 being silently
14596 reset to 40. The equal sign is optional.
14599 @geindex -gnatr (gcc)
14601 @geindex pragma Restrictions
14606 @item @code{-gnatr}
14608 This switch causes pragma Restrictions to be treated as Restriction_Warnings
14609 so that violation of restrictions causes warnings rather than illegalities.
14610 This is useful during the development process when new restrictions are added
14611 or investigated. The switch also causes pragma Profile to be treated as
14612 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
14613 restriction warnings rather than restrictions.
14616 @geindex -gnatR (gcc)
14621 @item @code{-gnatR[0|1|2|3[s]]}
14623 This switch controls output from the compiler of a listing showing
14624 representation information for declared types and objects. For
14625 @emph{-gnatR0}, no information is output (equivalent to omitting
14626 the @emph{-gnatR} switch). For @emph{-gnatR1} (which is the default,
14627 so @emph{-gnatR} with no parameter has the same effect), size and alignment
14628 information is listed for declared array and record types. For
14629 @emph{-gnatR2}, size and alignment information is listed for all
14630 declared types and objects. The @cite{Linker_Section} is also listed for any
14631 entity for which the @cite{Linker_Section} is set explicitly or implicitly (the
14632 latter case occurs for objects of a type for which a @cite{Linker_Section}
14635 Finally @emph{-gnatR3} includes symbolic
14636 expressions for values that are computed at run time for
14637 variant records. These symbolic expressions have a mostly obvious
14638 format with #n being used to represent the value of the n'th
14639 discriminant. See source files @code{repinfo.ads/adb} in the
14640 @cite{GNAT} sources for full details on the format of @emph{-gnatR3}
14641 output. If the switch is followed by an s (e.g., @emph{-gnatR2s}), then
14642 the output is to a file with the name @code{file.rep} where
14643 file is the name of the corresponding source file.
14645 @item @code{-gnatRm[s]}
14647 This form of the switch controls output of subprogram conventions
14648 and parameter passing mechanisms for all subprograms. A following
14649 @cite{s} means output to a file as described above.
14651 Note that it is possible for record components to have zero size. In
14652 this case, the component clause uses an obvious extension of permitted
14653 Ada syntax, for example @cite{at 0 range 0 .. -1}.
14655 Representation information requires that code be generated (since it is the
14656 code generator that lays out complex data structures). If an attempt is made
14657 to output representation information when no code is generated, for example
14658 when a subunit is compiled on its own, then no information can be generated
14659 and the compiler outputs a message to this effect.
14662 @geindex -gnatS (gcc)
14667 @item @code{-gnatS}
14669 The use of the switch @emph{-gnatS} for an
14670 Ada compilation will cause the compiler to output a
14671 representation of package Standard in a form very
14672 close to standard Ada. It is not quite possible to
14673 do this entirely in standard Ada (since new
14674 numeric base types cannot be created in standard
14675 Ada), but the output is easily
14676 readable to any Ada programmer, and is useful to
14677 determine the characteristics of target dependent
14678 types in package Standard.
14681 @geindex -gnatx (gcc)
14686 @item @code{-gnatx}
14688 Normally the compiler generates full cross-referencing information in
14689 the @code{ALI} file. This information is used by a number of tools,
14690 including @cite{gnatfind} and @cite{gnatxref}. The @emph{-gnatx} switch
14691 suppresses this information. This saves some space and may slightly
14692 speed up compilation, but means that these tools cannot be used.
14695 @node Exception Handling Control,Units to Sources Mapping Files,Debugging Control,Compiler Switches
14696 @anchor{gnat_ugn/building_executable_programs_with_gnat id28}@anchor{119}@anchor{gnat_ugn/building_executable_programs_with_gnat exception-handling-control}@anchor{11a}
14697 @subsection Exception Handling Control
14700 GNAT uses two methods for handling exceptions at run-time. The
14701 @cite{setjmp/longjmp} method saves the context when entering
14702 a frame with an exception handler. Then when an exception is
14703 raised, the context can be restored immediately, without the
14704 need for tracing stack frames. This method provides very fast
14705 exception propagation, but introduces significant overhead for
14706 the use of exception handlers, even if no exception is raised.
14708 The other approach is called 'zero cost' exception handling.
14709 With this method, the compiler builds static tables to describe
14710 the exception ranges. No dynamic code is required when entering
14711 a frame containing an exception handler. When an exception is
14712 raised, the tables are used to control a back trace of the
14713 subprogram invocation stack to locate the required exception
14714 handler. This method has considerably poorer performance for
14715 the propagation of exceptions, but there is no overhead for
14716 exception handlers if no exception is raised. Note that in this
14717 mode and in the context of mixed Ada and C/C++ programming,
14718 to propagate an exception through a C/C++ code, the C/C++ code
14719 must be compiled with the @emph{-funwind-tables} GCC's
14722 The following switches may be used to control which of the
14723 two exception handling methods is used.
14725 @geindex --RTS=sjlj (gnatmake)
14730 @item @code{--RTS=sjlj}
14732 This switch causes the setjmp/longjmp run-time (when available) to be used
14733 for exception handling. If the default
14734 mechanism for the target is zero cost exceptions, then
14735 this switch can be used to modify this default, and must be
14736 used for all units in the partition.
14737 This option is rarely used. One case in which it may be
14738 advantageous is if you have an application where exception
14739 raising is common and the overall performance of the
14740 application is improved by favoring exception propagation.
14743 @geindex --RTS=zcx (gnatmake)
14745 @geindex Zero Cost Exceptions
14750 @item @code{--RTS=zcx}
14752 This switch causes the zero cost approach to be used
14753 for exception handling. If this is the default mechanism for the
14754 target (see below), then this switch is unneeded. If the default
14755 mechanism for the target is setjmp/longjmp exceptions, then
14756 this switch can be used to modify this default, and must be
14757 used for all units in the partition.
14758 This option can only be used if the zero cost approach
14759 is available for the target in use, otherwise it will generate an error.
14762 The same option @emph{--RTS} must be used both for @emph{gcc}
14763 and @emph{gnatbind}. Passing this option to @emph{gnatmake}
14764 (@ref{df,,Switches for gnatmake}) will ensure the required consistency
14765 through the compilation and binding steps.
14767 @node Units to Sources Mapping Files,Code Generation Control,Exception Handling Control,Compiler Switches
14768 @anchor{gnat_ugn/building_executable_programs_with_gnat id29}@anchor{11b}@anchor{gnat_ugn/building_executable_programs_with_gnat units-to-sources-mapping-files}@anchor{fc}
14769 @subsection Units to Sources Mapping Files
14772 @geindex -gnatem (gcc)
14777 @item @code{-gnatem=@emph{path}}
14779 A mapping file is a way to communicate to the compiler two mappings:
14780 from unit names to file names (without any directory information) and from
14781 file names to path names (with full directory information). These mappings
14782 are used by the compiler to short-circuit the path search.
14784 The use of mapping files is not required for correct operation of the
14785 compiler, but mapping files can improve efficiency, particularly when
14786 sources are read over a slow network connection. In normal operation,
14787 you need not be concerned with the format or use of mapping files,
14788 and the @emph{-gnatem} switch is not a switch that you would use
14789 explicitly. It is intended primarily for use by automatic tools such as
14790 @emph{gnatmake} running under the project file facility. The
14791 description here of the format of mapping files is provided
14792 for completeness and for possible use by other tools.
14794 A mapping file is a sequence of sets of three lines. In each set, the
14795 first line is the unit name, in lower case, with @cite{%s} appended
14796 for specs and @cite{%b} appended for bodies; the second line is the
14797 file name; and the third line is the path name.
14804 /gnat/project1/sources/main.2.ada
14807 When the switch @emph{-gnatem} is specified, the compiler will
14808 create in memory the two mappings from the specified file. If there is
14809 any problem (nonexistent file, truncated file or duplicate entries),
14810 no mapping will be created.
14812 Several @emph{-gnatem} switches may be specified; however, only the
14813 last one on the command line will be taken into account.
14815 When using a project file, @emph{gnatmake} creates a temporary
14816 mapping file and communicates it to the compiler using this switch.
14819 @node Code Generation Control,,Units to Sources Mapping Files,Compiler Switches
14820 @anchor{gnat_ugn/building_executable_programs_with_gnat code-generation-control}@anchor{11c}@anchor{gnat_ugn/building_executable_programs_with_gnat id30}@anchor{11d}
14821 @subsection Code Generation Control
14824 The GCC technology provides a wide range of target dependent
14825 @code{-m} switches for controlling
14826 details of code generation with respect to different versions of
14827 architectures. This includes variations in instruction sets (e.g.,
14828 different members of the power pc family), and different requirements
14829 for optimal arrangement of instructions (e.g., different members of
14830 the x86 family). The list of available @emph{-m} switches may be
14831 found in the GCC documentation.
14833 Use of these @emph{-m} switches may in some cases result in improved
14836 The GNAT technology is tested and qualified without any
14837 @code{-m} switches,
14838 so generally the most reliable approach is to avoid the use of these
14839 switches. However, we generally expect most of these switches to work
14840 successfully with GNAT, and many customers have reported successful
14841 use of these options.
14843 Our general advice is to avoid the use of @emph{-m} switches unless
14844 special needs lead to requirements in this area. In particular,
14845 there is no point in using @emph{-m} switches to improve performance
14846 unless you actually see a performance improvement.
14848 @node Binding with gnatbind,Linking with gnatlink,Compiler Switches,Building Executable Programs with GNAT
14849 @anchor{gnat_ugn/building_executable_programs_with_gnat binding-with-gnatbind}@anchor{1f}@anchor{gnat_ugn/building_executable_programs_with_gnat id31}@anchor{11e}
14850 @section Binding with @cite{gnatbind}
14855 This chapter describes the GNAT binder, @cite{gnatbind}, which is used
14856 to bind compiled GNAT objects.
14858 Note: to invoke @cite{gnatbind} with a project file, use the @cite{gnat}
14859 driver (see @ref{11f,,The GNAT Driver and Project Files}).
14861 The @cite{gnatbind} program performs four separate functions:
14867 Checks that a program is consistent, in accordance with the rules in
14868 Chapter 10 of the Ada Reference Manual. In particular, error
14869 messages are generated if a program uses inconsistent versions of a
14873 Checks that an acceptable order of elaboration exists for the program
14874 and issues an error message if it cannot find an order of elaboration
14875 that satisfies the rules in Chapter 10 of the Ada Language Manual.
14878 Generates a main program incorporating the given elaboration order.
14879 This program is a small Ada package (body and spec) that
14880 must be subsequently compiled
14881 using the GNAT compiler. The necessary compilation step is usually
14882 performed automatically by @emph{gnatlink}. The two most important
14883 functions of this program
14884 are to call the elaboration routines of units in an appropriate order
14885 and to call the main program.
14888 Determines the set of object files required by the given main program.
14889 This information is output in the forms of comments in the generated program,
14890 to be read by the @emph{gnatlink} utility used to link the Ada application.
14894 * Running gnatbind::
14895 * Switches for gnatbind::
14896 * Command-Line Access::
14897 * Search Paths for gnatbind::
14898 * Examples of gnatbind Usage::
14902 @node Running gnatbind,Switches for gnatbind,,Binding with gnatbind
14903 @anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatbind}@anchor{120}@anchor{gnat_ugn/building_executable_programs_with_gnat id32}@anchor{121}
14904 @subsection Running @cite{gnatbind}
14907 The form of the @cite{gnatbind} command is
14910 $ gnatbind [`switches`] `mainprog`[.ali] [`switches`]
14913 where @code{mainprog.adb} is the Ada file containing the main program
14914 unit body. @cite{gnatbind} constructs an Ada
14915 package in two files whose names are
14916 @code{b~mainprog.ads}, and @code{b~mainprog.adb}.
14917 For example, if given the
14918 parameter @code{hello.ali}, for a main program contained in file
14919 @code{hello.adb}, the binder output files would be @code{b~hello.ads}
14920 and @code{b~hello.adb}.
14922 When doing consistency checking, the binder takes into consideration
14923 any source files it can locate. For example, if the binder determines
14924 that the given main program requires the package @cite{Pack}, whose
14926 file is @code{pack.ali} and whose corresponding source spec file is
14927 @code{pack.ads}, it attempts to locate the source file @code{pack.ads}
14928 (using the same search path conventions as previously described for the
14929 @emph{gcc} command). If it can locate this source file, it checks that
14931 or source checksums of the source and its references to in @code{ALI} files
14932 match. In other words, any @code{ALI} files that mentions this spec must have
14933 resulted from compiling this version of the source file (or in the case
14934 where the source checksums match, a version close enough that the
14935 difference does not matter).
14937 @geindex Source files
14938 @geindex use by binder
14940 The effect of this consistency checking, which includes source files, is
14941 that the binder ensures that the program is consistent with the latest
14942 version of the source files that can be located at bind time. Editing a
14943 source file without compiling files that depend on the source file cause
14944 error messages to be generated by the binder.
14946 For example, suppose you have a main program @code{hello.adb} and a
14947 package @cite{P}, from file @code{p.ads} and you perform the following
14954 Enter @cite{gcc -c hello.adb} to compile the main program.
14957 Enter @cite{gcc -c p.ads} to compile package @cite{P}.
14960 Edit file @code{p.ads}.
14963 Enter @cite{gnatbind hello}.
14966 At this point, the file @code{p.ali} contains an out-of-date time stamp
14967 because the file @code{p.ads} has been edited. The attempt at binding
14968 fails, and the binder generates the following error messages:
14971 error: "hello.adb" must be recompiled ("p.ads" has been modified)
14972 error: "p.ads" has been modified and must be recompiled
14975 Now both files must be recompiled as indicated, and then the bind can
14976 succeed, generating a main program. You need not normally be concerned
14977 with the contents of this file, but for reference purposes a sample
14978 binder output file is given in @ref{10,,Example of Binder Output File}.
14980 In most normal usage, the default mode of @emph{gnatbind} which is to
14981 generate the main package in Ada, as described in the previous section.
14982 In particular, this means that any Ada programmer can read and understand
14983 the generated main program. It can also be debugged just like any other
14984 Ada code provided the @emph{-g} switch is used for
14985 @emph{gnatbind} and @emph{gnatlink}.
14987 @node Switches for gnatbind,Command-Line Access,Running gnatbind,Binding with gnatbind
14988 @anchor{gnat_ugn/building_executable_programs_with_gnat id33}@anchor{122}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatbind}@anchor{123}
14989 @subsection Switches for @emph{gnatbind}
14992 The following switches are available with @cite{gnatbind}; details will
14993 be presented in subsequent sections.
14995 @geindex --version (gnatbind)
15000 @item @code{--version}
15002 Display Copyright and version, then exit disregarding all other options.
15005 @geindex --help (gnatbind)
15010 @item @code{--help}
15012 If @emph{--version} was not used, display usage, then exit disregarding
15016 @geindex -a (gnatbind)
15023 Indicates that, if supported by the platform, the adainit procedure should
15024 be treated as an initialisation routine by the linker (a constructor). This
15025 is intended to be used by the Project Manager to automatically initialize
15026 shared Stand-Alone Libraries.
15029 @geindex -aO (gnatbind)
15036 Specify directory to be searched for ALI files.
15039 @geindex -aI (gnatbind)
15046 Specify directory to be searched for source file.
15049 @geindex -A (gnatbind)
15054 @item @code{-A[=@emph{filename}]}
15056 Output ALI list (to standard output or to the named file).
15059 @geindex -b (gnatbind)
15066 Generate brief messages to @code{stderr} even if verbose mode set.
15069 @geindex -c (gnatbind)
15076 Check only, no generation of binder output file.
15079 @geindex -dnn[k|m] (gnatbind)
15084 @item @code{-d@emph{nn}[k|m]}
15086 This switch can be used to change the default task stack size value
15087 to a specified size @cite{nn}, which is expressed in bytes by default, or
15088 in kilobytes when suffixed with @cite{k} or in megabytes when suffixed
15090 In the absence of a @code{[k|m]} suffix, this switch is equivalent,
15091 in effect, to completing all task specs with
15094 pragma Storage_Size (nn);
15097 When they do not already have such a pragma.
15100 @geindex -D (gnatbind)
15105 @item @code{-D@emph{nn}[k|m]}
15107 This switch can be used to change the default secondary stack size value
15108 to a specified size @cite{nn}, which is expressed in bytes by default, or
15109 in kilobytes when suffixed with @cite{k} or in megabytes when suffixed
15112 The secondary stack is used to deal with functions that return a variable
15113 sized result, for example a function returning an unconstrained
15114 String. There are two ways in which this secondary stack is allocated.
15116 For most targets, the secondary stack is growing on demand and is allocated
15117 as a chain of blocks in the heap. The -D option is not very
15118 relevant. It only give some control over the size of the allocated
15119 blocks (whose size is the minimum of the default secondary stack size value,
15120 and the actual size needed for the current allocation request).
15122 For certain targets, notably VxWorks 653,
15123 the secondary stack is allocated by carving off a fixed ratio chunk of the
15124 primary task stack. The -D option is used to define the
15125 size of the environment task's secondary stack.
15128 @geindex -e (gnatbind)
15135 Output complete list of elaboration-order dependencies.
15138 @geindex -E (gnatbind)
15145 Store tracebacks in exception occurrences when the target supports it.
15147 See also the packages @cite{GNAT.Traceback} and
15148 @cite{GNAT.Traceback.Symbolic} for more information.
15149 Note that on x86 ports, you must not use @emph{-fomit-frame-pointer}
15153 @geindex -F (gnatbind)
15160 Force the checks of elaboration flags. @emph{gnatbind} does not normally
15161 generate checks of elaboration flags for the main executable, except when
15162 a Stand-Alone Library is used. However, there are cases when this cannot be
15163 detected by gnatbind. An example is importing an interface of a Stand-Alone
15164 Library through a pragma Import and only specifying through a linker switch
15165 this Stand-Alone Library. This switch is used to guarantee that elaboration
15166 flag checks are generated.
15169 @geindex -h (gnatbind)
15176 Output usage (help) information
15178 @geindex -H32 (gnatbind)
15182 Use 32-bit allocations for @cite{__gnat_malloc} (and thus for access types).
15183 For further details see @ref{124,,Dynamic Allocation Control}.
15185 @geindex -H64 (gnatbind)
15187 @geindex __gnat_malloc
15191 Use 64-bit allocations for @cite{__gnat_malloc} (and thus for access types).
15192 For further details see @ref{124,,Dynamic Allocation Control}.
15194 @geindex -I (gnatbind)
15198 Specify directory to be searched for source and ALI files.
15200 @geindex -I- (gnatbind)
15204 Do not look for sources in the current directory where @cite{gnatbind} was
15205 invoked, and do not look for ALI files in the directory containing the
15206 ALI file named in the @cite{gnatbind} command line.
15208 @geindex -l (gnatbind)
15212 Output chosen elaboration order.
15214 @geindex -L (gnatbind)
15216 @item @code{-L@emph{xxx}}
15218 Bind the units for library building. In this case the adainit and
15219 adafinal procedures (@ref{ba,,Binding with Non-Ada Main Programs})
15220 are renamed to @cite{xxx`init and `xxx`final. Implies -n. (:ref:`GNAT_and_Libraries}, for more details.)
15222 @geindex -M (gnatbind)
15224 @item @code{-M@emph{xyz}}
15226 Rename generated main program from main to xyz. This option is
15227 supported on cross environments only.
15229 @geindex -m (gnatbind)
15231 @item @code{-m@emph{n}}
15233 Limit number of detected errors or warnings to @cite{n}, where @cite{n} is
15234 in the range 1..999999. The default value if no switch is
15235 given is 9999. If the number of warnings reaches this limit, then a
15236 message is output and further warnings are suppressed, the bind
15237 continues in this case. If the number of errors reaches this
15238 limit, then a message is output and the bind is abandoned.
15239 A value of zero means that no limit is enforced. The equal
15242 @geindex -n (gnatbind)
15248 @geindex -nostdinc (gnatbind)
15250 @item @code{-nostdinc}
15252 Do not look for sources in the system default directory.
15254 @geindex -nostdlib (gnatbind)
15256 @item @code{-nostdlib}
15258 Do not look for library files in the system default directory.
15260 @geindex --RTS (gnatbind)
15262 @item @code{--RTS=@emph{rts-path}}
15264 Specifies the default location of the runtime library. Same meaning as the
15265 equivalent @emph{gnatmake} flag (@ref{df,,Switches for gnatmake}).
15267 @geindex -o (gnatbind)
15269 @item @code{-o @emph{file}}
15271 Name the output file @cite{file} (default is @code{b~`xxx}.adb`).
15272 Note that if this option is used, then linking must be done manually,
15273 gnatlink cannot be used.
15275 @geindex -O (gnatbind)
15277 @item @code{-O[=@emph{filename}]}
15279 Output object list (to standard output or to the named file).
15281 @geindex -p (gnatbind)
15285 Pessimistic (worst-case) elaboration order
15287 @geindex -P (gnatbind)
15291 Generate binder file suitable for CodePeer.
15293 @geindex -R (gnatbind)
15297 Output closure source list, which includes all non-run-time units that are
15298 included in the bind.
15300 @geindex -Ra (gnatbind)
15304 Like @emph{-R} but the list includes run-time units.
15306 @geindex -s (gnatbind)
15310 Require all source files to be present.
15312 @geindex -S (gnatbind)
15314 @item @code{-S@emph{xxx}}
15316 Specifies the value to be used when detecting uninitialized scalar
15317 objects with pragma Initialize_Scalars.
15318 The @cite{xxx} string specified with the switch is one of:
15324 @code{in} for an invalid value*.
15326 If zero is invalid for the discrete type in question,
15327 then the scalar value is set to all zero bits.
15328 For signed discrete types, the largest possible negative value of
15329 the underlying scalar is set (i.e. a one bit followed by all zero bits).
15330 For unsigned discrete types, the underlying scalar value is set to all
15331 one bits. For floating-point types, a NaN value is set
15332 (see body of package System.Scalar_Values for exact values).
15335 @code{lo} for low value.
15337 If zero is invalid for the discrete type in question,
15338 then the scalar value is set to all zero bits.
15339 For signed discrete types, the largest possible negative value of
15340 the underlying scalar is set (i.e. a one bit followed by all zero bits).
15341 For unsigned discrete types, the underlying scalar value is set to all
15342 zero bits. For floating-point, a small value is set
15343 (see body of package System.Scalar_Values for exact values).
15346 @code{hi} for high value.
15348 If zero is invalid for the discrete type in question,
15349 then the scalar value is set to all one bits.
15350 For signed discrete types, the largest possible positive value of
15351 the underlying scalar is set (i.e. a zero bit followed by all one bits).
15352 For unsigned discrete types, the underlying scalar value is set to all
15353 one bits. For floating-point, a large value is set
15354 (see body of package System.Scalar_Values for exact values).
15357 @cite{xx} for hex value (two hex digits).
15359 The underlying scalar is set to a value consisting of repeated bytes, whose
15360 value corresponds to the given value. For example if @code{BF} is given,
15361 then a 32-bit scalar value will be set to the bit patterm @code{16#BFBFBFBF#}.
15364 @geindex GNAT_INIT_SCALARS
15366 In addition, you can specify @emph{-Sev} to indicate that the value is
15367 to be set at run time. In this case, the program will look for an environment
15368 variable of the form @code{GNAT_INIT_SCALARS=@emph{yy}}, where @cite{yy} is one
15369 of @emph{in/lo/hi/`xx*` with the same meanings as above.
15370 If no environment variable is found, or if it does not have a valid value,
15371 then the default is *in} (invalid values).
15374 @geindex -static (gnatbind)
15379 @item @code{-static}
15381 Link against a static GNAT run time.
15383 @geindex -shared (gnatbind)
15385 @item @code{-shared}
15387 Link against a shared GNAT run time when available.
15389 @geindex -t (gnatbind)
15393 Tolerate time stamp and other consistency errors
15395 @geindex -T (gnatbind)
15397 @item @code{-T@emph{n}}
15399 Set the time slice value to @cite{n} milliseconds. If the system supports
15400 the specification of a specific time slice value, then the indicated value
15401 is used. If the system does not support specific time slice values, but
15402 does support some general notion of round-robin scheduling, then any
15403 nonzero value will activate round-robin scheduling.
15405 A value of zero is treated specially. It turns off time
15406 slicing, and in addition, indicates to the tasking run time that the
15407 semantics should match as closely as possible the Annex D
15408 requirements of the Ada RM, and in particular sets the default
15409 scheduling policy to @cite{FIFO_Within_Priorities}.
15411 @geindex -u (gnatbind)
15413 @item @code{-u@emph{n}}
15415 Enable dynamic stack usage, with @cite{n} results stored and displayed
15416 at program termination. A result is generated when a task
15417 terminates. Results that can't be stored are displayed on the fly, at
15418 task termination. This option is currently not supported on Itanium
15419 platforms. (See @ref{125,,Dynamic Stack Usage Analysis} for details.)
15421 @geindex -v (gnatbind)
15425 Verbose mode. Write error messages, header, summary output to
15428 @geindex -w (gnatbind)
15430 @item @code{-w@emph{x}}
15432 Warning mode; @cite{x} = s/e for suppress/treat as error
15434 @geindex -Wx (gnatbind)
15436 @item @code{-Wx@emph{e}}
15438 Override default wide character encoding for standard Text_IO files.
15440 @geindex -x (gnatbind)
15444 Exclude source files (check object consistency only).
15446 @geindex -Xnnn (gnatbind)
15448 @item @code{-X@emph{nnn}}
15450 Set default exit status value, normally 0 for POSIX compliance.
15452 @geindex -y (gnatbind)
15456 Enable leap seconds support in @cite{Ada.Calendar} and its children.
15458 @geindex -z (gnatbind)
15462 No main subprogram.
15465 You may obtain this listing of switches by running @cite{gnatbind} with
15469 * Consistency-Checking Modes::
15470 * Binder Error Message Control::
15471 * Elaboration Control::
15473 * Dynamic Allocation Control::
15474 * Binding with Non-Ada Main Programs::
15475 * Binding Programs with No Main Subprogram::
15479 @node Consistency-Checking Modes,Binder Error Message Control,,Switches for gnatbind
15480 @anchor{gnat_ugn/building_executable_programs_with_gnat consistency-checking-modes}@anchor{126}@anchor{gnat_ugn/building_executable_programs_with_gnat id34}@anchor{127}
15481 @subsubsection Consistency-Checking Modes
15484 As described earlier, by default @cite{gnatbind} checks
15485 that object files are consistent with one another and are consistent
15486 with any source files it can locate. The following switches control binder
15491 @geindex -s (gnatbind)
15499 Require source files to be present. In this mode, the binder must be
15500 able to locate all source files that are referenced, in order to check
15501 their consistency. In normal mode, if a source file cannot be located it
15502 is simply ignored. If you specify this switch, a missing source
15505 @geindex -Wx (gnatbind)
15507 @item @code{-Wx@emph{e}}
15509 Override default wide character encoding for standard Text_IO files.
15510 Normally the default wide character encoding method used for standard
15511 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
15512 the main source input (see description of switch
15513 @emph{-gnatWx} for the compiler). The
15514 use of this switch for the binder (which has the same set of
15515 possible arguments) overrides this default as specified.
15517 @geindex -x (gnatbind)
15521 Exclude source files. In this mode, the binder only checks that ALI
15522 files are consistent with one another. Source files are not accessed.
15523 The binder runs faster in this mode, and there is still a guarantee that
15524 the resulting program is self-consistent.
15525 If a source file has been edited since it was last compiled, and you
15526 specify this switch, the binder will not detect that the object
15527 file is out of date with respect to the source file. Note that this is the
15528 mode that is automatically used by @emph{gnatmake} because in this
15529 case the checking against sources has already been performed by
15530 @emph{gnatmake} in the course of compilation (i.e., before binding).
15533 @node Binder Error Message Control,Elaboration Control,Consistency-Checking Modes,Switches for gnatbind
15534 @anchor{gnat_ugn/building_executable_programs_with_gnat id35}@anchor{128}@anchor{gnat_ugn/building_executable_programs_with_gnat binder-error-message-control}@anchor{129}
15535 @subsubsection Binder Error Message Control
15538 The following switches provide control over the generation of error
15539 messages from the binder:
15543 @geindex -v (gnatbind)
15551 Verbose mode. In the normal mode, brief error messages are generated to
15552 @code{stderr}. If this switch is present, a header is written
15553 to @code{stdout} and any error messages are directed to @code{stdout}.
15554 All that is written to @code{stderr} is a brief summary message.
15556 @geindex -b (gnatbind)
15560 Generate brief error messages to @code{stderr} even if verbose mode is
15561 specified. This is relevant only when used with the
15564 @geindex -m (gnatbind)
15566 @item @code{-m@emph{n}}
15568 Limits the number of error messages to @cite{n}, a decimal integer in the
15569 range 1-999. The binder terminates immediately if this limit is reached.
15571 @geindex -M (gnatbind)
15573 @item @code{-M@emph{xxx}}
15575 Renames the generated main program from @cite{main} to @cite{xxx}.
15576 This is useful in the case of some cross-building environments, where
15577 the actual main program is separate from the one generated
15578 by @cite{gnatbind}.
15580 @geindex -ws (gnatbind)
15586 Suppress all warning messages.
15588 @geindex -we (gnatbind)
15592 Treat any warning messages as fatal errors.
15594 @geindex -t (gnatbind)
15596 @geindex Time stamp checks
15599 @geindex Binder consistency checks
15601 @geindex Consistency checks
15606 The binder performs a number of consistency checks including:
15612 Check that time stamps of a given source unit are consistent
15615 Check that checksums of a given source unit are consistent
15618 Check that consistent versions of @cite{GNAT} were used for compilation
15621 Check consistency of configuration pragmas as required
15624 Normally failure of such checks, in accordance with the consistency
15625 requirements of the Ada Reference Manual, causes error messages to be
15626 generated which abort the binder and prevent the output of a binder
15627 file and subsequent link to obtain an executable.
15629 The @emph{-t} switch converts these error messages
15630 into warnings, so that
15631 binding and linking can continue to completion even in the presence of such
15632 errors. The result may be a failed link (due to missing symbols), or a
15633 non-functional executable which has undefined semantics.
15637 This means that @emph{-t} should be used only in unusual situations,
15643 @node Elaboration Control,Output Control,Binder Error Message Control,Switches for gnatbind
15644 @anchor{gnat_ugn/building_executable_programs_with_gnat id36}@anchor{12a}@anchor{gnat_ugn/building_executable_programs_with_gnat elaboration-control}@anchor{12b}
15645 @subsubsection Elaboration Control
15648 The following switches provide additional control over the elaboration
15649 order. For full details see @ref{11,,Elaboration Order Handling in GNAT}.
15653 @geindex -p (gnatbind)
15661 Normally the binder attempts to choose an elaboration order that is
15662 likely to minimize the likelihood of an elaboration order error resulting
15663 in raising a @cite{Program_Error} exception. This switch reverses the
15664 action of the binder, and requests that it deliberately choose an order
15665 that is likely to maximize the likelihood of an elaboration error.
15666 This is useful in ensuring portability and avoiding dependence on
15667 accidental fortuitous elaboration ordering.
15669 Normally it only makes sense to use the @emph{-p}
15671 elaboration checking is used (@emph{-gnatE} switch used for compilation).
15672 This is because in the default static elaboration mode, all necessary
15673 @cite{Elaborate} and @cite{Elaborate_All} pragmas are implicitly inserted.
15674 These implicit pragmas are still respected by the binder in
15675 @emph{-p} mode, so a
15676 safe elaboration order is assured.
15678 Note that @emph{-p} is not intended for
15679 production use; it is more for debugging/experimental use.
15682 @node Output Control,Dynamic Allocation Control,Elaboration Control,Switches for gnatbind
15683 @anchor{gnat_ugn/building_executable_programs_with_gnat output-control}@anchor{12c}@anchor{gnat_ugn/building_executable_programs_with_gnat id37}@anchor{12d}
15684 @subsubsection Output Control
15687 The following switches allow additional control over the output
15688 generated by the binder.
15692 @geindex -c (gnatbind)
15700 Check only. Do not generate the binder output file. In this mode the
15701 binder performs all error checks but does not generate an output file.
15703 @geindex -e (gnatbind)
15707 Output complete list of elaboration-order dependencies, showing the
15708 reason for each dependency. This output can be rather extensive but may
15709 be useful in diagnosing problems with elaboration order. The output is
15710 written to @code{stdout}.
15712 @geindex -h (gnatbind)
15716 Output usage information. The output is written to @code{stdout}.
15718 @geindex -K (gnatbind)
15722 Output linker options to @code{stdout}. Includes library search paths,
15723 contents of pragmas Ident and Linker_Options, and libraries added
15724 by @cite{gnatbind}.
15726 @geindex -l (gnatbind)
15730 Output chosen elaboration order. The output is written to @code{stdout}.
15732 @geindex -O (gnatbind)
15736 Output full names of all the object files that must be linked to provide
15737 the Ada component of the program. The output is written to @code{stdout}.
15738 This list includes the files explicitly supplied and referenced by the user
15739 as well as implicitly referenced run-time unit files. The latter are
15740 omitted if the corresponding units reside in shared libraries. The
15741 directory names for the run-time units depend on the system configuration.
15743 @geindex -o (gnatbind)
15745 @item @code{-o @emph{file}}
15747 Set name of output file to @cite{file} instead of the normal
15748 @code{b~`mainprog}.adb` default. Note that @cite{file} denote the Ada
15749 binder generated body filename.
15750 Note that if this option is used, then linking must be done manually.
15751 It is not possible to use gnatlink in this case, since it cannot locate
15754 @geindex -r (gnatbind)
15758 Generate list of @cite{pragma Restrictions} that could be applied to
15759 the current unit. This is useful for code audit purposes, and also may
15760 be used to improve code generation in some cases.
15763 @node Dynamic Allocation Control,Binding with Non-Ada Main Programs,Output Control,Switches for gnatbind
15764 @anchor{gnat_ugn/building_executable_programs_with_gnat dynamic-allocation-control}@anchor{124}@anchor{gnat_ugn/building_executable_programs_with_gnat id38}@anchor{12e}
15765 @subsubsection Dynamic Allocation Control
15768 The heap control switches -- @emph{-H32} and @emph{-H64} --
15769 determine whether dynamic allocation uses 32-bit or 64-bit memory.
15770 They only affect compiler-generated allocations via @cite{__gnat_malloc};
15771 explicit calls to @cite{malloc} and related functions from the C
15772 run-time library are unaffected.
15779 Allocate memory on 32-bit heap
15783 Allocate memory on 64-bit heap. This is the default
15784 unless explicitly overridden by a @cite{'Size} clause on the access type.
15787 These switches are only effective on VMS platforms.
15789 @node Binding with Non-Ada Main Programs,Binding Programs with No Main Subprogram,Dynamic Allocation Control,Switches for gnatbind
15790 @anchor{gnat_ugn/building_executable_programs_with_gnat binding-with-non-ada-main-programs}@anchor{ba}@anchor{gnat_ugn/building_executable_programs_with_gnat id39}@anchor{12f}
15791 @subsubsection Binding with Non-Ada Main Programs
15794 The description so far has assumed that the main
15795 program is in Ada, and that the task of the binder is to generate a
15796 corresponding function @cite{main} that invokes this Ada main
15797 program. GNAT also supports the building of executable programs where
15798 the main program is not in Ada, but some of the called routines are
15799 written in Ada and compiled using GNAT (@ref{46,,Mixed Language Programming}).
15800 The following switch is used in this situation:
15804 @geindex -n (gnatbind)
15812 No main program. The main program is not in Ada.
15815 In this case, most of the functions of the binder are still required,
15816 but instead of generating a main program, the binder generates a file
15817 containing the following callable routines:
15826 @item @emph{adainit}
15828 You must call this routine to initialize the Ada part of the program by
15829 calling the necessary elaboration routines. A call to @cite{adainit} is
15830 required before the first call to an Ada subprogram.
15832 Note that it is assumed that the basic execution environment must be setup
15833 to be appropriate for Ada execution at the point where the first Ada
15834 subprogram is called. In particular, if the Ada code will do any
15835 floating-point operations, then the FPU must be setup in an appropriate
15836 manner. For the case of the x86, for example, full precision mode is
15837 required. The procedure GNAT.Float_Control.Reset may be used to ensure
15838 that the FPU is in the right state.
15846 @item @emph{adafinal}
15848 You must call this routine to perform any library-level finalization
15849 required by the Ada subprograms. A call to @cite{adafinal} is required
15850 after the last call to an Ada subprogram, and before the program
15855 @geindex -n (gnatbind)
15858 @geindex multiple input files
15860 If the @emph{-n} switch
15861 is given, more than one ALI file may appear on
15862 the command line for @cite{gnatbind}. The normal @emph{closure}
15863 calculation is performed for each of the specified units. Calculating
15864 the closure means finding out the set of units involved by tracing
15865 @emph{with} references. The reason it is necessary to be able to
15866 specify more than one ALI file is that a given program may invoke two or
15867 more quite separate groups of Ada units.
15869 The binder takes the name of its output file from the last specified ALI
15870 file, unless overridden by the use of the @emph{-o file}.
15872 @geindex -o (gnatbind)
15874 The output is an Ada unit in source form that can be compiled with GNAT.
15875 This compilation occurs automatically as part of the @emph{gnatlink}
15878 Currently the GNAT run time requires a FPU using 80 bits mode
15879 precision. Under targets where this is not the default it is required to
15880 call GNAT.Float_Control.Reset before using floating point numbers (this
15881 include float computation, float input and output) in the Ada code. A
15882 side effect is that this could be the wrong mode for the foreign code
15883 where floating point computation could be broken after this call.
15885 @node Binding Programs with No Main Subprogram,,Binding with Non-Ada Main Programs,Switches for gnatbind
15886 @anchor{gnat_ugn/building_executable_programs_with_gnat binding-programs-with-no-main-subprogram}@anchor{130}@anchor{gnat_ugn/building_executable_programs_with_gnat id40}@anchor{131}
15887 @subsubsection Binding Programs with No Main Subprogram
15890 It is possible to have an Ada program which does not have a main
15891 subprogram. This program will call the elaboration routines of all the
15892 packages, then the finalization routines.
15894 The following switch is used to bind programs organized in this manner:
15898 @geindex -z (gnatbind)
15906 Normally the binder checks that the unit name given on the command line
15907 corresponds to a suitable main subprogram. When this switch is used,
15908 a list of ALI files can be given, and the execution of the program
15909 consists of elaboration of these units in an appropriate order. Note
15910 that the default wide character encoding method for standard Text_IO
15911 files is always set to Brackets if this switch is set (you can use
15913 @emph{-Wx} to override this default).
15916 @node Command-Line Access,Search Paths for gnatbind,Switches for gnatbind,Binding with gnatbind
15917 @anchor{gnat_ugn/building_executable_programs_with_gnat id41}@anchor{132}@anchor{gnat_ugn/building_executable_programs_with_gnat command-line-access}@anchor{133}
15918 @subsection Command-Line Access
15921 The package @cite{Ada.Command_Line} provides access to the command-line
15922 arguments and program name. In order for this interface to operate
15923 correctly, the two variables
15934 are declared in one of the GNAT library routines. These variables must
15935 be set from the actual @cite{argc} and @cite{argv} values passed to the
15936 main program. With no @emph{n} present, @cite{gnatbind}
15937 generates the C main program to automatically set these variables.
15938 If the @emph{n} switch is used, there is no automatic way to
15939 set these variables. If they are not set, the procedures in
15940 @cite{Ada.Command_Line} will not be available, and any attempt to use
15941 them will raise @cite{Constraint_Error}. If command line access is
15942 required, your main program must set @cite{gnat_argc} and
15943 @cite{gnat_argv} from the @cite{argc} and @cite{argv} values passed to
15946 @node Search Paths for gnatbind,Examples of gnatbind Usage,Command-Line Access,Binding with gnatbind
15947 @anchor{gnat_ugn/building_executable_programs_with_gnat search-paths-for-gnatbind}@anchor{91}@anchor{gnat_ugn/building_executable_programs_with_gnat id42}@anchor{134}
15948 @subsection Search Paths for @cite{gnatbind}
15951 The binder takes the name of an ALI file as its argument and needs to
15952 locate source files as well as other ALI files to verify object consistency.
15954 For source files, it follows exactly the same search rules as @emph{gcc}
15955 (see @ref{8e,,Search Paths and the Run-Time Library (RTL)}). For ALI files the
15956 directories searched are:
15962 The directory containing the ALI file named in the command line, unless
15963 the switch @emph{-I-} is specified.
15966 All directories specified by @emph{-I}
15967 switches on the @cite{gnatbind}
15968 command line, in the order given.
15970 @geindex ADA_PRJ_OBJECTS_FILE
15973 Each of the directories listed in the text file whose name is given
15975 @geindex ADA_PRJ_OBJECTS_FILE
15976 @geindex environment variable; ADA_PRJ_OBJECTS_FILE
15977 @code{ADA_PRJ_OBJECTS_FILE} environment variable.
15979 @geindex ADA_PRJ_OBJECTS_FILE
15980 @geindex environment variable; ADA_PRJ_OBJECTS_FILE
15981 @code{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the gnat
15982 driver when project files are used. It should not normally be set
15985 @geindex ADA_OBJECTS_PATH
15988 Each of the directories listed in the value of the
15989 @geindex ADA_OBJECTS_PATH
15990 @geindex environment variable; ADA_OBJECTS_PATH
15991 @code{ADA_OBJECTS_PATH} environment variable.
15992 Construct this value
15995 @geindex environment variable; PATH
15996 @code{PATH} environment variable: a list of directory
15997 names separated by colons (semicolons when working with the NT version
16001 The content of the @code{ada_object_path} file which is part of the GNAT
16002 installation tree and is used to store standard libraries such as the
16003 GNAT Run Time Library (RTL) unless the switch @emph{-nostdlib} is
16004 specified. See @ref{8b,,Installing a library}
16007 @geindex -I (gnatbind)
16009 @geindex -aI (gnatbind)
16011 @geindex -aO (gnatbind)
16013 In the binder the switch @emph{-I}
16014 is used to specify both source and
16015 library file paths. Use @emph{-aI}
16016 instead if you want to specify
16017 source paths only, and @emph{-aO}
16018 if you want to specify library paths
16019 only. This means that for the binder
16020 @code{-I@emph{dir}} is equivalent to
16021 @code{-aI@emph{dir}}
16022 @code{-aO`@emph{dir}}.
16023 The binder generates the bind file (a C language source file) in the
16024 current working directory.
16030 @geindex Interfaces
16034 The packages @cite{Ada}, @cite{System}, and @cite{Interfaces} and their
16035 children make up the GNAT Run-Time Library, together with the package
16036 GNAT and its children, which contain a set of useful additional
16037 library functions provided by GNAT. The sources for these units are
16038 needed by the compiler and are kept together in one directory. The ALI
16039 files and object files generated by compiling the RTL are needed by the
16040 binder and the linker and are kept together in one directory, typically
16041 different from the directory containing the sources. In a normal
16042 installation, you need not specify these directory names when compiling
16043 or binding. Either the environment variables or the built-in defaults
16044 cause these files to be found.
16046 Besides simplifying access to the RTL, a major use of search paths is
16047 in compiling sources from multiple directories. This can make
16048 development environments much more flexible.
16050 @node Examples of gnatbind Usage,,Search Paths for gnatbind,Binding with gnatbind
16051 @anchor{gnat_ugn/building_executable_programs_with_gnat examples-of-gnatbind-usage}@anchor{135}@anchor{gnat_ugn/building_executable_programs_with_gnat id43}@anchor{136}
16052 @subsection Examples of @cite{gnatbind} Usage
16055 Here are some examples of @cite{gnatbind} invovations:
16063 The main program @cite{Hello} (source program in @code{hello.adb}) is
16064 bound using the standard switch settings. The generated main program is
16065 @code{b~hello.adb}. This is the normal, default use of the binder.
16068 gnatbind hello -o mainprog.adb
16071 The main program @cite{Hello} (source program in @code{hello.adb}) is
16072 bound using the standard switch settings. The generated main program is
16073 @code{mainprog.adb} with the associated spec in
16074 @code{mainprog.ads}. Note that you must specify the body here not the
16075 spec. Note that if this option is used, then linking must be done manually,
16076 since gnatlink will not be able to find the generated file.
16079 @node Linking with gnatlink,Using the GNU make Utility,Binding with gnatbind,Building Executable Programs with GNAT
16080 @anchor{gnat_ugn/building_executable_programs_with_gnat id44}@anchor{137}@anchor{gnat_ugn/building_executable_programs_with_gnat linking-with-gnatlink}@anchor{20}
16081 @section Linking with @emph{gnatlink}
16084 @c index: ! gnatlink
16086 This chapter discusses @emph{gnatlink}, a tool that links
16087 an Ada program and builds an executable file. This utility
16088 invokes the system linker (via the @emph{gcc} command)
16089 with a correct list of object files and library references.
16090 @emph{gnatlink} automatically determines the list of files and
16091 references for the Ada part of a program. It uses the binder file
16092 generated by the @emph{gnatbind} to determine this list.
16094 Note: to invoke @cite{gnatlink} with a project file, use the @cite{gnat}
16095 driver (see @ref{11f,,The GNAT Driver and Project Files}).
16098 * Running gnatlink::
16099 * Switches for gnatlink::
16103 @node Running gnatlink,Switches for gnatlink,,Linking with gnatlink
16104 @anchor{gnat_ugn/building_executable_programs_with_gnat id45}@anchor{138}@anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatlink}@anchor{139}
16105 @subsection Running @emph{gnatlink}
16108 The form of the @emph{gnatlink} command is
16111 $ gnatlink [`switches`] `mainprog`[.ali]
16112 [`non-Ada objects`] [`linker options`]
16115 The arguments of @emph{gnatlink} (switches, main @code{ALI} file,
16117 or linker options) may be in any order, provided that no non-Ada object may
16118 be mistaken for a main @code{ALI} file.
16119 Any file name @code{F} without the @code{.ali}
16120 extension will be taken as the main @code{ALI} file if a file exists
16121 whose name is the concatenation of @code{F} and @code{.ali}.
16123 @code{mainprog.ali} references the ALI file of the main program.
16124 The @code{.ali} extension of this file can be omitted. From this
16125 reference, @emph{gnatlink} locates the corresponding binder file
16126 @code{b~mainprog.adb} and, using the information in this file along
16127 with the list of non-Ada objects and linker options, constructs a
16128 linker command file to create the executable.
16130 The arguments other than the @emph{gnatlink} switches and the main
16131 @code{ALI} file are passed to the linker uninterpreted.
16132 They typically include the names of
16133 object files for units written in other languages than Ada and any library
16134 references required to resolve references in any of these foreign language
16135 units, or in @cite{Import} pragmas in any Ada units.
16137 @cite{linker options} is an optional list of linker specific
16139 The default linker called by gnatlink is @emph{gcc} which in
16140 turn calls the appropriate system linker.
16142 One useful option for the linker is @emph{-s}: it reduces the size of the
16143 executable by removing all symbol table and relocation information from the
16146 Standard options for the linker such as @emph{-lmy_lib} or
16147 @emph{-Ldir} can be added as is.
16148 For options that are not recognized by
16149 @emph{gcc} as linker options, use the @emph{gcc} switches
16150 @emph{-Xlinker} or @emph{-Wl,}.
16152 Refer to the GCC documentation for
16155 Here is an example showing how to generate a linker map:
16158 $ gnatlink my_prog -Wl,-Map,MAPFILE
16161 Using @cite{linker options} it is possible to set the program stack and
16163 See @ref{13a,,Setting Stack Size from gnatlink} and
16164 @ref{13b,,Setting Heap Size from gnatlink}.
16166 @emph{gnatlink} determines the list of objects required by the Ada
16167 program and prepends them to the list of objects passed to the linker.
16168 @emph{gnatlink} also gathers any arguments set by the use of
16169 @cite{pragma Linker_Options} and adds them to the list of arguments
16170 presented to the linker.
16172 @node Switches for gnatlink,,Running gnatlink,Linking with gnatlink
16173 @anchor{gnat_ugn/building_executable_programs_with_gnat id46}@anchor{13c}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatlink}@anchor{13d}
16174 @subsection Switches for @emph{gnatlink}
16177 The following switches are available with the @emph{gnatlink} utility:
16179 @geindex --version (gnatlink)
16184 @item @code{--version}
16186 Display Copyright and version, then exit disregarding all other options.
16189 @geindex --help (gnatlink)
16194 @item @code{--help}
16196 If @emph{--version} was not used, display usage, then exit disregarding
16200 @geindex Command line length
16202 @geindex -f (gnatlink)
16209 On some targets, the command line length is limited, and @emph{gnatlink}
16210 will generate a separate file for the linker if the list of object files
16212 The @emph{-f} switch forces this file
16213 to be generated even if
16214 the limit is not exceeded. This is useful in some cases to deal with
16215 special situations where the command line length is exceeded.
16218 @geindex Debugging information
16221 @geindex -g (gnatlink)
16228 The option to include debugging information causes the Ada bind file (in
16229 other words, @code{b~mainprog.adb}) to be compiled with @emph{-g}.
16230 In addition, the binder does not delete the @code{b~mainprog.adb},
16231 @code{b~mainprog.o} and @code{b~mainprog.ali} files.
16232 Without @emph{-g}, the binder removes these files by default.
16235 @geindex -n (gnatlink)
16242 Do not compile the file generated by the binder. This may be used when
16243 a link is rerun with different options, but there is no need to recompile
16247 @geindex -v (gnatlink)
16254 Verbose mode. Causes additional information to be output, including a full
16255 list of the included object files.
16256 This switch option is most useful when you want
16257 to see what set of object files are being used in the link step.
16260 @geindex -v -v (gnatlink)
16267 Very verbose mode. Requests that the compiler operate in verbose mode when
16268 it compiles the binder file, and that the system linker run in verbose mode.
16271 @geindex -o (gnatlink)
16276 @item @code{-o @emph{exec-name}}
16278 @cite{exec-name} specifies an alternate name for the generated
16279 executable program. If this switch is omitted, the executable has the same
16280 name as the main unit. For example, @cite{gnatlink try.ali} creates
16281 an executable called @code{try}.
16284 @geindex -b (gnatlink)
16289 @item @code{-b @emph{target}}
16291 Compile your program to run on @cite{target}, which is the name of a
16292 system configuration. You must have a GNAT cross-compiler built if
16293 @cite{target} is not the same as your host system.
16296 @geindex -B (gnatlink)
16301 @item @code{-B@emph{dir}}
16303 Load compiler executables (for example, @cite{gnat1}, the Ada compiler)
16304 from @cite{dir} instead of the default location. Only use this switch
16305 when multiple versions of the GNAT compiler are available.
16306 See the @cite{Directory Options} section in @cite{The_GNU_Compiler_Collection}
16307 for further details. You would normally use the @emph{-b} or
16308 @emph{-V} switch instead.
16311 @geindex -M (gnatlink)
16318 When linking an executable, create a map file. The name of the map file
16319 has the same name as the executable with extension ".map".
16322 @geindex -M= (gnatlink)
16327 @item @code{-M=@emph{mapfile}}
16329 When linking an executable, create a map file. The name of the map file is
16333 @geindex --GCC=compiler_name (gnatlink)
16338 @item @code{--GCC=@emph{compiler_name}}
16340 Program used for compiling the binder file. The default is
16341 @code{gcc}. You need to use quotes around @cite{compiler_name} if
16342 @cite{compiler_name} contains spaces or other separator characters.
16343 As an example @code{--GCC="foo -x -y"} will instruct @emph{gnatlink} to
16344 use @code{foo -x -y} as your compiler. Note that switch @code{-c} is always
16345 inserted after your command name. Thus in the above example the compiler
16346 command that will be used by @emph{gnatlink} will be @code{foo -c -x -y}.
16347 A limitation of this syntax is that the name and path name of the executable
16348 itself must not include any embedded spaces. If the compiler executable is
16349 different from the default one (gcc or <prefix>-gcc), then the back-end
16350 switches in the ALI file are not used to compile the binder generated source.
16351 For example, this is the case with @code{--GCC="foo -x -y"}. But the back end
16352 switches will be used for @code{--GCC="gcc -gnatv"}. If several
16353 @code{--GCC=compiler_name} are used, only the last @cite{compiler_name}
16354 is taken into account. However, all the additional switches are also taken
16355 into account. Thus,
16356 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
16357 @code{--GCC="bar -x -y -z -t"}.
16360 @geindex --LINK= (gnatlink)
16365 @item @code{--LINK=@emph{name}}
16367 @cite{name} is the name of the linker to be invoked. This is especially
16368 useful in mixed language programs since languages such as C++ require
16369 their own linker to be used. When this switch is omitted, the default
16370 name for the linker is @emph{gcc}. When this switch is used, the
16371 specified linker is called instead of @emph{gcc} with exactly the same
16372 parameters that would have been passed to @emph{gcc} so if the desired
16373 linker requires different parameters it is necessary to use a wrapper
16374 script that massages the parameters before invoking the real linker. It
16375 may be useful to control the exact invocation by using the verbose
16379 @node Using the GNU make Utility,,Linking with gnatlink,Building Executable Programs with GNAT
16380 @anchor{gnat_ugn/building_executable_programs_with_gnat id47}@anchor{13e}@anchor{gnat_ugn/building_executable_programs_with_gnat using-the-gnu-make-utility}@anchor{21}
16381 @section Using the GNU @cite{make} Utility
16384 @geindex make (GNU)
16387 This chapter offers some examples of makefiles that solve specific
16388 problems. It does not explain how to write a makefile, nor does it try to replace the
16389 @emph{gnatmake} utility (@ref{1d,,Building with gnatmake}).
16391 All the examples in this section are specific to the GNU version of
16392 make. Although @emph{make} is a standard utility, and the basic language
16393 is the same, these examples use some advanced features found only in
16397 * Using gnatmake in a Makefile::
16398 * Automatically Creating a List of Directories::
16399 * Generating the Command Line Switches::
16400 * Overcoming Command Line Length Limits::
16404 @node Using gnatmake in a Makefile,Automatically Creating a List of Directories,,Using the GNU make Utility
16405 @anchor{gnat_ugn/building_executable_programs_with_gnat using-gnatmake-in-a-makefile}@anchor{13f}@anchor{gnat_ugn/building_executable_programs_with_gnat id48}@anchor{140}
16406 @subsection Using gnatmake in a Makefile
16409 @c index makefile (GNU make)
16411 Complex project organizations can be handled in a very powerful way by
16412 using GNU make combined with gnatmake. For instance, here is a Makefile
16413 which allows you to build each subsystem of a big project into a separate
16414 shared library. Such a makefile allows you to significantly reduce the link
16415 time of very big applications while maintaining full coherence at
16416 each step of the build process.
16418 The list of dependencies are handled automatically by
16419 @emph{gnatmake}. The Makefile is simply used to call gnatmake in each of
16420 the appropriate directories.
16422 Note that you should also read the example on how to automatically
16423 create the list of directories
16424 (@ref{141,,Automatically Creating a List of Directories})
16425 which might help you in case your project has a lot of subdirectories.
16428 ## This Makefile is intended to be used with the following directory
16430 ## - The sources are split into a series of csc (computer software components)
16431 ## Each of these csc is put in its own directory.
16432 ## Their name are referenced by the directory names.
16433 ## They will be compiled into shared library (although this would also work
16434 ## with static libraries
16435 ## - The main program (and possibly other packages that do not belong to any
16436 ## csc is put in the top level directory (where the Makefile is).
16437 ## toplevel_dir __ first_csc (sources) __ lib (will contain the library)
16438 ## \\_ second_csc (sources) __ lib (will contain the library)
16440 ## Although this Makefile is build for shared library, it is easy to modify
16441 ## to build partial link objects instead (modify the lines with -shared and
16444 ## With this makefile, you can change any file in the system or add any new
16445 ## file, and everything will be recompiled correctly (only the relevant shared
16446 ## objects will be recompiled, and the main program will be re-linked).
16448 # The list of computer software component for your project. This might be
16449 # generated automatically.
16452 # Name of the main program (no extension)
16455 # If we need to build objects with -fPIC, uncomment the following line
16458 # The following variable should give the directory containing libgnat.so
16459 # You can get this directory through 'gnatls -v'. This is usually the last
16460 # directory in the Object_Path.
16463 # The directories for the libraries
16464 # (This macro expands the list of CSC to the list of shared libraries, you
16465 # could simply use the expanded form:
16466 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
16467 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
16469 $@{MAIN@}: objects $@{LIB_DIR@}
16470 gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
16471 gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
16474 # recompile the sources
16475 gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
16477 # Note: In a future version of GNAT, the following commands will be simplified
16478 # by a new tool, gnatmlib
16480 mkdir -p $@{dir $@@ @}
16481 cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
16482 cd $@{dir $@@ @} && cp -f ../*.ali .
16484 # The dependencies for the modules
16485 # Note that we have to force the expansion of *.o, since in some cases
16486 # make won't be able to do it itself.
16487 aa/lib/libaa.so: $@{wildcard aa/*.o@}
16488 bb/lib/libbb.so: $@{wildcard bb/*.o@}
16489 cc/lib/libcc.so: $@{wildcard cc/*.o@}
16491 # Make sure all of the shared libraries are in the path before starting the
16494 LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
16497 $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
16498 $@{RM@} $@{CSC_LIST:%=%/*.ali@}
16499 $@{RM@} $@{CSC_LIST:%=%/*.o@}
16500 $@{RM@} *.o *.ali $@{MAIN@}
16503 @node Automatically Creating a List of Directories,Generating the Command Line Switches,Using gnatmake in a Makefile,Using the GNU make Utility
16504 @anchor{gnat_ugn/building_executable_programs_with_gnat automatically-creating-a-list-of-directories}@anchor{141}@anchor{gnat_ugn/building_executable_programs_with_gnat id49}@anchor{142}
16505 @subsection Automatically Creating a List of Directories
16508 In most makefiles, you will have to specify a list of directories, and
16509 store it in a variable. For small projects, it is often easier to
16510 specify each of them by hand, since you then have full control over what
16511 is the proper order for these directories, which ones should be
16514 However, in larger projects, which might involve hundreds of
16515 subdirectories, it might be more convenient to generate this list
16518 The example below presents two methods. The first one, although less
16519 general, gives you more control over the list. It involves wildcard
16520 characters, that are automatically expanded by @emph{make}. Its
16521 shortcoming is that you need to explicitly specify some of the
16522 organization of your project, such as for instance the directory tree
16523 depth, whether some directories are found in a separate tree, etc.
16525 The second method is the most general one. It requires an external
16526 program, called @emph{find}, which is standard on all Unix systems. All
16527 the directories found under a given root directory will be added to the
16531 # The examples below are based on the following directory hierarchy:
16532 # All the directories can contain any number of files
16533 # ROOT_DIRECTORY -> a -> aa -> aaa
16536 # -> b -> ba -> baa
16539 # This Makefile creates a variable called DIRS, that can be reused any time
16540 # you need this list (see the other examples in this section)
16542 # The root of your project's directory hierarchy
16546 # First method: specify explicitly the list of directories
16547 # This allows you to specify any subset of all the directories you need.
16550 DIRS := a/aa/ a/ab/ b/ba/
16553 # Second method: use wildcards
16554 # Note that the argument(s) to wildcard below should end with a '/'.
16555 # Since wildcards also return file names, we have to filter them out
16556 # to avoid duplicate directory names.
16557 # We thus use make's `dir` and `sort` functions.
16558 # It sets DIRs to the following value (note that the directories aaa and baa
16559 # are not given, unless you change the arguments to wildcard).
16560 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
16563 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
16564 $@{ROOT_DIRECTORY@}/*/*/@}@}@}
16567 # Third method: use an external program
16568 # This command is much faster if run on local disks, avoiding NFS slowdowns.
16569 # This is the most complete command: it sets DIRs to the following value:
16570 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
16573 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
16576 @node Generating the Command Line Switches,Overcoming Command Line Length Limits,Automatically Creating a List of Directories,Using the GNU make Utility
16577 @anchor{gnat_ugn/building_executable_programs_with_gnat id50}@anchor{143}@anchor{gnat_ugn/building_executable_programs_with_gnat generating-the-command-line-switches}@anchor{144}
16578 @subsection Generating the Command Line Switches
16581 Once you have created the list of directories as explained in the
16582 previous section (@ref{141,,Automatically Creating a List of Directories}),
16583 you can easily generate the command line arguments to pass to gnatmake.
16585 For the sake of completeness, this example assumes that the source path
16586 is not the same as the object path, and that you have two separate lists
16590 # see "Automatically creating a list of directories" to create
16595 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
16596 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
16599 gnatmake $@{GNATMAKE_SWITCHES@} main_unit
16602 @node Overcoming Command Line Length Limits,,Generating the Command Line Switches,Using the GNU make Utility
16603 @anchor{gnat_ugn/building_executable_programs_with_gnat overcoming-command-line-length-limits}@anchor{145}@anchor{gnat_ugn/building_executable_programs_with_gnat id51}@anchor{146}
16604 @subsection Overcoming Command Line Length Limits
16607 One problem that might be encountered on big projects is that many
16608 operating systems limit the length of the command line. It is thus hard to give
16609 gnatmake the list of source and object directories.
16611 This example shows how you can set up environment variables, which will
16612 make @emph{gnatmake} behave exactly as if the directories had been
16613 specified on the command line, but have a much higher length limit (or
16614 even none on most systems).
16616 It assumes that you have created a list of directories in your Makefile,
16617 using one of the methods presented in
16618 @ref{141,,Automatically Creating a List of Directories}.
16619 For the sake of completeness, we assume that the object
16620 path (where the ALI files are found) is different from the sources patch.
16622 Note a small trick in the Makefile below: for efficiency reasons, we
16623 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
16624 expanded immediately by @cite{make}. This way we overcome the standard
16625 make behavior which is to expand the variables only when they are
16628 On Windows, if you are using the standard Windows command shell, you must
16629 replace colons with semicolons in the assignments to these variables.
16632 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
16633 # This is the same thing as putting the -I arguments on the command line.
16634 # (the equivalent of using -aI on the command line would be to define
16635 # only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
16636 # You can of course have different values for these variables.
16638 # Note also that we need to keep the previous values of these variables, since
16639 # they might have been set before running 'make' to specify where the GNAT
16640 # library is installed.
16642 # see "Automatically creating a list of directories" to create these
16648 space:=$@{empty@} $@{empty@}
16649 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
16650 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
16651 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
16652 ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
16653 export ADA_INCLUDE_PATH
16654 export ADA_OBJECTS_PATH
16660 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
16662 @node GNAT Project Manager,Tools Supporting Project Files,Building Executable Programs with GNAT,Top
16663 @anchor{gnat_ugn/gnat_project_manager doc}@anchor{147}@anchor{gnat_ugn/gnat_project_manager gnat-project-manager}@anchor{b}@anchor{gnat_ugn/gnat_project_manager id1}@anchor{148}
16664 @chapter GNAT Project Manager
16669 * Building With Projects::
16670 * Organizing Projects into Subsystems::
16671 * Scenarios in Projects::
16672 * Library Projects::
16673 * Project Extension::
16674 * Aggregate Projects::
16675 * Aggregate Library Projects::
16676 * Project File Reference::
16680 @node Introduction,Building With Projects,,GNAT Project Manager
16681 @anchor{gnat_ugn/gnat_project_manager introduction}@anchor{149}@anchor{gnat_ugn/gnat_project_manager gnat-project-manager-introduction}@anchor{14a}
16682 @section Introduction
16685 This chapter describes GNAT's @emph{Project Manager}, a facility that allows
16686 you to manage complex builds involving a number of source files, directories,
16687 and options for different system configurations. In particular,
16688 project files allow you to specify:
16694 The directory or set of directories containing the source files, and/or the
16695 names of the specific source files themselves
16698 The directory in which the compiler's output
16699 (@code{ALI} files, object files, tree files, etc.) is to be placed
16702 The directory in which the executable programs are to be placed
16705 Switch settings for any of the project-enabled tools;
16706 you can apply these settings either globally or to individual compilation units.
16709 The source files containing the main subprogram(s) to be built
16712 The source programming language(s)
16715 Source file naming conventions; you can specify these either globally or for
16716 individual compilation units (see @ref{14b,,Naming Schemes}).
16719 Change any of the above settings depending on external values, thus enabling
16720 the reuse of the projects in various @strong{scenarios} (see @ref{14c,,Scenarios in Projects}).
16723 Automatically build libraries as part of the build process
16724 (see @ref{8a,,Library Projects}).
16727 Project files are written in a syntax close to that of Ada, using familiar
16728 notions such as packages, context clauses, declarations, default values,
16729 assignments, and inheritance (see @ref{14d,,Project File Reference}).
16731 Project files can be built hierarchically from other project files, simplifying
16732 complex system integration and project reuse (see @ref{14e,,Organizing Projects into Subsystems}).
16738 One project can import other projects containing needed source files.
16739 More generally, the Project Manager lets you structure large development
16740 efforts into hierarchical subsystems, where build decisions are delegated
16741 to the subsystem level, and thus different compilation environments
16742 (switch settings) used for different subsystems.
16745 You can organize GNAT projects in a hierarchy: a child project
16746 can extend a parent project, inheriting the parent's source files and
16747 optionally overriding any of them with alternative versions
16748 (see @ref{14f,,Project Extension}).
16751 Several tools support project files, generally in addition to specifying
16752 the information on the command line itself). They share common switches
16753 to control the loading of the project (in particular
16754 @code{-P@emph{projectfile}} and
16755 @code{-X@emph{vbl}=@emph{value}}).
16757 The Project Manager supports a wide range of development strategies,
16758 for systems of all sizes. Here are some typical practices that are
16765 Using a common set of source files and generating object files in different
16766 directories via different switch settings. It can be used for instance, for
16767 generating separate sets of object files for debugging and for production.
16770 Using a mostly-shared set of source files with different versions of
16771 some units or subunits. It can be used for instance, for grouping and hiding
16772 all OS dependencies in a small number of implementation units.
16775 Project files can be used to achieve some of the effects of a source
16776 versioning system (for example, defining separate projects for
16777 the different sets of sources that comprise different releases) but the
16778 Project Manager is independent of any source configuration management tool
16779 that might be used by the developers.
16781 The various sections below introduce the different concepts related to
16782 projects. Each section starts with examples and use cases, and then goes into
16783 the details of related project file capabilities.
16785 @node Building With Projects,Organizing Projects into Subsystems,Introduction,GNAT Project Manager
16786 @anchor{gnat_ugn/gnat_project_manager building-with-projects}@anchor{150}@anchor{gnat_ugn/gnat_project_manager id2}@anchor{151}
16787 @section Building With Projects
16790 In its simplest form, a unique project is used to build a single executable.
16791 This section concentrates on such a simple setup. Later sections will extend
16792 this basic model to more complex setups.
16794 The following concepts are the foundation of project files, and will be further
16795 detailed later in this documentation. They are summarized here as a reference.
16800 @item @strong{Project file}:
16802 A text file using an Ada-like syntax, generally using the @code{.gpr}
16803 extension. It defines build-related characteristics of an application.
16804 The characteristics include the list of sources, the location of those
16805 sources, the location for the generated object files, the name of
16806 the main program, and the options for the various tools involved in the
16809 @item @strong{Project attribute}:
16811 A specific project characteristic is defined by an attribute clause. Its
16812 value is a string or a sequence of strings. All settings in a project
16813 are defined through a list of predefined attributes with precise
16814 semantics. See @ref{152,,Attributes}.
16816 @item @strong{Package in a project}:
16818 Global attributes are defined at the top level of a project.
16819 Attributes affecting specific tools are grouped in a
16820 package whose name is related to tool's function. The most common
16821 packages are @cite{Builder}, @cite{Compiler}, @cite{Binder},
16822 and @cite{Linker}. See @ref{153,,Packages}.
16824 @item @strong{Project variables}:
16826 In addition to attributes, a project can use variables to store intermediate
16827 values and avoid duplication in complex expressions. It can be initialized
16828 with a value coming from the environment.
16829 A frequent use of variables is to define scenarios.
16830 See @ref{154,,External Values}, @ref{14c,,Scenarios in Projects}, and @ref{155,,Variables}.
16832 @item @strong{Source files} and @strong{source directories}:
16834 A source file is associated with a language through a naming convention. For
16835 instance, @cite{foo.c} is typically the name of a C source file;
16836 @cite{bar.ads} or @cite{bar.1.ada} are two common naming conventions for a
16837 file containing an Ada spec. A compilation unit is often composed of a main
16838 source file and potentially several auxiliary ones, such as header files in C.
16839 The naming conventions can be user defined @ref{14b,,Naming Schemes}, and will
16840 drive the builder to call the appropriate compiler for the given source file.
16841 Source files are searched for in the source directories associated with the
16842 project through the @strong{Source_Dirs} attribute. By default, all the files (in
16843 these source directories) following the naming conventions associated with the
16844 declared languages are considered to be part of the project. It is also
16845 possible to limit the list of source files using the @strong{Source_Files} or
16846 @strong{Source_List_File} attributes. Note that those last two attributes only
16847 accept basenames with no directory information.
16849 @item @strong{Object files} and @strong{object directory}:
16851 An object file is an intermediate file produced by the compiler from a
16852 compilation unit. It is used by post-compilation tools to produce
16853 final executables or libraries. Object files produced in the context of
16854 a given project are stored in a single directory that can be specified by the
16855 @strong{Object_Dir} attribute. In order to store objects in
16856 two or more object directories, the system must be split into
16857 distinct subsystems with their own project file.
16860 The following subsections introduce gradually all the attributes of interest
16861 for simple build needs. Here is the simple setup that will be used in the
16862 following examples.
16864 The Ada source files @code{pack.ads}, @code{pack.adb}, and @code{proc.adb} are in
16865 the @code{common/} directory. The file @code{proc.adb} contains an Ada main
16866 subprogram @cite{Proc} that @emph{with}s package @cite{Pack}. We want to compile
16867 these source files with the switch
16868 @emph{-O2}, and put the resulting files in
16869 the directory @code{obj/}.
16877 proc.ali, proc.o pack.ali, pack.o
16880 Our project is to be called @emph{Build}. The name of the
16881 file is the name of the project (case-insensitive) with the
16882 @code{.gpr} extension, therefore the project file name is @code{build.gpr}. This
16883 is not mandatory, but a warning is issued when this convention is not followed.
16885 This is a very simple example, and as stated above, a single project
16886 file is enough for it. We will thus create a new file, that for now
16887 should contain the following code:
16895 * Source Files and Directories::
16896 * Duplicate Sources in Projects::
16897 * Object and Exec Directory::
16898 * Main Subprograms::
16899 * Tools Options in Project Files::
16900 * Compiling with Project Files::
16901 * Executable File Names::
16902 * Avoid Duplication With Variables::
16905 * Distributed support::
16909 @node Source Files and Directories,Duplicate Sources in Projects,,Building With Projects
16910 @anchor{gnat_ugn/gnat_project_manager id3}@anchor{156}@anchor{gnat_ugn/gnat_project_manager source-files-and-directories}@anchor{157}
16911 @subsection Source Files and Directories
16914 When you create a new project, the first thing to describe is how to find the
16915 corresponding source files. These are the only settings that are needed by all
16916 the tools that will use this project (builder, compiler, binder and linker for
16917 the compilation, IDEs to edit the source files,...).
16919 @geindex Source directories (GNAT Project Manager)
16921 The first step is to declare the source directories, which are the directories
16922 to be searched to find source files. In the case of the example,
16923 the @code{common} directory is the only source directory.
16925 @geindex Source_Dirs (GNAT Project Manager)
16927 There are several ways of defining source directories:
16933 When the attribute @strong{Source_Dirs} is not used, a project contains a
16934 single source directory which is the one where the project file itself
16935 resides. In our example, if @code{build.gpr} is placed in the @code{common}
16936 directory, the project has the needed implicit source directory.
16939 The attribute @strong{Source_Dirs} can be set to a list of path names, one
16940 for each of the source directories. Such paths can either be absolute
16941 names (for instance @code{"/usr/local/common/"} on UNIX), or relative to the
16942 directory in which the project file resides (for instance "." if
16943 @code{build.gpr} is inside @code{common/}, or "common" if it is one level up).
16944 Each of the source directories must exist and be readable.
16946 @geindex portability of path names (GNAT Project Manager)
16948 The syntax for directories is platform specific. For portability, however,
16949 the project manager will always properly translate UNIX-like path names to
16950 the native format of the specific platform. For instance, when the same
16951 project file is to be used both on Unix and Windows, "/" should be used as
16952 the directory separator rather than "\".
16955 The attribute @strong{Source_Dirs} can automatically include subdirectories
16956 using a special syntax inspired by some UNIX shells. If any of the paths in
16957 the list ends with "@code{**}", then that path and all its subdirectories
16958 (recursively) are included in the list of source directories. For instance,
16959 @code{**} and @code{./**} represent the complete directory tree rooted at
16960 the directory in which the project file resides.
16962 @geindex Source directories (GNAT Project Manager)
16964 @geindex Excluded_Source_Dirs (GNAT Project Manager)
16966 When using that construct, it can sometimes be convenient to also use the
16967 attribute @strong{Excluded_Source_Dirs}, which is also a list of paths. Each entry
16968 specifies a directory whose immediate content, not including subdirs, is to
16969 be excluded. It is also possible to exclude a complete directory subtree
16970 using the "**" notation.
16972 @geindex Ignore_Source_Sub_Dirs (GNAT Project Manager)
16974 It is often desirable to remove, from the source directories, directory
16975 subtrees rooted at some subdirectories. An example is the subdirectories
16976 created by a Version Control System such as Subversion that creates directory
16977 subtrees rooted at subdirectories ".svn". To do that, attribute
16978 @strong{Ignore_Source_Sub_Dirs} can be used. It specifies the list of simple
16979 file names for the roots of these undesirable directory subtrees.
16981 @c code-block: ada-project
16983 @c for Source_Dirs use ("./**");
16984 @c for Ignore_Source_Sub_Dirs use (".svn");
16987 When applied to the simple example, and because we generally prefer to have
16988 the project file at the toplevel directory rather than mixed with the sources,
16989 we will create the following file
16991 @c code-block: ada-project
16994 @c project Build is
16995 @c for Source_Dirs use ("common"); -- <<<<
16998 Once source directories have been specified, one may need to indicate
16999 source files of interest. By default, all source files present in the source
17000 directories are considered by the project manager. When this is not desired,
17001 it is possible to specify the list of sources to consider explicitly.
17002 In such a case, only source file base names are indicated and not
17003 their absolute or relative path names. The project manager is in charge of
17004 locating the specified source files in the specified source directories.
17010 By default, the project manager searches for all source files of all
17011 specified languages in all the source directories.
17013 Since the project manager was initially developed for Ada environments, the
17014 default language is usually Ada and the above project file is complete: it
17015 defines without ambiguity the sources composing the project: that is to say,
17016 all the sources in subdirectory "common" for the default language (Ada) using
17017 the default naming convention.
17019 @geindex Languages (GNAT Project Manager)
17021 However, when compiling a multi-language application, or a pure C
17022 application, the project manager must be told which languages are of
17023 interest, which is done by setting the @strong{Languages} attribute to a list of
17024 strings, each of which is the name of a language.
17026 @geindex Naming scheme (GNAT Project Manager)
17028 Even when using only Ada, the default naming might not be suitable. Indeed,
17029 how does the project manager recognizes an "Ada file" from any other
17030 file? Project files can describe the naming scheme used for source files,
17031 and override the default (see @ref{14b,,Naming Schemes}). The default is the
17032 standard GNAT extension (@code{.adb} for bodies and @code{.ads} for
17033 specs), which is what is used in our example, explaining why no naming scheme
17034 is explicitly specified.
17035 See @ref{14b,,Naming Schemes}.
17037 @geindex Source_Files (GNAT Project Manager)
17040 @cite{Source_Files}.
17041 In some cases, source directories might contain files that should not be
17042 included in a project. One can specify the explicit list of file names to
17043 be considered through the @strong{Source_Files} attribute.
17044 When this attribute is defined, instead of looking at every file in the
17045 source directories, the project manager takes only those names into
17046 consideration reports errors if they cannot be found in the source
17047 directories or does not correspond to the naming scheme.
17050 For various reasons, it is sometimes useful to have a project with no
17051 sources (most of the time because the attributes defined in the project
17052 file will be reused in other projects, as explained in
17053 @ref{14e,,Organizing Projects into Subsystems}. To do this, the attribute
17054 @emph{Source_Files} is set to the empty list, i.e. @cite{()}. Alternatively,
17055 @emph{Source_Dirs} can be set to the empty list, with the same
17058 @geindex Source_List_File (GNAT Project Manager)
17061 @cite{Source_List_File}.
17062 If there is a great number of files, it might be more convenient to use
17063 the attribute @strong{Source_List_File}, which specifies the full path of a file.
17064 This file must contain a list of source file names (one per line, no
17065 directory information) that are searched as if they had been defined
17066 through @emph{Source_Files}. Such a file can easily be created through
17069 A warning is issued if both attributes @cite{Source_Files} and
17070 @cite{Source_List_File} are given explicit values. In this case, the
17071 attribute @cite{Source_Files} prevails.
17073 @geindex Excluded_Source_Files (GNAT Project Manager)
17075 @geindex Locally_Removed_Files (GNAT Project Manager)
17077 @geindex Excluded_Source_List_File (GNAT Project Manager)
17080 @cite{Excluded_Source_Files}.
17081 Specifying an explicit list of files is not always convenient.It might be
17082 more convenient to use the default search rules with specific exceptions.
17083 This can be done thanks to the attribute @strong{Excluded_Source_Files}
17084 (or its synonym @strong{Locally_Removed_Files}).
17085 Its value is the list of file names that should not be taken into account.
17086 This attribute is often used when extending a project,
17087 see @ref{14f,,Project Extension}. A similar attribute
17088 @strong{Excluded_Source_List_File} plays the same
17089 role but takes the name of file containing file names similarly to
17090 @cite{Source_List_File}.
17093 In most simple cases, such as the above example, the default source file search
17094 behavior provides the expected result, and we do not need to add anything after
17095 setting @cite{Source_Dirs}. The project manager automatically finds
17096 @code{pack.ads}, @code{pack.adb}, and @code{proc.adb} as source files of the
17099 Note that by default a warning is issued when a project has no sources attached
17100 to it and this is not explicitly indicated in the project file.
17102 @node Duplicate Sources in Projects,Object and Exec Directory,Source Files and Directories,Building With Projects
17103 @anchor{gnat_ugn/gnat_project_manager duplicate-sources-in-projects}@anchor{158}@anchor{gnat_ugn/gnat_project_manager id4}@anchor{159}
17104 @subsection Duplicate Sources in Projects
17107 If the order of the source directories is known statically, that is if
17108 @cite{"/**"} is not used in the string list @cite{Source_Dirs}, then there may
17109 be several files with the same name sitting in different directories of the
17110 project. In this case, only the file in the first directory is considered as a
17111 source of the project and the others are hidden. If @cite{"/**"} is used in the
17112 string list @cite{Source_Dirs}, it is an error to have several files with the
17113 same name in the same directory @cite{"/**"} subtree, since there would be an
17114 ambiguity as to which one should be used. However, two files with the same name
17115 may exist in two single directories or directory subtrees. In this case, the
17116 one in the first directory or directory subtree is a source of the project.
17118 If there are two sources in different directories of the same @cite{"/**"}
17119 subtree, one way to resolve the problem is to exclude the directory of the
17120 file that should not be used as a source of the project.
17122 @node Object and Exec Directory,Main Subprograms,Duplicate Sources in Projects,Building With Projects
17123 @anchor{gnat_ugn/gnat_project_manager object-and-exec-directory}@anchor{15a}@anchor{gnat_ugn/gnat_project_manager id5}@anchor{15b}
17124 @subsection Object and Exec Directory
17127 The next step when writing a project is to indicate where the compiler should
17128 put the object files. In fact, the compiler and other tools might create
17129 several different kind of files (for GNAT, there is the object file and the ALI
17130 file for instance). One of the important concepts in projects is that most
17131 tools may consider source directories as read-only and do not attempt to create
17132 new or temporary files there. Instead, all files are created in the object
17133 directory. It is of course not true for project-aware IDEs, whose purpose it is
17134 to create the source files.
17136 @geindex Object_Dir (GNAT Project Manager)
17138 The object directory is specified through the @strong{Object_Dir} attribute.
17139 Its value is the path to the object directory, either absolute or
17140 relative to the directory containing the project file. This
17141 directory must already exist and be readable and writable, although
17142 some tools have a switch to create the directory if needed (See
17143 the switch @cite{-p} for @emph{gprbuild}).
17145 If the attribute @cite{Object_Dir} is not specified, it defaults to
17146 the project directory, that is the directory containing the project file.
17148 For our example, we can specify the object dir in this way:
17150 @c code-block: ada-project
17152 @c project Build is
17153 @c for Source_Dirs use ("common");
17154 @c for Object_Dir use "obj"; -- <<<<
17157 As mentioned earlier, there is a single object directory per project. As a
17158 result, if you have an existing system where the object files are spread across
17159 several directories, you can either move all of them into the same directory if
17160 you want to build it with a single project file, or study the section on
17161 subsystems (see @ref{14e,,Organizing Projects into Subsystems}) to see how each
17162 separate object directory can be associated with one of the subsystems
17163 constituting the application.
17165 When the @emph{linker} is called, it usually creates an executable. By
17166 default, this executable is placed in the object directory of the project. It
17167 might be convenient to store it in its own directory.
17169 @geindex Exec_Dir (GNAT Project Manager)
17171 This can be done through the @cite{Exec_Dir} attribute, which, like
17172 @emph{Object_Dir} contains a single absolute or relative path and must point to
17173 an existing and writable directory, unless you ask the tool to create it on
17174 your behalf. When not specified, It defaults to the object directory and
17175 therefore to the project file's directory if neither @emph{Object_Dir} nor
17176 @emph{Exec_Dir} was specified.
17178 In the case of the example, let's place the executable in the root
17179 of the hierarchy, ie the same directory as @code{build.gpr}. Hence
17180 the project file is now
17182 @c code-block: ada-project
17184 @c project Build is
17185 @c for Source_Dirs use ("common");
17186 @c for Object_Dir use "obj";
17187 @c for Exec_Dir use "."; -- <<<<
17190 @node Main Subprograms,Tools Options in Project Files,Object and Exec Directory,Building With Projects
17191 @anchor{gnat_ugn/gnat_project_manager id6}@anchor{15c}@anchor{gnat_ugn/gnat_project_manager main-subprograms}@anchor{15d}
17192 @subsection Main Subprograms
17195 In the previous section, executables were mentioned. The project manager needs
17196 to be taught what they are. In a project file, an executable is indicated by
17197 pointing to the source file of a main subprogram. In C this is the file that
17198 contains the @cite{main} function, and in Ada the file that contains the main
17201 There can be any number of such main files within a given project, and thus
17202 several executables can be built in the context of a single project file. Of
17203 course, one given executable might not (and in fact will not) need all the
17204 source files referenced by the project. As opposed to other build environments
17205 such as @emph{makefile}, one does not need to specify the list of
17206 dependencies of each executable, the project-aware builder knows enough of the
17207 semantics of the languages to build and link only the necessary elements.
17209 @geindex Main (GNAT Project Manager)
17211 The list of main files is specified via the @strong{Main} attribute. It contains
17212 a list of file names (no directories). If a project defines this
17213 attribute, it is not necessary to identify main files on the
17214 command line when invoking a builder, and editors like
17215 @emph{GPS} will be able to create extra menus to spawn or debug the
17216 corresponding executables.
17218 @c code-block: ada-project
17220 @c project Build is
17221 @c for Source_Dirs use ("common");
17222 @c for Object_Dir use "obj";
17223 @c for Exec_Dir use ".";
17224 @c for Main use ("proc.adb"); -- <<<<
17227 If this attribute is defined in the project, then spawning the builder
17228 with a command such as
17234 automatically builds all the executables corresponding to the files
17235 listed in the @emph{Main} attribute. It is possible to specify one
17236 or more executables on the command line to build a subset of them.
17238 @node Tools Options in Project Files,Compiling with Project Files,Main Subprograms,Building With Projects
17239 @anchor{gnat_ugn/gnat_project_manager tools-options-in-project-files}@anchor{15e}@anchor{gnat_ugn/gnat_project_manager id7}@anchor{15f}
17240 @subsection Tools Options in Project Files
17243 We now have a project file that fully describes our environment, and can be
17244 used to build the application with a simple @emph{gprbuild} command as seen
17245 in the previous section. In fact, the empty project we showed immediately at
17246 the beginning (with no attribute at all) could already fulfill that need if it
17247 was put in the @code{common} directory.
17249 Of course, we might want more control. This section shows you how to specify
17250 the compilation switches that the various tools involved in the building of the
17251 executable should use.
17253 @geindex command line length (GNAT Project Manager)
17255 Since source names and locations are described in the project file, it is not
17256 necessary to use switches on the command line for this purpose (switches such
17257 as -I for gcc). This removes a major source of command line length overflow.
17258 Clearly, the builders will have to communicate this information one way or
17259 another to the underlying compilers and tools they call but they usually use
17260 response files for this and thus are not subject to command line overflows.
17262 Several tools participate to the creation of an executable: the compiler
17263 produces object files from the source files; the binder (in the Ada case)
17264 creates a "source" file that takes care, among other things, of elaboration
17265 issues and global variable initialization; and the linker gathers everything
17266 into a single executable that users can execute. All these tools are known to
17267 the project manager and will be called with user defined switches from the
17268 project files. However, we need to introduce a new project file concept to
17269 express the switches to be used for any of the tools involved in the build.
17271 @geindex project file packages (GNAT Project Manager)
17273 A project file is subdivided into zero or more @strong{packages}, each of which
17274 contains the attributes specific to one tool (or one set of tools). Project
17275 files use an Ada-like syntax for packages. Package names permitted in project
17276 files are restricted to a predefined set (see @ref{153,,Packages}), and the contents
17277 of packages are limited to a small set of constructs and attributes
17278 (see @ref{152,,Attributes}).
17280 Our example project file can be extended with the following empty packages. At
17281 this stage, they could all be omitted since they are empty, but they show which
17282 packages would be involved in the build process.
17284 @c code-block: ada-project
17286 @c project Build is
17287 @c for Source_Dirs use ("common");
17288 @c for Object_Dir use "obj";
17289 @c for Exec_Dir use ".";
17290 @c for Main use ("proc.adb");
17292 @c package Builder is --<<< for gprbuild
17295 @c package Compiler is --<<< for the compiler
17298 @c package Binder is --<<< for the binder
17301 @c package Linker is --<<< for the linker
17305 Let's first examine the compiler switches. As stated in the initial description
17306 of the example, we want to compile all files with @emph{-O2}. This is a
17307 compiler switch, although it is usual, on the command line, to pass it to the
17308 builder which then passes it to the compiler. It is recommended to use directly
17309 the right package, which will make the setup easier to understand for other
17312 Several attributes can be used to specify the switches:
17314 @geindex Default_Switches (GNAT Project Manager)
17316 @strong{Default_Switches}:
17320 This is the first mention in this manual of an @strong{indexed attribute}. When
17321 this attribute is defined, one must supply an @emph{index} in the form of a
17323 In the case of @emph{Default_Switches}, the index is the name of the
17324 language to which the switches apply (since a different compiler will
17325 likely be used for each language, and each compiler has its own set of
17326 switches). The value of the attribute is a list of switches.
17328 In this example, we want to compile all Ada source files with the switch
17329 @emph{-O2}, and the resulting project file is as follows
17330 (only the @cite{Compiler} package is shown):
17332 @c code-block: ada-project
17334 @c package Compiler is
17335 @c for Default_Switches ("Ada") use ("-O2");
17339 @geindex Switches (GNAT Project Manager)
17345 In some cases, we might want to use specific switches
17346 for one or more files. For instance, compiling @code{proc.adb} might not be
17347 possible at high level of optimization because of a compiler issue.
17348 In such a case, the @emph{Switches}
17349 attribute (indexed on the file name) can be used and will override the
17350 switches defined by @emph{Default_Switches}. Our project file would
17353 @c code-block: ada-project
17356 @c package Compiler is
17357 @c for Default_Switches ("Ada")
17359 @c for Switches ("proc.adb")
17363 @cite{Switches} may take a pattern as an index, such as in:
17365 @c code-block: ada-project
17367 @c package Compiler is
17368 @c for Default_Switches ("Ada")
17370 @c for Switches ("pkg*")
17374 Sources @code{pkg.adb} and @code{pkg-child.adb} would be compiled with -O0,
17377 @cite{Switches} can also be given a language name as index instead of a file
17378 name in which case it has the same semantics as @emph{Default_Switches}.
17379 However, indexes with wild cards are never valid for language name.
17382 @geindex Local_Configuration_Pragmas (GNAT Project Manager)
17384 @strong{Local_Configuration_Pragmas}:
17388 This attribute may specify the path
17389 of a file containing configuration pragmas for use by the Ada compiler,
17390 such as @cite{pragma Restrictions (No_Tasking)}. These pragmas will be
17391 used for all the sources of the project.
17394 The switches for the other tools are defined in a similar manner through the
17395 @strong{Default_Switches} and @strong{Switches} attributes, respectively in the
17396 @emph{Builder} package (for @emph{gprbuild}),
17397 the @emph{Binder} package (binding Ada executables) and the @emph{Linker}
17398 package (for linking executables).
17400 @node Compiling with Project Files,Executable File Names,Tools Options in Project Files,Building With Projects
17401 @anchor{gnat_ugn/gnat_project_manager compiling-with-project-files}@anchor{160}@anchor{gnat_ugn/gnat_project_manager id8}@anchor{161}
17402 @subsection Compiling with Project Files
17405 Now that our project files are written, let's build our executable.
17406 Here is the command we would use from the command line:
17412 This will automatically build the executables specified through the
17413 @emph{Main} attribute: for each, it will compile or recompile the
17414 sources for which the object file does not exist or is not up-to-date; it
17415 will then run the binder; and finally run the linker to create the
17418 The @emph{gprbuild} builder, can automatically manage C files the
17419 same way: create the file @code{utils.c} in the @code{common} directory,
17420 set the attribute @emph{Languages} to @cite{"(Ada@comma{} C)"}, and re-run
17426 Gprbuild knows how to recompile the C files and will
17427 recompile them only if one of their dependencies has changed. No direct
17428 indication on how to build the various elements is given in the
17429 project file, which describes the project properties rather than a
17430 set of actions to be executed. Here is the invocation of
17431 @emph{gprbuild} when building a multi-language program:
17443 Notice the three steps described earlier:
17449 The first three gcc commands correspond to the compilation phase.
17452 The gprbind command corresponds to the post-compilation phase.
17455 The last gcc command corresponds to the final link.
17458 @geindex -v option (for GPRbuild)
17460 The default output of GPRbuild's execution is kept reasonably simple and easy
17461 to understand. In particular, some of the less frequently used commands are not
17462 shown, and some parameters are abbreviated. So it is not possible to rerun the
17463 effect of the @emph{gprbuild} command by cut-and-pasting its output.
17464 GPRbuild's option @cite{-v} provides a much more verbose output which includes,
17465 among other information, more complete compilation, post-compilation and link
17468 @node Executable File Names,Avoid Duplication With Variables,Compiling with Project Files,Building With Projects
17469 @anchor{gnat_ugn/gnat_project_manager executable-file-names}@anchor{162}@anchor{gnat_ugn/gnat_project_manager id9}@anchor{163}
17470 @subsection Executable File Names
17473 @geindex Executable (GNAT Project Manager)
17475 By default, the executable name corresponding to a main file is
17476 computed from the main source file name. Through the attribute
17477 @strong{Builder.Executable}, it is possible to change this default.
17479 For instance, instead of building @emph{proc} (or @emph{proc.exe}
17480 on Windows), we could configure our project file to build "proc1"
17481 (resp proc1.exe) with the following addition:
17485 ... -- same as before
17487 for Executable ("proc.adb") use "proc1";
17492 @geindex Executable_Suffix (GNAT Project Manager)
17494 Attribute @strong{Executable_Suffix}, when specified, may change the suffix
17495 of the executable files, when no attribute @cite{Executable} applies:
17496 its value replaces the platform-specific executable suffix.
17497 The default executable suffix is empty on UNIX and ".exe" on Windows.
17499 It is also possible to change the name of the produced executable by using the
17500 command line switch @emph{-o}. When several mains are defined in the project,
17501 it is not possible to use the @emph{-o} switch and the only way to change the
17502 names of the executable is provided by Attributes @cite{Executable} and
17503 @cite{Executable_Suffix}.
17505 @node Avoid Duplication With Variables,Naming Schemes,Executable File Names,Building With Projects
17506 @anchor{gnat_ugn/gnat_project_manager id10}@anchor{164}@anchor{gnat_ugn/gnat_project_manager avoid-duplication-with-variables}@anchor{165}
17507 @subsection Avoid Duplication With Variables
17510 To illustrate some other project capabilities, here is a slightly more complex
17511 project using similar sources and a main program in C:
17515 for Languages use ("Ada", "C");
17516 for Source_Dirs use ("common");
17517 for Object_Dir use "obj";
17518 for Main use ("main.c");
17519 package Compiler is
17520 C_Switches := ("-pedantic");
17521 for Default_Switches ("C") use C_Switches;
17522 for Default_Switches ("Ada") use ("-gnaty");
17523 for Switches ("main.c") use C_Switches & ("-g");
17528 This project has many similarities with the previous one.
17529 As expected, its @cite{Main} attribute now refers to a C source.
17530 The attribute @emph{Exec_Dir} is now omitted, thus the resulting
17531 executable will be put in the directory @code{obj}.
17533 The most noticeable difference is the use of a variable in the
17534 @emph{Compiler} package to store settings used in several attributes.
17535 This avoids text duplication, and eases maintenance (a single place to
17536 modify if we want to add new switches for C files). We will revisit
17537 the use of variables in the context of scenarios (see @ref{14c,,Scenarios in Projects}).
17539 In this example, we see how the file @code{main.c} can be compiled with
17540 the switches used for all the other C files, plus @emph{-g}.
17541 In this specific situation the use of a variable could have been
17542 replaced by a reference to the @cite{Default_Switches} attribute:
17545 for Switches ("c_main.c") use Compiler'Default_Switches ("C") & ("-g");
17548 Note the tick (@emph{'}) used to refer to attributes defined in a package.
17550 Here is the output of the GPRbuild command using this project:
17553 $ gprbuild -Pc_main
17554 gcc -c -pedantic -g main.c
17555 gcc -c -gnaty proc.adb
17556 gcc -c -gnaty pack.adb
17557 gcc -c -pedantic utils.c
17563 The default switches for Ada sources,
17564 the default switches for C sources (in the compilation of @code{lib.c}),
17565 and the specific switches for @code{main.c} have all been taken into
17568 @node Naming Schemes,Installation,Avoid Duplication With Variables,Building With Projects
17569 @anchor{gnat_ugn/gnat_project_manager id11}@anchor{166}@anchor{gnat_ugn/gnat_project_manager naming-schemes}@anchor{14b}
17570 @subsection Naming Schemes
17573 Sometimes an Ada software system is ported from one compilation environment to
17574 another (say GNAT), and the file are not named using the default GNAT
17575 conventions. Instead of changing all the file names, which for a variety of
17576 reasons might not be possible, you can define the relevant file naming scheme
17577 in the @strong{Naming} package of your project file.
17579 The naming scheme has two distinct goals for the project manager: it
17580 allows finding of source files when searching in the source
17581 directories, and given a source file name it makes it possible to guess
17582 the associated language, and thus the compiler to use.
17584 Note that the use by the Ada compiler of pragmas Source_File_Name is not
17585 supported when using project files. You must use the features described in this
17586 paragraph. You can however specify other configuration pragmas.
17588 The following attributes can be defined in package @cite{Naming}:
17590 @geindex Casing (GNAT Project Manager)
17596 Its value must be one of @cite{"lowercase"} (the default if
17597 unspecified), @cite{"uppercase"} or @cite{"mixedcase"}. It describes the
17598 casing of file names with regards to the Ada unit name. Given an Ada unit
17599 My_Unit, the file name will respectively be @code{my_unit.adb} (lowercase),
17600 @code{MY_UNIT.ADB} (uppercase) or @code{My_Unit.adb} (mixedcase).
17601 On Windows, file names are case insensitive, so this attribute is
17605 @geindex Dot_Replacement (GNAT Project Manager)
17607 @strong{Dot_Replacement}:
17611 This attribute specifies the string that should replace the "." in unit
17612 names. Its default value is @cite{"-"} so that a unit
17613 @cite{Parent.Child} is expected to be found in the file
17614 @code{parent-child.adb}. The replacement string must satisfy the following
17615 requirements to avoid ambiguities in the naming scheme:
17621 It must not be empty
17624 It cannot start or end with an alphanumeric character
17627 It cannot be a single underscore
17630 It cannot start with an underscore followed by an alphanumeric
17633 It cannot contain a dot @cite{'.'} except if the entire string is @cite{"."}
17637 @geindex Spec_Suffix (GNAT Project Manager)
17639 @geindex Specification_Suffix (GNAT Project Manager)
17641 @strong{Spec_Suffix} and @strong{Specification_Suffix}:
17645 For Ada, these attributes give the suffix used in file names that contain
17646 specifications. For other languages, they give the extension for files
17647 that contain declaration (header files in C for instance). The attribute
17648 is indexed on the language.
17649 The two attributes are equivalent, but the latter is obsolescent.
17651 If the value of the attribute is the empty string, it indicates to the
17652 Project Manager that the only specifications/header files for the language
17653 are those specified with attributes @cite{Spec} or
17654 @cite{Specification_Exceptions}.
17656 If @cite{Spec_Suffix ("Ada")} is not specified, then the default is
17659 A non empty value must satisfy the following requirements:
17665 It must include at least one dot
17668 If @cite{Dot_Replacement} is a single dot, then it cannot include
17673 @geindex Body_Suffix (GNAT Project Manager)
17675 @geindex Implementation_Suffix (GNAT Project Manager)
17677 @strong{Body_Suffix} and @strong{Implementation_Suffix}:
17681 These attributes give the extension used for file names that contain
17682 code (bodies in Ada). They are indexed on the language. The second
17683 version is obsolescent and fully replaced by the first attribute.
17685 For each language of a project, one of these two attributes need to be
17686 specified, either in the project itself or in the configuration project file.
17688 If the value of the attribute is the empty string, it indicates to the
17689 Project Manager that the only source files for the language
17690 are those specified with attributes @cite{Body} or
17691 @cite{Implementation_Exceptions}.
17693 These attributes must satisfy the same requirements as @cite{Spec_Suffix}.
17694 In addition, they must be different from any of the values in
17695 @cite{Spec_Suffix}.
17696 If @cite{Body_Suffix ("Ada")} is not specified, then the default is
17699 If @cite{Body_Suffix ("Ada")} and @cite{Spec_Suffix ("Ada")} end with the
17700 same string, then a file name that ends with the longest of these two
17701 suffixes will be a body if the longest suffix is @cite{Body_Suffix ("Ada")}
17702 or a spec if the longest suffix is @cite{Spec_Suffix ("Ada")}.
17704 If the suffix does not start with a '.', a file with a name exactly equal to
17705 the suffix will also be part of the project (for instance if you define the
17706 suffix as @cite{Makefile.in}, a file called @code{Makefile.in} will be part
17707 of the project. This capability is usually not interesting when building.
17708 However, it might become useful when a project is also used to
17709 find the list of source files in an editor, like the GNAT Programming System
17713 @geindex Separate_Suffix (GNAT Project Manager)
17715 @strong{Separate_Suffix}:
17719 This attribute is specific to Ada. It denotes the suffix used in file names
17720 that contain separate bodies. If it is not specified, then it defaults to
17721 same value as @cite{Body_Suffix ("Ada")}.
17723 The value of this attribute cannot be the empty string.
17725 Otherwise, the same rules apply as for the
17726 @cite{Body_Suffix} attribute. The only accepted index is "Ada".
17729 @strong{Spec} or @strong{Specification}:
17733 @geindex Spec (GNAT Project Manager)
17735 @geindex Specification (GNAT Project Manager)
17737 This attribute @cite{Spec} can be used to define the source file name for a
17738 given Ada compilation unit's spec. The index is the literal name of the Ada
17739 unit (case insensitive). The value is the literal base name of the file that
17740 contains this unit's spec (case sensitive or insensitive depending on the
17741 operating system). This attribute allows the definition of exceptions to the
17742 general naming scheme, in case some files do not follow the usual
17745 When a source file contains several units, the relative position of the unit
17746 can be indicated. The first unit in the file is at position 1
17749 for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
17750 for Spec ("top") use "foo.a" at 1;
17751 for Spec ("foo") use "foo.a" at 2;
17755 @geindex Body (GNAT Project Manager)
17757 @geindex Implementation (GNAT Project Manager)
17759 @strong{Body} or @strong{Implementation}:
17763 These attribute play the same role as @emph{Spec} for Ada bodies.
17766 @geindex Specification_Exceptions (GNAT Project Manager)
17768 @geindex Implementation_Exceptions (GNAT Project Manager)
17770 @strong{Specification_Exceptions} and @strong{Implementation_Exceptions}:
17774 These attributes define exceptions to the naming scheme for languages
17775 other than Ada. They are indexed on the language name, and contain
17776 a list of file names respectively for headers and source code.
17779 For example, the following package models the Apex file naming rules:
17783 for Casing use "lowercase";
17784 for Dot_Replacement use ".";
17785 for Spec_Suffix ("Ada") use ".1.ada";
17786 for Body_Suffix ("Ada") use ".2.ada";
17790 @node Installation,Distributed support,Naming Schemes,Building With Projects
17791 @anchor{gnat_ugn/gnat_project_manager id12}@anchor{167}@anchor{gnat_ugn/gnat_project_manager installation}@anchor{168}
17792 @subsection Installation
17795 After building an application or a library it is often required to
17796 install it into the development environment. For instance this step is
17797 required if the library is to be used by another application.
17798 The @emph{gprinstall} tool provides an easy way to install
17799 libraries, executable or object code generated during the build. The
17800 @strong{Install} package can be used to change the default locations.
17802 The following attributes can be defined in package @cite{Install}:
17804 @geindex Active (GNAT Project Manager)
17809 @item @strong{Active}
17811 Whether the project is to be installed, values are @cite{true}
17812 (default) or @cite{false}.
17815 @geindex Artifacts (GNAT Project Manager)
17821 An array attribute to declare a set of files not part of the sources
17822 to be installed. The array discriminant is the directory where the
17823 file is to be installed. If a relative directory then Prefix (see
17824 below) is prepended.
17827 @geindex Prefix (GNAT Project Manager)
17833 Root directory for the installation.
17836 @strong{Exec_Subdir}
17840 Subdirectory of @strong{Prefix} where executables are to be
17841 installed. Default is @strong{bin}.
17844 @strong{Lib_Subdir}
17848 Subdirectory of @strong{Prefix} where directory with the library or object
17849 files is to be installed. Default is @strong{lib}.
17852 @strong{Sources_Subdir}
17856 Subdirectory of @strong{Prefix} where directory with sources is to be
17857 installed. Default is @strong{include}.
17860 @strong{Project_Subdir}
17864 Subdirectory of @strong{Prefix} where the generated project file is to be
17865 installed. Default is @strong{share/gpr}.
17872 The installation mode, it is either @strong{dev} (default) or @strong{usage}.
17873 See @strong{gprbuild} user's guide for details.
17876 @strong{Install_Name}
17880 Specify the name to use for recording the installation. The default is
17881 the project name without the extension.
17884 @node Distributed support,,Installation,Building With Projects
17885 @anchor{gnat_ugn/gnat_project_manager id13}@anchor{169}@anchor{gnat_ugn/gnat_project_manager distributed-support}@anchor{16a}
17886 @subsection Distributed support
17889 For large projects the compilation time can become a limitation in
17890 the development cycle. To cope with that, GPRbuild supports
17891 distributed compilation.
17893 The following attributes can be defined in package @cite{Remote}:
17895 @geindex Root_Dir (GNAT Project Manager)
17901 Root directory of the project's sources. The default value is the
17902 project's directory.
17905 @node Organizing Projects into Subsystems,Scenarios in Projects,Building With Projects,GNAT Project Manager
17906 @anchor{gnat_ugn/gnat_project_manager organizing-projects-into-subsystems}@anchor{14e}@anchor{gnat_ugn/gnat_project_manager id14}@anchor{16b}
17907 @section Organizing Projects into Subsystems
17910 A @strong{subsystem} is a coherent part of the complete system to be built. It is
17911 represented by a set of sources and one single object directory. A system can
17912 be composed of a single subsystem when it is simple as we have seen in the
17913 first section. Complex systems are usually composed of several interdependent
17914 subsystems. A subsystem is dependent on another subsystem if knowledge of the
17915 other one is required to build it, and in particular if visibility on some of
17916 the sources of this other subsystem is required. Each subsystem is usually
17917 represented by its own project file.
17919 In this section, the previous example is being extended. Let's assume some
17920 sources of our @cite{Build} project depend on other sources.
17921 For instance, when building a graphical interface, it is usual to depend upon
17922 a graphical library toolkit such as GtkAda. Furthermore, we also need
17923 sources from a logging module we had previously written.
17926 * Project Dependencies::
17927 * Cyclic Project Dependencies::
17928 * Sharing Between Projects::
17929 * Global Attributes::
17933 @node Project Dependencies,Cyclic Project Dependencies,,Organizing Projects into Subsystems
17934 @anchor{gnat_ugn/gnat_project_manager project-dependencies}@anchor{16c}@anchor{gnat_ugn/gnat_project_manager id15}@anchor{16d}
17935 @subsection Project Dependencies
17938 GtkAda comes with its own project file (appropriately called
17939 @code{gtkada.gpr}), and we will assume we have already built a project
17940 called @code{logging.gpr} for the logging module. With the information provided
17941 so far in @code{build.gpr}, building the application would fail with an error
17942 indicating that the gtkada and logging units that are relied upon by the sources
17943 of this project cannot be found.
17945 This is solved by adding the following @strong{with} clauses at the beginning of our
17950 with "a/b/logging.gpr";
17956 @geindex Externally_Built (GNAT Project Manager)
17958 When such a project is compiled, @emph{gprbuild} will automatically check
17959 the other projects and recompile their sources when needed. It will also
17960 recompile the sources from @cite{Build} when needed, and finally create the
17961 executable. In some cases, the implementation units needed to recompile a
17962 project are not available, or come from some third party and you do not want to
17963 recompile it yourself. In this case, set the attribute @strong{Externally_Built} to
17964 "true", indicating to the builder that this project can be assumed to be
17965 up-to-date, and should not be considered for recompilation. In Ada, if the
17966 sources of this externally built project were compiled with another version of
17967 the compiler or with incompatible options, the binder will issue an error.
17969 The project's @emph{with} clause has several effects. It provides source
17970 visibility between projects during the compilation process. It also guarantees
17971 that the necessary object files from @cite{Logging} and @cite{GtkAda} are
17972 available when linking @cite{Build}.
17974 As can be seen in this example, the syntax for importing projects is similar
17975 to the syntax for importing compilation units in Ada. However, project files
17976 use literal strings instead of names, and the @emph{with} clause identifies
17977 project files rather than packages.
17979 Each literal string after @emph{with} is the path
17980 (absolute or relative) to a project file. The @cite{.gpr} extension is
17981 optional, although we recommend adding it. If no extension is specified,
17982 and no project file with the @code{.gpr} extension is found, then
17983 the file is searched for exactly as written in the @emph{with} clause,
17984 that is with no extension.
17986 As mentioned above, the path after a @emph{with} has to be a literal
17987 string, and you cannot use concatenation, or lookup the value of external
17988 variables to change the directories from which a project is loaded.
17989 A solution if you need something like this is to use aggregate projects
17990 (see @ref{16e,,Aggregate Projects}).
17992 @geindex project path (GNAT Project Manager)
17994 When a relative path or a base name is used, the
17995 project files are searched relative to each of the directories in the
17996 @strong{project path}. This path includes all the directories found with the
17997 following algorithm, in this order; the first matching file is used:
18003 First, the file is searched relative to the directory that contains the
18004 current project file.
18006 @geindex GPR_PROJECT_PATH_FILE (GNAT Project Manager)
18008 @geindex GPR_PROJECT_PATH (GNAT Project Manager)
18010 @geindex ADA_PROJECT_PATH (GNAT Project Manager)
18013 Then it is searched relative to all the directories specified in the
18014 environment variables @strong{GPR_PROJECT_PATH_FILE},
18015 @strong{GPR_PROJECT_PATH} and @strong{ADA_PROJECT_PATH} (in that order) if they exist.
18016 The value of @strong{GPR_PROJECT_PATH_FILE}, when defined, is the path name of
18017 a text file that contains project directory path names, one per line.
18018 @strong{GPR_PROJECT_PATH} and @strong{ADA_PROJECT_PATH}, when defined, contain
18019 project directory path names separated by directory separators.
18020 @strong{ADA_PROJECT_PATH} is used for compatibility, it is recommended to
18021 use @strong{GPR_PROJECT_PATH_FILE} or @strong{GPR_PROJECT_PATH}.
18024 Finally, it is searched relative to the default project directories.
18025 Such directories depend on the tool used. The locations searched in the
18026 specified order are:
18032 @code{<prefix>/<target>/lib/gnat} if option @emph{--target} is specified
18035 @code{<prefix>/<target>/share/gpr} if option @emph{--target} is specified
18038 @code{<prefix>/share/gpr/}
18041 @code{<prefix>/lib/gnat/}
18044 In our example, @code{gtkada.gpr} is found in the predefined directory if
18045 it was installed at the same root as GNAT.
18048 Some tools also support extending the project path from the command line,
18049 generally through the @emph{-aP}. You can see the value of the project
18050 path by using the @emph{gnatls -v} command.
18052 Any symbolic link will be fully resolved in the directory of the
18053 importing project file before the imported project file is examined.
18055 Any source file in the imported project can be used by the sources of the
18056 importing project, transitively.
18057 Thus if @cite{A} imports @cite{B}, which imports @cite{C}, the sources of
18058 @cite{A} may depend on the sources of @cite{C}, even if @cite{A} does not
18059 import @cite{C} explicitly. However, this is not recommended, because if
18060 and when @cite{B} ceases to import @cite{C}, some sources in @cite{A} will
18061 no longer compile. @emph{gprbuild} has a switch @emph{--no-indirect-imports}
18062 that will report such indirect dependencies.
18066 One very important aspect of a project hierarchy is that
18067 @strong{a given source can only belong to one project} (otherwise the project manager
18068 would not know which settings apply to it and when to recompile it). It means
18069 that different project files do not usually share source directories or
18070 when they do, they need to specify precisely which project owns which sources
18071 using attribute @cite{Source_Files} or equivalent. By contrast, 2 projects
18072 can each own a source with the same base file name as long as they live in
18073 different directories. The latter is not true for Ada Sources because of the
18074 correlation between source files and Ada units.
18078 @node Cyclic Project Dependencies,Sharing Between Projects,Project Dependencies,Organizing Projects into Subsystems
18079 @anchor{gnat_ugn/gnat_project_manager id16}@anchor{16f}@anchor{gnat_ugn/gnat_project_manager cyclic-project-dependencies}@anchor{170}
18080 @subsection Cyclic Project Dependencies
18083 Cyclic dependencies are mostly forbidden:
18084 if @cite{A} imports @cite{B} (directly or indirectly) then @cite{B}
18085 is not allowed to import @cite{A}. However, there are cases when cyclic
18086 dependencies would be beneficial. For these cases, another form of import
18087 between projects exists: the @strong{limited with}. A project @cite{A} that
18088 imports a project @cite{B} with a straight @emph{with} may also be imported,
18089 directly or indirectly, by @cite{B} through a @cite{limited with}.
18091 The difference between straight @emph{with} and @cite{limited with} is that
18092 the name of a project imported with a @cite{limited with} cannot be used in the
18093 project importing it. In particular, its packages cannot be renamed and
18094 its variables cannot be referred to.
18100 for Exec_Dir use B'Exec_Dir; -- ok
18103 limited with "a.gpr"; -- Cyclic dependency: A -> B -> A
18105 for Exec_Dir use A'Exec_Dir; -- not ok
18112 limited with "a.gpr"; -- Cyclic dependency: A -> C -> D -> A
18114 for Exec_Dir use A'Exec_Dir; -- not ok
18118 @node Sharing Between Projects,Global Attributes,Cyclic Project Dependencies,Organizing Projects into Subsystems
18119 @anchor{gnat_ugn/gnat_project_manager sharing-between-projects}@anchor{171}@anchor{gnat_ugn/gnat_project_manager id17}@anchor{172}
18120 @subsection Sharing Between Projects
18123 When building an application, it is common to have similar needs in several of
18124 the projects corresponding to the subsystems under construction. For instance,
18125 they will all have the same compilation switches.
18127 As seen before (see @ref{15e,,Tools Options in Project Files}), setting compilation
18128 switches for all sources of a subsystem is simple: it is just a matter of
18129 adding a @cite{Compiler.Default_Switches} attribute to each project files with
18130 the same value. Of course, that means duplication of data, and both places need
18131 to be changed in order to recompile the whole application with different
18132 switches. It can become a real problem if there are many subsystems and thus
18133 many project files to edit.
18135 There are two main approaches to avoiding this duplication:
18141 Since @code{build.gpr} imports @code{logging.gpr}, we could change it
18142 to reference the attribute in Logging, either through a package renaming,
18143 or by referencing the attribute. The following example shows both cases:
18147 package Compiler is
18148 for Switches ("Ada")
18152 for Switches ("Ada")
18157 with "logging.gpr";
18159 package Compiler renames Logging.Compiler;
18161 for Switches ("Ada") use Logging.Binder'Switches ("Ada");
18166 The solution used for @cite{Compiler} gets the same value for all
18167 attributes of the package, but you cannot modify anything from the
18168 package (adding extra switches or some exceptions). The second
18169 version is more flexible, but more verbose.
18171 If you need to refer to the value of a variable in an imported
18172 project, rather than an attribute, the syntax is similar but uses
18173 a "." rather than an apostrophe. For instance:
18178 Var1 := Imported.Var;
18183 The second approach is to define the switches in a third project.
18184 That project is set up without any sources (so that, as opposed to
18185 the first example, none of the project plays a special role), and
18186 will only be used to define the attributes. Such a project is
18187 typically called @code{shared.gpr}.
18190 abstract project Shared is
18191 for Source_Files use (); -- no sources
18192 package Compiler is
18193 for Switches ("Ada")
18200 package Compiler renames Shared.Compiler;
18205 package Compiler renames Shared.Compiler;
18209 As for the first example, we could have chosen to set the attributes
18210 one by one rather than to rename a package. The reason we explicitly
18211 indicate that @cite{Shared} has no sources is so that it can be created
18212 in any directory and we are sure it shares no sources with @cite{Build}
18213 or @cite{Logging}, which of course would be invalid.
18215 @geindex project qualifier (GNAT Project Manager)
18217 Note the additional use of the @strong{abstract} qualifier in @code{shared.gpr}.
18218 This qualifier is optional, but helps convey the message that we do not
18219 intend this project to have sources (see @ref{173,,Qualified Projects} for
18223 @node Global Attributes,,Sharing Between Projects,Organizing Projects into Subsystems
18224 @anchor{gnat_ugn/gnat_project_manager global-attributes}@anchor{174}@anchor{gnat_ugn/gnat_project_manager id18}@anchor{175}
18225 @subsection Global Attributes
18228 We have already seen many examples of attributes used to specify a special
18229 option of one of the tools involved in the build process. Most of those
18230 attributes are project specific. That it to say, they only affect the invocation
18231 of tools on the sources of the project where they are defined.
18233 There are a few additional attributes that apply to all projects in a
18234 hierarchy as long as they are defined on the "main" project.
18235 The main project is the project explicitly mentioned on the command-line.
18236 The project hierarchy is the "with"-closure of the main project.
18238 Here is a list of commonly used global attributes:
18240 @geindex Global_Configuration_Pragmas (GNAT Project Manager)
18242 @strong{Builder.Global_Configuration_Pragmas}:
18246 This attribute points to a file that contains configuration pragmas
18247 to use when building executables. These pragmas apply for all
18248 executables built from this project hierarchy. As we have seen before,
18249 additional pragmas can be specified on a per-project basis by setting the
18250 @cite{Compiler.Local_Configuration_Pragmas} attribute.
18253 @geindex Global_Compilation_Switches (GNAT Project Manager)
18255 @strong{Builder.Global_Compilation_Switches}:
18259 This attribute is a list of compiler switches to use when compiling any
18260 source file in the project hierarchy. These switches are used in addition
18261 to the ones defined in the @cite{Compiler} package, which only apply to
18262 the sources of the corresponding project. This attribute is indexed on
18263 the name of the language.
18266 Using such global capabilities is convenient. It can also lead to unexpected
18267 behavior. Especially when several subsystems are shared among different main
18268 projects and the different global attributes are not
18269 compatible. Note that using aggregate projects can be a safer and more powerful
18270 replacement to global attributes.
18272 @node Scenarios in Projects,Library Projects,Organizing Projects into Subsystems,GNAT Project Manager
18273 @anchor{gnat_ugn/gnat_project_manager id19}@anchor{176}@anchor{gnat_ugn/gnat_project_manager scenarios-in-projects}@anchor{14c}
18274 @section Scenarios in Projects
18277 Various aspects of the projects can be modified based on @strong{scenarios}. These
18278 are user-defined modes that change the behavior of a project. Typical
18279 examples are the setup of platform-specific compiler options, or the use of
18280 a debug and a release mode (the former would activate the generation of debug
18281 information, while the second will focus on improving code optimization).
18283 Let's enhance our example to support debug and release modes. The issue is to
18284 let the user choose what kind of system he is building: use @emph{-g} as
18285 compiler switches in debug mode and @emph{-O2} in release mode. We will also
18286 set up the projects so that we do not share the same object directory in both
18287 modes; otherwise switching from one to the other might trigger more
18288 recompilations than needed or mix objects from the two modes.
18290 One naive approach is to create two different project files, say
18291 @code{build_debug.gpr} and @code{build_release.gpr}, that set the appropriate
18292 attributes as explained in previous sections. This solution does not scale
18293 well, because in the presence of multiple projects depending on each other, you
18294 will also have to duplicate the complete hierarchy and adapt the project files
18295 to point to the right copies.
18297 @geindex scenarios (GNAT Project Manager)
18299 Instead, project files support the notion of scenarios controlled
18300 by external values. Such values can come from several sources (in decreasing
18301 order of priority):
18303 @geindex -X (usage with GNAT Project Manager)
18308 @item @strong{Command line}:
18310 When launching @emph{gprbuild}, the user can pass
18311 extra @emph{-X} switches to define the external value. In
18312 our case, the command line might look like
18315 gprbuild -Pbuild.gpr -Xmode=release
18318 @item @strong{Environment variables}:
18320 When the external value does not come from the command line, it can come from
18321 the value of environment variables of the appropriate name.
18322 In our case, if an environment variable called "mode"
18323 exists, its value will be taken into account.
18326 @geindex external (GNAT Project Manager)
18328 @strong{External function second parameter}.
18330 We now need to get that value in the project. The general form is to use
18331 the predefined function @strong{external} which returns the current value of
18332 the external. For instance, we could set up the object directory to point to
18333 either @code{obj/debug} or @code{obj/release} by changing our project to
18337 for Object_Dir use "obj/" & external ("mode", "debug");
18342 The second parameter to @cite{external} is optional, and is the default
18343 value to use if "mode" is not set from the command line or the environment.
18345 In order to set the switches according to the different scenarios, other
18346 constructs have to be introduced such as typed variables and case constructions.
18348 @geindex typed variable (GNAT Project Manager)
18350 @geindex case construction (GNAT Project Manager)
18352 A @strong{typed variable} is a variable that
18353 can take only a limited number of values, similar to an enumeration in Ada.
18354 Such a variable can then be used in a @strong{case construction} and create conditional
18355 sections in the project. The following example shows how this can be done:
18359 type Mode_Type is ("debug", "release"); -- all possible values
18360 Mode : Mode_Type := external ("mode", "debug"); -- a typed variable
18362 package Compiler is
18365 for Switches ("Ada")
18368 for Switches ("Ada")
18375 The project has suddenly grown in size, but has become much more flexible.
18376 @cite{Mode_Type} defines the only valid values for the @cite{mode} variable. If
18377 any other value is read from the environment, an error is reported and the
18378 project is considered as invalid.
18380 The @cite{Mode} variable is initialized with an external value
18381 defaulting to @cite{"debug"}. This default could be omitted and that would
18382 force the user to define the value. Finally, we can use a case construction to set the
18383 switches depending on the scenario the user has chosen.
18385 Most aspects of the projects can depend on scenarios. The notable exception
18386 are project dependencies (@emph{with} clauses), which cannot depend on a scenario.
18388 Scenarios work the same way with @strong{project hierarchies}: you can either
18389 duplicate a variable similar to @cite{Mode} in each of the project (as long
18390 as the first argument to @cite{external} is always the same and the type is
18391 the same), or simply set the variable in the @code{shared.gpr} project
18392 (see @ref{171,,Sharing Between Projects}).
18394 @node Library Projects,Project Extension,Scenarios in Projects,GNAT Project Manager
18395 @anchor{gnat_ugn/gnat_project_manager library-projects}@anchor{8a}@anchor{gnat_ugn/gnat_project_manager id20}@anchor{177}
18396 @section Library Projects
18399 So far, we have seen examples of projects that create executables. However,
18400 it is also possible to create libraries instead. A @strong{library} is a specific
18401 type of subsystem where, for convenience, objects are grouped together
18402 using system-specific means such as archives or windows DLLs.
18404 Library projects provide a system- and language-independent way of building
18405 both @strong{static} and @strong{dynamic} libraries. They also support the concept of
18406 @strong{standalone libraries} (SAL) which offer two significant properties: the
18407 elaboration (e.g. initialization) of the library is either automatic or
18408 very simple; a change in the
18409 implementation part of the library implies minimal post-compilation actions on
18410 the complete system and potentially no action at all for the rest of the
18411 system in the case of dynamic SALs.
18413 There is a restriction on shared library projects: by default, they are only
18414 allowed to import other shared library projects. They are not allowed to
18415 import non library projects or static library projects.
18417 The GNAT Project Manager takes complete care of the library build, rebuild and
18418 installation tasks, including recompilation of the source files for which
18419 objects do not exist or are not up to date, assembly of the library archive, and
18420 installation of the library (i.e., copying associated source, object and
18421 @code{ALI} files to the specified location).
18424 * Building Libraries::
18425 * Using Library Projects::
18426 * Stand-alone Library Projects::
18427 * Installing a library with project files::
18431 @node Building Libraries,Using Library Projects,,Library Projects
18432 @anchor{gnat_ugn/gnat_project_manager id21}@anchor{178}@anchor{gnat_ugn/gnat_project_manager building-libraries}@anchor{179}
18433 @subsection Building Libraries
18436 Let's enhance our example and transform the @cite{logging} subsystem into a
18437 library. In order to do so, a few changes need to be made to
18438 @code{logging.gpr}. Some attributes need to be defined: at least
18439 @cite{Library_Name} and @cite{Library_Dir}; in addition, some other attributes
18440 can be used to specify specific aspects of the library. For readability, it is
18441 also recommended (although not mandatory), to use the qualifier @cite{library}
18442 in front of the @cite{project} keyword.
18444 @geindex Library_Name (GNAT Project Manager)
18446 @strong{Library_Name}:
18450 This attribute is the name of the library to be built. There is no
18451 restriction on the name of a library imposed by the project manager, except
18452 for stand-alone libraries whose names must follow the syntax of Ada
18453 identifiers; however, there may be system-specific restrictions on the name.
18454 In general, it is recommended to stick to alphanumeric characters (and
18455 possibly single underscores) to help portability.
18458 @geindex Library_Dir (GNAT Project Manager)
18460 @strong{Library_Dir}:
18464 This attribute is the path (absolute or relative) of the directory where
18465 the library is to be installed. In the process of building a library,
18466 the sources are compiled, the object files end up in the explicit or
18467 implicit @cite{Object_Dir} directory. When all sources of a library
18468 are compiled, some of the compilation artifacts, including the library itself,
18469 are copied to the library_dir directory. This directory must exist and be
18470 writable. It must also be different from the object directory so that cleanup
18471 activities in the Library_Dir do not affect recompilation needs.
18474 Here is the new version of @code{logging.gpr} that makes it a library:
18477 library project Logging is -- "library" is optional
18478 for Library_Name use "logging"; -- will create "liblogging.a" on Unix
18479 for Object_Dir use "obj";
18480 for Library_Dir use "lib"; -- different from object_dir
18484 Once the above two attributes are defined, the library project is valid and
18485 is enough for building a library with default characteristics.
18486 Other library-related attributes can be used to change the defaults:
18488 @geindex Library_Kind (GNAT Project Manager)
18490 @strong{Library_Kind}:
18494 The value of this attribute must be either @cite{"static"}, @cite{"dynamic"} or
18495 @cite{"relocatable"} (the latter is a synonym for dynamic). It indicates
18496 which kind of library should be built (the default is to build a
18497 static library, that is an archive of object files that can potentially
18498 be linked into a static executable). When the library is set to be dynamic,
18499 a separate image is created that will be loaded independently, usually
18500 at the start of the main program execution. Support for dynamic libraries is
18501 very platform specific, for instance on Windows it takes the form of a DLL
18502 while on GNU/Linux, it is a dynamic elf image whose suffix is usually
18503 @code{.so}. Library project files, on the other hand, can be written in
18504 a platform independent way so that the same project file can be used to build
18505 a library on different operating systems.
18507 If you need to build both a static and a dynamic library, it is recommended
18508 to use two different object directories, since in some cases some extra code
18509 needs to be generated for the latter. For such cases, one can either define
18510 two different project files, or a single one that uses scenarios to indicate
18511 the various kinds of library to be built and their corresponding object_dir.
18514 @geindex Library_ALI_Dir (GNAT Project Manager)
18516 @strong{Library_ALI_Dir}:
18520 This attribute may be specified to indicate the directory where the ALI
18521 files of the library are installed. By default, they are copied into the
18522 @cite{Library_Dir} directory, but as for the executables where we have a
18523 separate @cite{Exec_Dir} attribute, you might want to put them in a separate
18524 directory since there can be hundreds of them. The same restrictions as for
18525 the @cite{Library_Dir} attribute apply.
18528 @geindex Library_Version (GNAT Project Manager)
18530 @strong{Library_Version}:
18534 This attribute is platform dependent, and has no effect on Windows.
18535 On Unix, it is used only for dynamic libraries as the internal
18536 name of the library (the @cite{"soname"}). If the library file name (built
18537 from the @cite{Library_Name}) is different from the @cite{Library_Version},
18538 then the library file will be a symbolic link to the actual file whose name
18539 will be @cite{Library_Version}. This follows the usual installation schemes
18540 for dynamic libraries on many Unix systems.
18545 for Library_Dir use "lib";
18546 for Library_Name use "logging";
18547 for Library_Kind use "dynamic";
18548 for Library_Version use "liblogging.so." & Version;
18552 After the compilation, the directory @code{lib} will contain both a
18553 @code{libdummy.so.1} library and a symbolic link to it called
18554 @code{libdummy.so}.
18557 @geindex Library_GCC (GNAT Project Manager)
18559 @strong{Library_GCC}:
18563 This attribute is the name of the tool to use instead of "gcc" to link shared
18564 libraries. A common use of this attribute is to define a wrapper script that
18565 accomplishes specific actions before calling gcc (which itself calls the
18566 linker to build the library image).
18569 @geindex Library_Options (GNAT Project Manager)
18571 @strong{Library_Options}:
18575 This attribute may be used to specify additional switches (last switches)
18576 when linking a shared library.
18578 It may also be used to add foreign object files to a static library.
18579 Each string in Library_Options is an absolute or relative path of an object
18580 file. When a relative path, it is relative to the object directory.
18583 @geindex Leading_Library_Options (GNAT Project Manager)
18585 @strong{Leading_Library_Options}:
18589 This attribute, that is taken into account only by @emph{gprbuild}, may be
18590 used to specified leading options (first switches) when linking a shared
18594 @geindex Linker_Options (GNAT Project Manager)
18596 @strong{Linker.Linker_Options}:
18600 This attribute specifies additional switches to be given to the linker when
18601 linking an executable. It is ignored when defined in the main project and
18602 taken into account in all other projects that are imported directly or
18603 indirectly. These switches complement the @cite{Linker.Switches}
18604 defined in the main project. This is useful when a particular subsystem
18605 depends on an external library: adding this dependency as a
18606 @cite{Linker_Options} in the project of the subsystem is more convenient than
18607 adding it to all the @cite{Linker.Switches} of the main projects that depend
18608 upon this subsystem.
18611 @node Using Library Projects,Stand-alone Library Projects,Building Libraries,Library Projects
18612 @anchor{gnat_ugn/gnat_project_manager id22}@anchor{17a}@anchor{gnat_ugn/gnat_project_manager using-library-projects}@anchor{17b}
18613 @subsection Using Library Projects
18616 When the builder detects that a project file is a library project file, it
18617 recompiles all sources of the project that need recompilation and rebuild the
18618 library if any of the sources have been recompiled. It then groups all object
18619 files into a single file, which is a shared or a static library. This library
18620 can later on be linked with multiple executables. Note that the use
18621 of shard libraries reduces the size of the final executable and can also reduce
18622 the memory footprint at execution time when the library is shared among several
18625 @emph{gprbuild also allows to build **multi-language libraries*} when specifying
18626 sources from multiple languages.
18628 A non-library project can import a library project. When the builder is invoked
18629 on the former, the library of the latter is only rebuilt when absolutely
18630 necessary. For instance, if a unit of the library is not up-to-date but none of
18631 the executables need this unit, then the unit is not recompiled and the library
18632 is not reassembled. For instance, let's assume in our example that logging has
18633 the following sources: @code{log1.ads}, @code{log1.adb}, @code{log2.ads} and
18634 @code{log2.adb}. If @code{log1.adb} has been modified, then the library
18635 @code{liblogging} will be rebuilt when compiling all the sources of
18636 @cite{Build} only if @code{proc.ads}, @code{pack.ads} or @code{pack.adb}
18637 include a @cite{"with Log1"}.
18639 To ensure that all the sources in the @cite{Logging} library are
18640 up to date, and that all the sources of @cite{Build} are also up to date,
18641 the following two commands need to be used:
18644 gprbuild -Plogging.gpr
18645 gprbuild -Pbuild.gpr
18648 All @code{ALI} files will also be copied from the object directory to the
18649 library directory. To build executables, @emph{gprbuild} will use the
18650 library rather than the individual object files.
18652 Library projects can also be useful to describe a library that needs to be used
18653 but, for some reason, cannot be rebuilt. For instance, it is the case when some
18654 of the library sources are not available. Such library projects need to use the
18655 @cite{Externally_Built} attribute as in the example below:
18657 @c code-block: ada-project
18659 @c library project Extern_Lib is
18660 @c for Languages use ("Ada", "C");
18661 @c for Source_Dirs use ("lib_src");
18662 @c for Library_Dir use "lib2";
18663 @c for Library_Kind use "dynamic";
18664 @c for Library_Name use "l2";
18665 @c for Externally_Built use "true"; -- <<<<
18668 In the case of externally built libraries, the @cite{Object_Dir}
18669 attribute does not need to be specified because it will never be
18672 The main effect of using such an externally built library project is mostly to
18673 affect the linker command in order to reference the desired library. It can
18674 also be achieved by using @cite{Linker.Linker_Options} or @cite{Linker.Switches}
18675 in the project corresponding to the subsystem needing this external library.
18676 This latter method is more straightforward in simple cases but when several
18677 subsystems depend upon the same external library, finding the proper place
18678 for the @cite{Linker.Linker_Options} might not be easy and if it is
18679 not placed properly, the final link command is likely to present ordering issues.
18680 In such a situation, it is better to use the externally built library project
18681 so that all other subsystems depending on it can declare this dependency thanks
18682 to a project @emph{with} clause, which in turn will trigger the builder to find
18683 the proper order of libraries in the final link command.
18685 @node Stand-alone Library Projects,Installing a library with project files,Using Library Projects,Library Projects
18686 @anchor{gnat_ugn/gnat_project_manager id23}@anchor{17c}@anchor{gnat_ugn/gnat_project_manager stand-alone-library-projects}@anchor{97}
18687 @subsection Stand-alone Library Projects
18690 @geindex standalone libraries (usage with GNAT Project Manager)
18692 A @strong{stand-alone library} is a library that contains the necessary code to
18693 elaborate the Ada units that are included in the library. A stand-alone
18694 library is a convenient way to add an Ada subsystem to a more global system
18695 whose main is not in Ada since it makes the elaboration of the Ada part mostly
18696 transparent. However, stand-alone libraries are also useful when the main is in
18697 Ada: they provide a means for minimizing relinking & redeployment of complex
18698 systems when localized changes are made.
18700 The name of a stand-alone library, specified with attribute
18701 @cite{Library_Name}, must have the syntax of an Ada identifier.
18703 The most prominent characteristic of a stand-alone library is that it offers a
18704 distinction between interface units and implementation units. Only the former
18705 are visible to units outside the library. A stand-alone library project is thus
18706 characterised by a third attribute, usually @strong{Library_Interface}, in addition
18707 to the two attributes that make a project a Library Project
18708 (@cite{Library_Name} and @cite{Library_Dir}). This third attribute may also be
18709 @strong{Interfaces}. @strong{Library_Interface} only works when the interface is in Ada
18710 and takes a list of units as parameter. @strong{Interfaces} works for any supported
18711 language and takes a list of sources as parameter.
18713 @geindex Library_Interface (GNAT Project Manager)
18715 @strong{Library_Interface}:
18719 This attribute defines an explicit subset of the units of the project. Units
18720 from projects importing this library project may only "with" units whose
18721 sources are listed in the @cite{Library_Interface}. Other sources are
18722 considered implementation units.
18725 for Library_Dir use "lib";
18726 for Library_Name use "logging";
18727 for Library_Interface use ("lib1", "lib2"); -- unit names
18731 @strong{Interfaces}
18735 This attribute defines an explicit subset of the source files of a project.
18736 Sources from projects importing this project, can only depend on sources from
18737 this subset. This attribute can be used on non library projects. It can also
18738 be used as a replacement for attribute @cite{Library_Interface}, in which
18739 case, units have to be replaced by source files. For multi-language library
18740 projects, it is the only way to make the project a Stand-Alone Library project
18741 whose interface is not purely Ada.
18744 @geindex Library_Standalone (GNAT Project Manager)
18746 @strong{Library_Standalone}:
18750 This attribute defines the kind of standalone library to
18751 build. Values are either @cite{standard} (the default), @cite{no} or
18752 @cite{encapsulated}. When @cite{standard} is used the code to elaborate and
18753 finalize the library is embedded, when @cite{encapsulated} is used the
18754 library can furthermore depend only on static libraries (including
18755 the GNAT runtime). This attribute can be set to @cite{no} to make it clear
18756 that the library should not be standalone in which case the
18757 @cite{Library_Interface} should not defined. Note that this attribute
18758 only applies to shared libraries, so @cite{Library_Kind} must be set
18762 for Library_Dir use "lib";
18763 for Library_Name use "logging";
18764 for Library_Kind use "dynamic";
18765 for Library_Interface use ("lib1", "lib2"); -- unit names
18766 for Library_Standalone use "encapsulated";
18770 In order to include the elaboration code in the stand-alone library, the binder
18771 is invoked on the closure of the library units creating a package whose name
18772 depends on the library name (b~logging.ads/b in the example).
18773 This binder-generated package includes @strong{initialization} and @strong{finalization}
18774 procedures whose names depend on the library name (@cite{logginginit} and
18775 @cite{loggingfinal} in the example). The object corresponding to this package is
18776 included in the library.
18778 @geindex Library_Auto_Init (GNAT Project Manager)
18780 @strong{Library_Auto_Init}:
18784 A dynamic stand-alone Library is automatically initialized
18785 if automatic initialization of Stand-alone Libraries is supported on the
18786 platform and if attribute @strong{Library_Auto_Init} is not specified or
18787 is specified with the value "true". A static Stand-alone Library is never
18788 automatically initialized. Specifying "false" for this attribute
18789 prevents automatic initialization.
18791 When a non-automatically initialized stand-alone library is used in an
18792 executable, its initialization procedure must be called before any service of
18793 the library is used. When the main subprogram is in Ada, it may mean that the
18794 initialization procedure has to be called during elaboration of another
18798 @geindex Library_Dir (GNAT Project Manager)
18800 @strong{Library_Dir}:
18804 For a stand-alone library, only the @code{ALI} files of the interface units
18805 (those that are listed in attribute @cite{Library_Interface}) are copied to
18806 the library directory. As a consequence, only the interface units may be
18807 imported from Ada units outside of the library. If other units are imported,
18808 the binding phase will fail.
18811 @strong{Binder.Default_Switches}:
18815 When a stand-alone library is bound, the switches that are specified in
18816 the attribute @strong{Binder.Default_Switches ("Ada")} are
18817 used in the call to @emph{gnatbind}.
18820 @geindex Library_Src_Dir (GNAT Project Manager)
18822 @strong{Library_Src_Dir}:
18826 This attribute defines the location (absolute or relative to the project
18827 directory) where the sources of the interface units are copied at
18829 These sources includes the specs of the interface units along with the
18830 closure of sources necessary to compile them successfully. That may include
18831 bodies and subunits, when pragmas @cite{Inline} are used, or when there are
18832 generic units in specs. This directory cannot point to the object directory
18833 or one of the source directories, but it can point to the library directory,
18834 which is the default value for this attribute.
18837 @geindex Library_Symbol_Policy (GNAT Project Manager)
18839 @strong{Library_Symbol_Policy}:
18843 This attribute controls the export of symbols and, on some platforms (like
18844 VMS) that have the notions of major and minor IDs built in the library
18845 files, it controls the setting of these IDs. It is not supported on all
18846 platforms (where it will just have no effect). It may have one of the
18853 @cite{"autonomous"} or @cite{"default"}: exported symbols are not controlled
18856 @cite{"compliant"}: if attribute @strong{Library_Reference_Symbol_File}
18857 is not defined, then it is equivalent to policy "autonomous". If there
18858 are exported symbols in the reference symbol file that are not in the
18859 object files of the interfaces, the major ID of the library is increased.
18860 If there are symbols in the object files of the interfaces that are not
18861 in the reference symbol file, these symbols are put at the end of the list
18862 in the newly created symbol file and the minor ID is increased.
18865 @cite{"controlled"}: the attribute @strong{Library_Reference_Symbol_File} must be
18866 defined. The library will fail to build if the exported symbols in the
18867 object files of the interfaces do not match exactly the symbol in the
18871 @cite{"restricted"}: The attribute @strong{Library_Symbol_File} must be defined.
18872 The library will fail to build if there are symbols in the symbol file that
18873 are not in the exported symbols of the object files of the interfaces.
18874 Additional symbols in the object files are not added to the symbol file.
18877 @cite{"direct"}: The attribute @strong{Library_Symbol_File} must be defined and
18878 must designate an existing file in the object directory. This symbol file
18879 is passed directly to the underlying linker without any symbol processing.
18883 @geindex Library_Reference_Symbol_File (GNAT Project Manager)
18885 @strong{Library_Reference_Symbol_File}
18889 This attribute may define the path name of a reference symbol file that is
18890 read when the symbol policy is either "compliant" or "controlled", on
18891 platforms that support symbol control, such as VMS, when building a
18892 stand-alone library. The path may be an absolute path or a path relative
18893 to the project directory.
18896 @geindex Library_Symbol_File (GNAT Project Manager)
18898 @strong{Library_Symbol_File}
18902 This attribute may define the name of the symbol file to be created when
18903 building a stand-alone library when the symbol policy is either "compliant",
18904 "controlled" or "restricted", on platforms that support symbol control,
18905 such as VMS. When symbol policy is "direct", then a file with this name
18906 must exist in the object directory.
18909 @node Installing a library with project files,,Stand-alone Library Projects,Library Projects
18910 @anchor{gnat_ugn/gnat_project_manager installing-a-library-with-project-files}@anchor{8d}@anchor{gnat_ugn/gnat_project_manager id24}@anchor{17d}
18911 @subsection Installing a library with project files
18914 When using project files, a usable version of the library is created in the
18915 directory specified by the @cite{Library_Dir} attribute of the library
18916 project file. Thus no further action is needed in order to make use of
18917 the libraries that are built as part of the general application build.
18919 You may want to install a library in a context different from where the library
18920 is built. This situation arises with third party suppliers, who may want
18921 to distribute a library in binary form where the user is not expected to be
18922 able to recompile the library. The simplest option in this case is to provide
18923 a project file slightly different from the one used to build the library, by
18924 using the @cite{externally_built} attribute. See @ref{17b,,Using Library Projects}
18926 Another option is to use @emph{gprinstall} to install the library in a
18927 different context than the build location. @emph{gprinstall} automatically
18928 generates a project to use this library, and also copies the minimum set of
18929 sources needed to use the library to the install location.
18930 @ref{168,,Installation}
18932 @node Project Extension,Aggregate Projects,Library Projects,GNAT Project Manager
18933 @anchor{gnat_ugn/gnat_project_manager id25}@anchor{17e}@anchor{gnat_ugn/gnat_project_manager project-extension}@anchor{14f}
18934 @section Project Extension
18937 During development of a large system, it is sometimes necessary to use
18938 modified versions of some of the source files, without changing the original
18939 sources. This can be achieved through the @strong{project extension} facility.
18941 Suppose for instance that our example @cite{Build} project is built every night
18942 for the whole team, in some shared directory. A developer usually needs to work
18943 on a small part of the system, and might not want to have a copy of all the
18944 sources and all the object files (mostly because that would require too much
18945 disk space, time to recompile everything). He prefers to be able to override
18946 some of the source files in his directory, while taking advantage of all the
18947 object files generated at night.
18949 Another example can be taken from large software systems, where it is common to have
18950 multiple implementations of a common interface; in Ada terms, multiple
18951 versions of a package body for the same spec. For example, one implementation
18952 might be safe for use in tasking programs, while another might be used only
18953 in sequential applications. This can be modeled in GNAT using the concept
18954 of @emph{project extension}. If one project (the 'child') @emph{extends}
18955 another project (the 'parent') then by default all source files of the
18956 parent project are inherited by the child, but the child project can
18957 override any of the parent's source files with new versions, and can also
18958 add new files or remove unnecessary ones.
18959 This facility is the project analog of a type extension in
18960 object-oriented programming. Project hierarchies are permitted (an extending
18961 project may itself be extended), and a project that
18962 extends a project can also import other projects.
18964 A third example is that of using project extensions to provide different
18965 versions of the same system. For instance, assume that a @cite{Common}
18966 project is used by two development branches. One of the branches has now
18967 been frozen, and no further change can be done to it or to @cite{Common}.
18968 However, the other development branch still needs evolution of @cite{Common}.
18969 Project extensions provide a flexible solution to create a new version
18970 of a subsystem while sharing and reusing as much as possible from the original
18973 A project extension implicitly inherits all the sources and objects from the
18974 project it extends. It is possible to create a new version of some of the
18975 sources in one of the additional source directories of the extending
18976 project. Those new versions hide the original versions. Adding new sources or
18977 removing existing ones is also possible. Here is an example on how to extend
18978 the project @cite{Build} from previous examples:
18981 project Work extends "../bld/build.gpr" is
18985 The project after @strong{extends} is the one being extended. As usual, it can be
18986 specified using an absolute path, or a path relative to any of the directories
18987 in the project path (see @ref{16c,,Project Dependencies}). This project does not
18988 specify source or object directories, so the default values for these
18989 attributes will be used that is to say the current directory (where project
18990 @cite{Work} is placed). We can compile that project with
18996 If no sources have been placed in the current directory, this command
18997 won't do anything, since this project does not change the
18998 sources it inherited from @cite{Build}, therefore all the object files
18999 in @cite{Build} and its dependencies are still valid and are reused
19002 Suppose we now want to supply an alternate version of @code{pack.adb} but use
19003 the existing versions of @code{pack.ads} and @code{proc.adb}. We can create
19004 the new file in Work's current directory (likely by copying the one from the
19005 @cite{Build} project and making changes to it. If new packages are needed at
19006 the same time, we simply create new files in the source directory of the
19009 When we recompile, @emph{gprbuild} will now automatically recompile
19010 this file (thus creating @code{pack.o} in the current directory) and
19011 any file that depends on it (thus creating @code{proc.o}). Finally, the
19012 executable is also linked locally.
19014 Note that we could have obtained the desired behavior using project import
19015 rather than project inheritance. A @cite{base} project would contain the
19016 sources for @code{pack.ads} and @code{proc.adb}, and @cite{Work} would
19017 import @cite{base} and add @code{pack.adb}. In this scenario, @cite{base}
19018 cannot contain the original version of @code{pack.adb} otherwise there would be
19019 2 versions of the same unit in the closure of the project and this is not
19020 allowed. Generally speaking, it is not recommended to put the spec and the
19021 body of a unit in different projects since this affects their autonomy and
19024 In a project file that extends another project, it is possible to
19025 indicate that an inherited source is @strong{not part} of the sources of the
19026 extending project. This is necessary sometimes when a package spec has
19027 been overridden and no longer requires a body: in this case, it is
19028 necessary to indicate that the inherited body is not part of the sources
19029 of the project, otherwise there will be a compilation error
19030 when compiling the spec.
19032 @geindex Excluded_Source_Files (GNAT Project Manager)
19034 @geindex Excluded_Source_List_File (GNAT Project Manager)
19036 For that purpose, the attribute @strong{Excluded_Source_Files} is used.
19037 Its value is a list of file names.
19038 It is also possible to use attribute @cite{Excluded_Source_List_File}.
19039 Its value is the path of a text file containing one file name per
19043 project Work extends "../bld/build.gpr" is
19044 for Source_Files use ("pack.ads");
19045 -- New spec of Pkg does not need a completion
19046 for Excluded_Source_Files use ("pack.adb");
19050 All packages that are not declared in the extending project are inherited from
19051 the project being extended, with their attributes, with the exception of
19052 @cite{Linker'Linker_Options} which is never inherited. In particular, an
19053 extending project retains all the switches specified in the project being
19056 At the project level, if they are not declared in the extending project, some
19057 attributes are inherited from the project being extended. They are:
19058 @cite{Languages}, @cite{Main} (for a root non library project) and
19059 @cite{Library_Name} (for a project extending a library project).
19062 * Project Hierarchy Extension::
19066 @node Project Hierarchy Extension,,,Project Extension
19067 @anchor{gnat_ugn/gnat_project_manager project-hierarchy-extension}@anchor{17f}@anchor{gnat_ugn/gnat_project_manager id26}@anchor{180}
19068 @subsection Project Hierarchy Extension
19071 One of the fundamental restrictions in project extension is the following:
19072 @strong{A project is not allowed to import directly or indirectly at the same time an extending project and one of its ancestors}.
19074 For example, consider the following hierarchy of projects.
19077 a.gpr contains package A1
19078 b.gpr, imports a.gpr and contains B1, which depends on A1
19079 c.gpr, imports b.gpr and contains C1, which depends on B1
19082 If we want to locally extend the packages @cite{A1} and @cite{C1}, we need to
19083 create several extending projects:
19086 a_ext.gpr which extends a.gpr, and overrides A1
19087 b_ext.gpr which extends b.gpr and imports a_ext.gpr
19088 c_ext.gpr which extends c.gpr, imports b_ext.gpr and overrides C1
19092 project A_Ext extends "a.gpr" is
19093 for Source_Files use ("a1.adb", "a1.ads");
19097 project B_Ext extends "b.gpr" is
19101 project C_Ext extends "c.gpr" is
19102 for Source_Files use ("c1.adb");
19106 The extension @code{b_ext.gpr} is required, even though we are not overriding
19107 any of the sources of @code{b.gpr} because otherwise @code{c_expr.gpr} would
19108 import @code{b.gpr} which itself knows nothing about @code{a_ext.gpr}.
19110 @geindex extends all (GNAT Project Manager)
19112 When extending a large system spanning multiple projects, it is often
19113 inconvenient to extend every project in the hierarchy that is impacted by a
19114 small change introduced in a low layer. In such cases, it is possible to create
19115 an @strong{implicit extension} of an entire hierarchy using @strong{extends all}
19118 When the project is extended using @cite{extends all} inheritance, all projects
19119 that are imported by it, both directly and indirectly, are considered virtually
19120 extended. That is, the project manager creates implicit projects
19121 that extend every project in the hierarchy; all these implicit projects do not
19122 control sources on their own and use the object directory of
19123 the "extending all" project.
19125 It is possible to explicitly extend one or more projects in the hierarchy
19126 in order to modify the sources. These extending projects must be imported by
19127 the "extending all" project, which will replace the corresponding virtual
19128 projects with the explicit ones.
19130 When building such a project hierarchy extension, the project manager will
19131 ensure that both modified sources and sources in implicit extending projects
19132 that depend on them are recompiled.
19134 Thus, in our example we could create the following projects instead:
19137 a_ext.gpr, extends a.gpr and overrides A1
19138 c_ext.gpr, "extends all" c.gpr, imports a_ext.gpr and overrides C1
19142 project A_Ext extends "a.gpr" is
19143 for Source_Files use ("a1.adb", "a1.ads");
19147 project C_Ext extends all "c.gpr" is
19148 for Source_Files use ("c1.adb");
19152 When building project @code{c_ext.gpr}, the entire modified project space is
19153 considered for recompilation, including the sources of @code{b.gpr} that are
19154 impacted by the changes in @cite{A1} and @cite{C1}.
19156 @node Aggregate Projects,Aggregate Library Projects,Project Extension,GNAT Project Manager
19157 @anchor{gnat_ugn/gnat_project_manager aggregate-projects}@anchor{16e}@anchor{gnat_ugn/gnat_project_manager id27}@anchor{181}
19158 @section Aggregate Projects
19161 Aggregate projects are an extension of the project paradigm, and are
19162 meant to solve a few specific use cases that cannot be solved directly
19163 using standard projects. This section will go over a few of these use
19164 cases to try to explain what you can use aggregate projects for.
19167 * Building all main programs from a single project tree::
19168 * Building a set of projects with a single command::
19169 * Define a build environment::
19170 * Performance improvements in builder::
19171 * Syntax of aggregate projects::
19172 * package Builder in aggregate projects::
19176 @node Building all main programs from a single project tree,Building a set of projects with a single command,,Aggregate Projects
19177 @anchor{gnat_ugn/gnat_project_manager id28}@anchor{182}@anchor{gnat_ugn/gnat_project_manager building-all-main-programs-from-a-single-project-tree}@anchor{183}
19178 @subsection Building all main programs from a single project tree
19181 Most often, an application is organized into modules and submodules,
19182 which are very conveniently represented as a project tree or graph
19183 (the root project A @emph{with}s the projects for each modules (say B and C),
19184 which in turn @emph{with} projects for submodules.
19186 Very often, modules will build their own executables (for testing
19187 purposes for instance), or libraries (for easier reuse in various
19190 However, if you build your project through @emph{gprbuild}, using a syntax similar to
19196 this will only rebuild the main programs of project A, not those of the
19197 imported projects B and C. Therefore you have to spawn several
19198 @emph{gprbuild} commands, one per project, to build all executables.
19199 This is a little inconvenient, but more importantly is inefficient
19200 because @emph{gprbuild} needs to do duplicate work to ensure that sources are
19201 up-to-date, and cannot easily compile things in parallel when using
19204 Also libraries are always rebuilt when building a project.
19206 You could therefore define an aggregate project Agg that groups A, B
19207 and C. Then, when you build with
19213 this will build all mains from A, B and C.
19216 aggregate project Agg is
19217 for Project_Files use ("a.gpr", "b.gpr", "c.gpr");
19221 If B or C do not define any main program (through their Main
19222 attribute), all their sources are built. When you do not group them
19223 in the aggregate project, only those sources that are needed by A
19226 If you add a main to a project P not already explicitly referenced in the
19227 aggregate project, you will need to add "p.gpr" in the list of project
19228 files for the aggregate project, or the main will not be built when
19229 building the aggregate project.
19231 @node Building a set of projects with a single command,Define a build environment,Building all main programs from a single project tree,Aggregate Projects
19232 @anchor{gnat_ugn/gnat_project_manager building-a-set-of-projects-with-a-single-command}@anchor{184}@anchor{gnat_ugn/gnat_project_manager id29}@anchor{185}
19233 @subsection Building a set of projects with a single command
19236 One other case is when you have multiple applications and libraries
19237 that are built independently from each other (but can be built in
19238 parallel). For instance, you have a project tree rooted at A, and
19239 another one (which might share some subprojects) rooted at B.
19241 Using only @emph{gprbuild}, you could do
19248 to build both. But again, @emph{gprbuild} has to do some duplicate work for
19249 those files that are shared between the two, and cannot truly build
19250 things in parallel efficiently.
19252 If the two projects are really independent, share no sources other
19253 than through a common subproject, and have no source files with a
19254 common basename, you could create a project C that imports A and
19255 B. But these restrictions are often too strong, and one has to build
19256 them independently. An aggregate project does not have these
19257 limitations and can aggregate two project trees that have common
19260 This scenario is particularly useful in environments like VxWorks 653
19261 where the applications running in the multiple partitions can be built
19262 in parallel through a single @emph{gprbuild} command. This also works nicely
19265 @node Define a build environment,Performance improvements in builder,Building a set of projects with a single command,Aggregate Projects
19266 @anchor{gnat_ugn/gnat_project_manager id30}@anchor{186}@anchor{gnat_ugn/gnat_project_manager define-a-build-environment}@anchor{187}
19267 @subsection Define a build environment
19270 The environment variables at the time you launch @emph{gprbuild}
19271 will influence the view these tools have of the project
19272 (PATH to find the compiler, ADA_PROJECT_PATH or GPR_PROJECT_PATH to find the
19273 projects, environment variables that are referenced in project files
19274 through the "external" built-in function, ...). Several command line switches
19275 can be used to override those (-X or -aP), but on some systems and
19276 with some projects, this might make the command line too long, and on
19277 all systems often make it hard to read.
19279 An aggregate project can be used to set the environment for all
19280 projects built through that aggregate. One of the nice aspects is that
19281 you can put the aggregate project under configuration management, and
19282 make sure all your user have a consistent environment when
19283 building. The syntax looks like
19286 aggregate project Agg is
19287 for Project_Files use ("A.gpr", "B.gpr");
19288 for Project_Path use ("../dir1", "../dir1/dir2");
19289 for External ("BUILD") use "PRODUCTION";
19292 for Switches ("Ada") use ("-q");
19297 One of the often requested features in projects is to be able to
19298 reference external variables in @emph{with} declarations, as in
19301 with external("SETUP") & "path/prj.gpr"; -- ILLEGAL
19302 project MyProject is
19307 For various reasons, this is not allowed. But using aggregate projects provide
19308 an elegant solution. For instance, you could use a project file like:
19311 aggregate project Agg is
19312 for Project_Path use (external("SETUP") & "path");
19313 for Project_Files use ("myproject.gpr");
19316 with "prj.gpr"; -- searched on Agg'Project_Path
19317 project MyProject is
19322 @node Performance improvements in builder,Syntax of aggregate projects,Define a build environment,Aggregate Projects
19323 @anchor{gnat_ugn/gnat_project_manager performance-improvements-in-builder}@anchor{188}@anchor{gnat_ugn/gnat_project_manager id31}@anchor{189}
19324 @subsection Performance improvements in builder
19327 The loading of aggregate projects is optimized in @emph{gprbuild},
19328 so that all files are searched for only once on the disk
19329 (thus reducing the number of system calls and contributing to faster
19330 compilation times, especially on systems with sources on remote
19331 servers). As part of the loading, @emph{gprbuild}
19332 computes how and where a source file should be compiled, and even if it is
19333 found several times in the aggregated projects it will be compiled only
19336 Since there is no ambiguity as to which switches should be used, files
19337 can be compiled in parallel (through the usual -j switch) and this can
19338 be done while maximizing the use of CPUs (compared to launching
19339 multiple @emph{gprbuild} commands in parallel).
19341 @node Syntax of aggregate projects,package Builder in aggregate projects,Performance improvements in builder,Aggregate Projects
19342 @anchor{gnat_ugn/gnat_project_manager id32}@anchor{18a}@anchor{gnat_ugn/gnat_project_manager syntax-of-aggregate-projects}@anchor{18b}
19343 @subsection Syntax of aggregate projects
19346 An aggregate project follows the general syntax of project files. The
19347 recommended extension is still @code{.gpr}. However, a special
19348 @cite{aggregate} qualifier must be put before the keyword
19351 An aggregate project cannot @emph{with} any other project (standard or
19352 aggregate), except an abstract project which can be used to share attribute
19353 values. Also, aggregate projects cannot be extended or imported though a
19354 @emph{with} clause by any other project. Building other aggregate projects from
19355 an aggregate project is done through the Project_Files attribute (see below).
19357 An aggregate project does not have any source files directly (only
19358 through other standard projects). Therefore a number of the standard
19359 attributes and packages are forbidden in an aggregate project. Here is the
19360 (non exhaustive) list:
19369 Source_Files, Source_List_File and other attributes dealing with
19373 Source_Dirs, Exec_Dir and Object_Dir
19376 Library_Dir, Library_Name and other library-related attributes
19388 Inherit_Source_Path
19391 Excluded_Source_Dirs
19394 Locally_Removed_Files
19397 Excluded_Source_Files
19400 Excluded_Source_List_File
19406 The only package that is authorized (albeit optional) is
19407 Builder. Other packages (in particular Compiler, Binder and Linker)
19410 The following three attributes can be used only in an aggregate project:
19412 @geindex Project_Files (GNAT Project Manager)
19414 @strong{Project_Files}:
19418 This attribute is compulsory (or else we are not aggregating any project,
19419 and thus not doing anything). It specifies a list of @code{.gpr} files
19420 that are grouped in the aggregate. The list may be empty. The project
19421 files can be either other aggregate projects, or standard projects. When
19422 grouping standard projects, you can have both the root of a project tree
19423 (and you do not need to specify all its imported projects), and any project
19426 Basically, the idea is to specify all those projects that have
19427 main programs you want to build and link, or libraries you want to
19428 build. You can even specify projects that do not use the Main
19429 attribute nor the @cite{Library_*} attributes, and the result will be to
19430 build all their source files (not just the ones needed by other
19433 The file can include paths (absolute or relative). Paths are relative to
19434 the location of the aggregate project file itself (if you use a base name,
19435 we expect to find the .gpr file in the same directory as the aggregate
19436 project file). The environment variables @cite{ADA_PROJECT_PATH},
19437 @cite{GPR_PROJECT_PATH} and @cite{GPR_PROJECT_PATH_FILE} are not used to find
19438 the project files. The extension @code{.gpr} is mandatory, since this attribute
19439 contains file names, not project names.
19441 Paths can also include the @cite{"*"} and @cite{"**"} globbing patterns. The
19442 latter indicates that any subdirectory (recursively) will be
19443 searched for matching files. The latter (@cite{"**"}) can only occur at the
19444 last position in the directory part (ie @cite{"a/**/*.gpr"} is supported, but
19445 not @cite{"**/a/*.gpr"}). Starting the pattern with @cite{"**"} is equivalent
19446 to starting with @cite{"./**"}.
19448 For now, the pattern @cite{"*"} is only allowed in the filename part, not
19449 in the directory part. This is mostly for efficiency reasons to limit the
19450 number of system calls that are needed.
19452 Here are a few valid examples:
19455 for Project_Files use ("a.gpr", "subdir/b.gpr");
19456 -- two specific projects relative to the directory of agg.gpr
19458 for Project_Files use ("/.gpr");
19459 -- all projects recursively
19463 @geindex Project_Path (GNAT Project Manager)
19465 @strong{Project_Path}:
19469 This attribute can be used to specify a list of directories in
19470 which to look for project files in @emph{with} declarations.
19472 When you specify a project in Project_Files (say @cite{x/y/a.gpr}), and
19473 @cite{a.gpr} imports a project @cite{b.gpr}, only @cite{b.gpr} is searched in
19474 the project path. @cite{a.gpr} must be exactly at
19475 @cite{<dir of the aggregate>/x/y/a.gpr}.
19477 This attribute, however, does not affect the search for the aggregated
19478 project files specified with @cite{Project_Files}.
19480 Each aggregate project has its own @cite{Project_Path} (that is if
19481 @cite{agg1.gpr} includes @cite{agg2.gpr}, they can potentially both have a
19482 different @cite{Project_Path}).
19484 This project path is defined as the concatenation, in that order, of:
19490 the current directory;
19493 followed by the command line -aP switches;
19496 then the directories from the GPR_PROJECT_PATH and ADA_PROJECT_PATH environment
19500 then the directories from the Project_Path attribute;
19503 and finally the predefined directories.
19506 In the example above, agg2.gpr's project path is not influenced by
19507 the attribute agg1'Project_Path, nor is agg1 influenced by
19510 This can potentially lead to errors. Consider the following example:
19514 -- +---------------+ +----------------+
19515 -- | Agg1.gpr |-=--includes--=-->| Agg2.gpr |
19516 -- | 'project_path| | 'project_path |
19518 -- +---------------+ +----------------+
19520 -- includes includes
19523 -- +-------+ +---------+
19524 -- | P.gpr |<---------- withs --------| Q.gpr |
19525 -- +-------+---------\ +---------+
19530 -- +-------+ +---------+
19531 -- | R.gpr | | R'.gpr |
19532 -- +-------+ +---------+
19535 When looking for p.gpr, both aggregates find the same physical file on
19536 the disk. However, it might happen that with their different project
19537 paths, both aggregate projects would in fact find a different r.gpr.
19538 Since we have a common project (p.gpr) "with"ing two different r.gpr,
19539 this will be reported as an error by the builder.
19541 Directories are relative to the location of the aggregate project file.
19546 for Project_Path use ("/usr/local/gpr", "gpr/");
19550 @geindex External (GNAT Project Manager)
19556 This attribute can be used to set the value of environment
19557 variables as retrieved through the @cite{external} function
19558 in projects. It does not affect the environment variables
19559 themselves (so for instance you cannot use it to change the value
19560 of your PATH as seen from the spawned compiler).
19562 This attribute affects the external values as seen in the rest of
19563 the aggregate project, and in the aggregated projects.
19565 The exact value of external a variable comes from one of three
19566 sources (each level overrides the previous levels):
19572 An External attribute in aggregate project, for instance
19573 @cite{for External ("BUILD_MODE") use "DEBUG"};
19576 Environment variables.
19577 These override the value given by the attribute, so that
19578 users can override the value set in the (presumably shared
19579 with others team members) aggregate project.
19582 The -X command line switch to @emph{gprbuild}.
19583 This always takes precedence.
19586 This attribute is only taken into account in the main aggregate
19587 project (i.e. the one specified on the command line to @emph{gprbuild}),
19588 and ignored in other aggregate projects. It is invalid
19589 in standard projects.
19590 The goal is to have a consistent value in all
19591 projects that are built through the aggregate, which would not
19592 be the case in the diamond case: A groups the aggregate
19593 projects B and C, which both (either directly or indirectly)
19594 build the project P. If B and C could set different values for
19595 the environment variables, we would have two different views of
19596 P, which in particular might impact the list of source files in P.
19599 @node package Builder in aggregate projects,,Syntax of aggregate projects,Aggregate Projects
19600 @anchor{gnat_ugn/gnat_project_manager package-builder-in-aggregate-projects}@anchor{18c}@anchor{gnat_ugn/gnat_project_manager id33}@anchor{18d}
19601 @subsection package Builder in aggregate projects
19604 As mentioned above, only the package Builder can be specified in
19605 an aggregate project. In this package, only the following attributes
19608 @geindex Switches (GNAT Project Manager)
19614 This attribute gives the list of switches to use for @emph{gprbuild}.
19615 Because no mains can be specified for aggregate projects, the only possible
19616 index for attribute @cite{Switches} is @cite{others}. All other indexes will
19622 for Switches (others) use ("-v", "-k", "-j8");
19625 These switches are only read from the main aggregate project (the
19626 one passed on the command line), and ignored in all other aggregate
19627 projects or projects.
19629 It can only contain builder switches, not compiler switches.
19632 @geindex Global_Compilation_Switches (GNAT Project Manager)
19634 @strong{Global_Compilation_Switches}
19638 This attribute gives the list of compiler switches for the various
19639 languages. For instance,
19642 for Global_Compilation_Switches ("Ada") use ("O1", "-g");
19643 for Global_Compilation_Switches ("C") use ("-O2");
19646 This attribute is only taken into account in the aggregate project
19647 specified on the command line, not in other aggregate projects.
19649 In the projects grouped by that aggregate, the attribute
19650 Builder.Global_Compilation_Switches is also ignored. However, the
19651 attribute Compiler.Default_Switches will be taken into account (but
19652 that of the aggregate have higher priority). The attribute
19653 Compiler.Switches is also taken into account and can be used to
19654 override the switches for a specific file. As a result, it always
19657 The rules are meant to avoid ambiguities when compiling. For
19658 instance, aggregate project Agg groups the projects A and B, that
19659 both depend on C. Here is an extra for all of these projects:
19662 aggregate project Agg is
19663 for Project_Files use ("a.gpr", "b.gpr");
19665 for Global_Compilation_Switches ("Ada") use ("-O2");
19672 for Global_Compilation_Switches ("Ada") use ("-O1");
19676 package Compiler is
19677 for Default_Switches ("Ada")
19679 for Switches ("a_file1.adb")
19686 package Compiler is
19687 for Default_Switches ("Ada") use ("-O0");
19692 package Compiler is
19693 for Default_Switches ("Ada")
19696 for Switches ("c_file1.adb")
19702 then the following switches are used:
19708 all files from project A except a_file1.adb are compiled
19709 with "-O2 -g", since the aggregate project has priority.
19712 the file a_file1.adb is compiled with
19713 "-O0", since the Compiler.Switches has priority
19716 all files from project B are compiled with
19717 "-O2", since the aggregate project has priority
19720 all files from C are compiled with "-O2 -gnatn", except for
19721 c_file1.adb which is compiled with "-O0 -g"
19724 Even though C is seen through two paths (through A and through
19725 B), the switches used by the compiler are unambiguous.
19728 @geindex Global_Configuration_Pragmas (GNAT Project Manager)
19730 @strong{Global_Configuration_Pragmas}
19734 This attribute can be used to specify a file containing
19735 configuration pragmas, to be passed to the Ada compiler. Since we
19736 ignore the package Builder in other aggregate projects and projects,
19737 only those pragmas defined in the main aggregate project will be
19738 taken into account.
19740 Projects can locally add to those by using the
19741 @cite{Compiler.Local_Configuration_Pragmas} attribute if they need.
19744 @geindex Global_Config_File (GNAT Project Manager)
19746 @strong{Global_Config_File}
19750 This attribute, indexed with a language name, can be used to specify a config
19751 when compiling sources of the language. For Ada, these files are configuration
19755 For projects that are built through the aggregate, the package Builder
19756 is ignored, except for the Executable attribute which specifies the
19757 name of the executables resulting from the link of the main programs, and
19758 for the Executable_Suffix.
19760 @node Aggregate Library Projects,Project File Reference,Aggregate Projects,GNAT Project Manager
19761 @anchor{gnat_ugn/gnat_project_manager id34}@anchor{18e}@anchor{gnat_ugn/gnat_project_manager aggregate-library-projects}@anchor{18f}
19762 @section Aggregate Library Projects
19765 Aggregate library projects make it possible to build a single library
19766 using object files built using other standard or library
19767 projects. This gives the flexibility to describe an application as
19768 having multiple modules (a GUI, database access, ...) using different
19769 project files (so possibly built with different compiler options) and
19770 yet create a single library (static or relocatable) out of the
19771 corresponding object files.
19774 * Building aggregate library projects::
19775 * Syntax of aggregate library projects::
19779 @node Building aggregate library projects,Syntax of aggregate library projects,,Aggregate Library Projects
19780 @anchor{gnat_ugn/gnat_project_manager building-aggregate-library-projects}@anchor{190}@anchor{gnat_ugn/gnat_project_manager id35}@anchor{191}
19781 @subsection Building aggregate library projects
19784 For example, we can define an aggregate project Agg that groups A, B
19788 aggregate library project Agg is
19789 for Project_Files use ("a.gpr", "b.gpr", "c.gpr");
19790 for Library_Name use ("agg");
19791 for Library_Dir use ("lagg");
19795 Then, when you build with:
19801 This will build all units from projects A, B and C and will create a
19802 static library named @code{libagg.a} in the @code{lagg}
19803 directory. An aggregate library project has the same set of
19804 restriction as a standard library project.
19806 Note that a shared aggregate library project cannot aggregate a
19807 static library project. In platforms where a compiler option is
19808 required to create relocatable object files, a Builder package in the
19809 aggregate library project may be used:
19812 aggregate library project Agg is
19813 for Project_Files use ("a.gpr", "b.gpr", "c.gpr");
19814 for Library_Name use ("agg");
19815 for Library_Dir use ("lagg");
19816 for Library_Kind use "relocatable";
19819 for Global_Compilation_Switches ("Ada") use ("-fPIC");
19824 With the above aggregate library Builder package, the @cite{-fPIC}
19825 option will be passed to the compiler when building any source code
19826 from projects @code{a.gpr}, @code{b.gpr} and @code{c.gpr}.
19828 @node Syntax of aggregate library projects,,Building aggregate library projects,Aggregate Library Projects
19829 @anchor{gnat_ugn/gnat_project_manager syntax-of-aggregate-library-projects}@anchor{192}@anchor{gnat_ugn/gnat_project_manager id36}@anchor{193}
19830 @subsection Syntax of aggregate library projects
19833 An aggregate library project follows the general syntax of project
19834 files. The recommended extension is still @code{.gpr}. However, a special
19835 @cite{aggregate library} qualifier must be put before the keyword
19838 An aggregate library project cannot @emph{with} any other project
19839 (standard or aggregate), except an abstract project which can be used
19840 to share attribute values.
19842 An aggregate library project does not have any source files directly (only
19843 through other standard projects). Therefore a number of the standard
19844 attributes and packages are forbidden in an aggregate library
19845 project. Here is the (non exhaustive) list:
19854 Source_Files, Source_List_File and other attributes dealing with
19858 Source_Dirs, Exec_Dir and Object_Dir
19870 Inherit_Source_Path
19873 Excluded_Source_Dirs
19876 Locally_Removed_Files
19879 Excluded_Source_Files
19882 Excluded_Source_List_File
19888 The only package that is authorized (albeit optional) is Builder.
19890 The Project_Files attribute (See @ref{16e,,Aggregate Projects}) is used to
19891 described the aggregated projects whose object files have to be
19892 included into the aggregate library. The environment variables
19893 @cite{ADA_PROJECT_PATH}, @cite{GPR_PROJECT_PATH} and
19894 @cite{GPR_PROJECT_PATH_FILE} are not used to find the project files.
19896 @node Project File Reference,,Aggregate Library Projects,GNAT Project Manager
19897 @anchor{gnat_ugn/gnat_project_manager id37}@anchor{194}@anchor{gnat_ugn/gnat_project_manager project-file-reference}@anchor{14d}
19898 @section Project File Reference
19901 This section describes the syntactic structure of project files, the various
19902 constructs that can be used. Finally, it ends with a summary of all available
19906 * Project Declaration::
19907 * Qualified Projects::
19911 * External Values::
19912 * Typed String Declaration::
19914 * Case Constructions::
19919 @node Project Declaration,Qualified Projects,,Project File Reference
19920 @anchor{gnat_ugn/gnat_project_manager id38}@anchor{195}@anchor{gnat_ugn/gnat_project_manager project-declaration}@anchor{196}
19921 @subsection Project Declaration
19924 Project files have an Ada-like syntax. The minimal project file is:
19931 The identifier @cite{Empty} is the name of the project.
19932 This project name must be present after the reserved
19933 word @cite{end} at the end of the project file, followed by a semi-colon.
19935 @strong{Identifiers} (i.e., the user-defined names such as project or variable names)
19936 have the same syntax as Ada identifiers: they must start with a letter,
19937 and be followed by zero or more letters, digits or underscore characters;
19938 it is also illegal to have two underscores next to each other. Identifiers
19939 are always case-insensitive ("Name" is the same as "name").
19942 simple_name ::= identifier
19943 name ::= simple_name @{ . simple_name @}
19946 @strong{Strings} are used for values of attributes or as indexes for these
19947 attributes. They are in general case sensitive, except when noted
19948 otherwise (in particular, strings representing file names will be case
19949 insensitive on some systems, so that "file.adb" and "File.adb" both
19950 represent the same file).
19952 @strong{Reserved words} are the same as for standard Ada 95, and cannot
19953 be used for identifiers. In particular, the following words are currently
19954 used in project files, but others could be added later on. In bold are the
19955 extra reserved words in project files:
19956 @code{all}, @code{at}, @code{case}, @code{end}, @code{for}, @code{is}, @code{limited},
19957 @code{null}, @code{others}, @code{package}, @code{renames}, @code{type}, @code{use}, @code{when},
19958 @code{with}, @strong{extends}, @strong{external}, @strong{project}.
19960 @strong{Comments} in project files have the same syntax as in Ada, two consecutive
19961 hyphens through the end of the line.
19963 A project may be an @strong{independent project}, entirely defined by a single
19964 project file. Any source file in an independent project depends only
19965 on the predefined library and other source files in the same project.
19966 But a project may also depend on other projects, either by importing them
19967 through @strong{with clauses}, or by @strong{extending} at most one other project. Both
19968 types of dependency can be used in the same project.
19970 A path name denotes a project file. It can be absolute or relative.
19971 An absolute path name includes a sequence of directories, in the syntax of
19972 the host operating system, that identifies uniquely the project file in the
19973 file system. A relative path name identifies the project file, relative
19974 to the directory that contains the current project, or relative to a
19975 directory listed in the environment variables ADA_PROJECT_PATH and
19976 GPR_PROJECT_PATH. Path names are case sensitive if file names in the host
19977 operating system are case sensitive. As a special case, the directory
19978 separator can always be "/" even on Windows systems, so that project files
19979 can be made portable across architectures.
19980 The syntax of the environment variables ADA_PROJECT_PATH and
19981 GPR_PROJECT_PATH is a list of directory names separated by colons on UNIX and
19982 semicolons on Windows.
19984 A given project name can appear only once in a context clause.
19986 It is illegal for a project imported by a context clause to refer, directly
19987 or indirectly, to the project in which this context clause appears (the
19988 dependency graph cannot contain cycles), except when one of the with clauses
19989 in the cycle is a @strong{limited with}.
19992 with "other_project.gpr";
19993 project My_Project extends "extended.gpr" is
19997 These dependencies form a @strong{directed graph}, potentially cyclic when using
19998 @strong{limited with}. The subgraph reflecting the @strong{extends} relations is a tree.
20000 A project's @strong{immediate sources} are the source files directly defined by
20001 that project, either implicitly by residing in the project source directories,
20002 or explicitly through any of the source-related attributes.
20003 More generally, a project's @strong{sources} are the immediate sources of the
20004 project together with the immediate sources (unless overridden) of any project
20005 on which it depends directly or indirectly.
20007 A @strong{project hierarchy} can be created, where projects are children of
20008 other projects. The name of such a child project must be @cite{Parent.Child},
20009 where @cite{Parent} is the name of the parent project. In particular, this
20010 makes all @emph{with} clauses of the parent project automatically visible
20011 in the child project.
20014 project ::= context_clause project_declaration
20016 context_clause ::= @{with_clause@}
20017 with_clause ::= *with* path_name @{ , path_name @} ;
20018 path_name ::= string_literal
20020 project_declaration ::= simple_project_declaration | project_extension
20021 simple_project_declaration ::=
20022 project <project_>name is
20023 @{declarative_item@}
20024 end <project_>simple_name;
20027 @node Qualified Projects,Declarations,Project Declaration,Project File Reference
20028 @anchor{gnat_ugn/gnat_project_manager qualified-projects}@anchor{173}@anchor{gnat_ugn/gnat_project_manager id39}@anchor{197}
20029 @subsection Qualified Projects
20032 Before the reserved @cite{project}, there may be one or two @strong{qualifiers}, that
20033 is identifiers or reserved words, to qualify the project.
20034 The current list of qualifiers is:
20039 @item @strong{abstract}:
20041 Qualifies a project with no sources.
20042 Such a project must either have no declaration of attributes @cite{Source_Dirs},
20043 @cite{Source_Files}, @cite{Languages} or @cite{Source_List_File}, or one of
20044 @cite{Source_Dirs}, @cite{Source_Files}, or @cite{Languages} must be declared
20045 as empty. If it extends another project, the project it extends must also be a
20046 qualified abstract project.
20048 @item @strong{standard}:
20050 A standard project is a non library project with sources.
20051 This is the default (implicit) qualifier.
20053 @item @strong{aggregate}:
20055 A project whose sources are aggregated from other project files.
20057 @item @strong{aggregate library}:
20059 A library whose sources are aggregated from other project
20060 or library project files.
20062 @item @strong{library}:
20064 A library project must declare both attributes
20065 Library_Name` and @cite{Library_Dir}.
20067 @item @strong{configuration}:
20069 A configuration project cannot be in a project tree.
20070 It describes compilers and other tools to @emph{gprbuild}.
20073 @node Declarations,Packages,Qualified Projects,Project File Reference
20074 @anchor{gnat_ugn/gnat_project_manager declarations}@anchor{198}@anchor{gnat_ugn/gnat_project_manager id40}@anchor{199}
20075 @subsection Declarations
20078 Declarations introduce new entities that denote types, variables, attributes,
20079 and packages. Some declarations can only appear immediately within a project
20080 declaration. Others can appear within a project or within a package.
20083 declarative_item ::= simple_declarative_item
20084 | typed_string_declaration
20085 | package_declaration
20087 simple_declarative_item ::= variable_declaration
20088 | typed_variable_declaration
20089 | attribute_declaration
20090 | case_construction
20091 | empty_declaration
20093 empty_declaration ::= *null* ;
20096 An empty declaration is allowed anywhere a declaration is allowed. It has
20099 @node Packages,Expressions,Declarations,Project File Reference
20100 @anchor{gnat_ugn/gnat_project_manager packages}@anchor{153}@anchor{gnat_ugn/gnat_project_manager id41}@anchor{19a}
20101 @subsection Packages
20104 A project file may contain @strong{packages}, that group attributes (typically
20105 all the attributes that are used by one of the GNAT tools).
20107 A package with a given name may only appear once in a project file.
20108 The following packages are currently supported in project files
20109 (See @ref{152,,Attributes} for the list of attributes that each can contain).
20114 @item @emph{Binder}
20116 This package specifies characteristics useful when invoking the binder either
20117 directly via the @emph{gnat} driver or when using @emph{gprbuild}.
20118 See @ref{15d,,Main Subprograms}.
20120 @item @emph{Builder}
20122 This package specifies the compilation options used when building an
20123 executable or a library for a project. Most of the options should be
20124 set in one of @cite{Compiler}, @cite{Binder} or @cite{Linker} packages,
20125 but there are some general options that should be defined in this
20126 package. See @ref{15d,,Main Subprograms}, and @ref{162,,Executable File Names} in
20136 This package specifies the options used when cleaning a project or a project
20137 tree using the tools @emph{gnatclean} or @emph{gprclean}.
20139 @item @emph{Compiler}
20141 This package specifies the compilation options used by the compiler for
20142 each languages. See @ref{15e,,Tools Options in Project Files}.
20144 @item @emph{Cross_Reference}
20146 This package specifies the options used when calling the library tool
20147 @emph{gnatxref} via the @emph{gnat} driver. Its attributes
20148 @strong{Default_Switches} and @strong{Switches} have the same semantics as for the
20149 package @cite{Builder}.
20156 @item @emph{Finder}
20158 This package specifies the options used when calling the search tool
20159 @emph{gnatfind} via the @emph{gnat} driver. Its attributes
20160 @strong{Default_Switches} and @strong{Switches} have the same semantics as for the
20161 package @cite{Builder}.
20163 @item @emph{Gnatls}
20165 This package specifies the options to use when invoking @emph{gnatls}
20166 via the @emph{gnat} driver.
20175 This package specifies the options used when starting an integrated
20176 development environment, for instance @emph{GPS} or @emph{Gnatbench}.
20178 @item @emph{Install}
20180 This package specifies the options used when installing a project
20181 with @emph{gprinstall}. See @ref{168,,Installation}.
20183 @item @emph{Linker}
20185 This package specifies the options used by the linker.
20186 See @ref{15d,,Main Subprograms}.
20193 @item @emph{Naming}
20197 This package specifies the naming conventions that apply
20198 to the source files in a project. In particular, these conventions are
20199 used to automatically find all source files in the source directories,
20200 or given a file name to find out its language for proper processing.
20201 See @ref{14b,,Naming Schemes}.
20204 @c only: PRO or GPL
20206 @c *Pretty_Printer*
20207 @c This package specifies the options used when calling the formatting tool
20208 @c *gnatpp* via the *gnat* driver. Its attributes
20209 @c **Default_Switches** and **Switches** have the same semantics as for the
20210 @c package `Builder`.
20212 @item @emph{Remote}
20214 This package is used by @emph{gprbuild} to describe how distributed
20215 compilation should be done.
20219 This package specifies the options used when calling the tool
20220 @emph{gnatstack} via the @emph{gnat} driver. Its attributes
20221 @strong{Default_Switches} and @strong{Switches} have the same semantics as for the
20222 package @cite{Builder}.
20224 @item @emph{Synchronize}
20226 This package specifies the options used when calling the tool
20227 @emph{gnatsync} via the @emph{gnat} driver.
20230 In its simplest form, a package may be empty:
20239 A package may contain @strong{attribute declarations},
20240 @strong{variable declarations} and @strong{case constructions}, as will be
20243 When there is ambiguity between a project name and a package name,
20244 the name always designates the project. To avoid possible confusion, it is
20245 always a good idea to avoid naming a project with one of the
20246 names allowed for packages or any name that starts with @cite{gnat}.
20248 A package can also be defined by a @strong{renaming declaration}. The new package
20249 renames a package declared in a different project file, and has the same
20250 attributes as the package it renames. The name of the renamed package
20251 must be the same as the name of the renaming package. The project must
20252 contain a package declaration with this name, and the project
20253 must appear in the context clause of the current project, or be its parent
20254 project. It is not possible to add or override attributes to the renaming
20255 project. If you need to do so, you should use an @strong{extending declaration}
20258 Packages that are renamed in other project files often come from project files
20259 that have no sources: they are just used as templates. Any modification in the
20260 template will be reflected automatically in all the project files that rename
20261 a package from the template. This is a very common way to share settings
20264 Finally, a package can also be defined by an @strong{extending declaration}. This is
20265 similar to a @strong{renaming declaration}, except that it is possible to add or
20266 override attributes.
20269 package_declaration ::= package_spec | package_renaming | package_extension
20271 package <package_>simple_name is
20272 @{simple_declarative_item@}
20273 end package_identifier ;
20274 package_renaming ::==
20275 package <package_>simple_name renames <project_>simple_name.package_identifier ;
20276 package_extension ::==
20277 package <package_>simple_name extends <project_>simple_name.package_identifier is
20278 @{simple_declarative_item@}
20279 end package_identifier ;
20282 @node Expressions,External Values,Packages,Project File Reference
20283 @anchor{gnat_ugn/gnat_project_manager expressions}@anchor{19b}@anchor{gnat_ugn/gnat_project_manager id42}@anchor{19c}
20284 @subsection Expressions
20287 An expression is any value that can be assigned to an attribute or a
20288 variable. It is either a literal value, or a construct requiring runtime
20289 computation by the project manager. In a project file, the computed value of
20290 an expression is either a string or a list of strings.
20292 A string value is one of:
20298 A literal string, for instance @cite{"comm/my_proj.gpr"}
20301 The name of a variable that evaluates to a string (see @ref{155,,Variables})
20304 The name of an attribute that evaluates to a string (see @ref{152,,Attributes})
20307 An external reference (see @ref{154,,External Values})
20310 A concatenation of the above, as in @cite{"prefix_" & Var}.
20313 A list of strings is one of the following:
20319 A parenthesized comma-separated list of zero or more string expressions, for
20320 instance @cite{(File_Name@comma{} "gnat.adc"@comma{} File_Name & ".orig")} or @cite{()}.
20323 The name of a variable that evaluates to a list of strings
20326 The name of an attribute that evaluates to a list of strings
20329 A concatenation of a list of strings and a string (as defined above), for
20330 instance @cite{("A"@comma{} "B") & "C"}
20333 A concatenation of two lists of strings
20336 The following is the grammar for expressions
20339 string_literal ::= "@{string_element@}" -- Same as Ada
20340 string_expression ::= string_literal
20343 | attribute_reference
20344 | ( string_expression @{ & string_expression @} )
20345 string_list ::= ( string_expression @{ , string_expression @} )
20346 | *string_variable*_name
20347 | *string_*attribute_reference
20348 term ::= string_expression | string_list
20349 expression ::= term @{ & term @} -- Concatenation
20352 Concatenation involves strings and list of strings. As soon as a list of
20353 strings is involved, the result of the concatenation is a list of strings. The
20354 following Ada declarations show the existing operators:
20357 function "&" (X : String; Y : String) return String;
20358 function "&" (X : String_List; Y : String) return String_List;
20359 function "&" (X : String_List; Y : String_List) return String_List;
20362 Here are some specific examples:
20365 List := () & File_Name; -- One string in this list
20366 List2 := List & (File_Name & ".orig"); -- Two strings
20367 Big_List := List & Lists2; -- Three strings
20368 Illegal := "gnat.adc" & List2; -- Illegal, must start with list
20371 @node External Values,Typed String Declaration,Expressions,Project File Reference
20372 @anchor{gnat_ugn/gnat_project_manager external-values}@anchor{154}@anchor{gnat_ugn/gnat_project_manager id43}@anchor{19d}
20373 @subsection External Values
20376 An external value is an expression whose value is obtained from the command
20377 that invoked the processing of the current project file (typically a
20378 @emph{gprbuild} command).
20380 There are two kinds of external values, one that returns a single string, and
20381 one that returns a string list.
20383 The syntax of a single string external value is:
20386 external_value ::= *external* ( string_literal [, string_literal] )
20389 The first string_literal is the string to be used on the command line or
20390 in the environment to specify the external value. The second string_literal,
20391 if present, is the default to use if there is no specification for this
20392 external value either on the command line or in the environment.
20394 Typically, the external value will either exist in the
20395 environment variables
20396 or be specified on the command line through the
20397 @code{-X@emph{vbl}=@emph{value}} switch. If both
20398 are specified, then the command line value is used, so that a user can more
20399 easily override the value.
20401 The function @cite{external} always returns a string. It is an error if the
20402 value was not found in the environment and no default was specified in the
20403 call to @cite{external}.
20405 An external reference may be part of a string expression or of a string
20406 list expression, and can therefore appear in a variable declaration or
20407 an attribute declaration.
20409 Most of the time, this construct is used to initialize typed variables, which
20410 are then used in @strong{case} constructions to control the value assigned to
20411 attributes in various scenarios. Thus such variables are often called
20412 @strong{scenario variables}.
20414 The syntax for a string list external value is:
20417 external_value ::= *external_as_list* ( string_literal , string_literal )
20420 The first string_literal is the string to be used on the command line or
20421 in the environment to specify the external value. The second string_literal is
20422 the separator between each component of the string list.
20424 If the external value does not exist in the environment or on the command line,
20425 the result is an empty list. This is also the case, if the separator is an
20426 empty string or if the external value is only one separator.
20428 Any separator at the beginning or at the end of the external value is
20429 discarded. Then, if there is no separator in the external value, the result is
20430 a string list with only one string. Otherwise, any string between the beginning
20431 and the first separator, between two consecutive separators and between the
20432 last separator and the end are components of the string list.
20435 *external_as_list* ("SWITCHES", ",")
20438 If the external value is "-O2,-g",
20439 the result is ("-O2", "-g").
20441 If the external value is ",-O2,-g,",
20442 the result is also ("-O2", "-g").
20444 if the external value is "-gnatv",
20445 the result is ("-gnatv").
20447 If the external value is ",,", the result is ("").
20449 If the external value is ",", the result is (), the empty string list.
20451 @node Typed String Declaration,Variables,External Values,Project File Reference
20452 @anchor{gnat_ugn/gnat_project_manager id44}@anchor{19e}@anchor{gnat_ugn/gnat_project_manager typed-string-declaration}@anchor{19f}
20453 @subsection Typed String Declaration
20456 A @strong{type declaration} introduces a discrete set of string literals.
20457 If a string variable is declared to have this type, its value
20458 is restricted to the given set of literals. These are the only named
20459 types in project files. A string type may only be declared at the project
20460 level, not inside a package.
20463 typed_string_declaration ::=
20464 *type* *<typed_string_>*_simple_name *is* ( string_literal @{, string_literal@} );
20467 The string literals in the list are case sensitive and must all be different.
20468 They may include any graphic characters allowed in Ada, including spaces.
20469 Here is an example of a string type declaration:
20472 type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
20475 Variables of a string type are called @strong{typed variables}; all other
20476 variables are called @strong{untyped variables}. Typed variables are
20477 particularly useful in @cite{case} constructions, to support conditional
20478 attribute declarations. (See @ref{1a0,,Case Constructions}).
20480 A string type may be referenced by its name if it has been declared in the same
20481 project file, or by an expanded name whose prefix is the name of the project
20482 in which it is declared.
20484 @node Variables,Case Constructions,Typed String Declaration,Project File Reference
20485 @anchor{gnat_ugn/gnat_project_manager variables}@anchor{155}@anchor{gnat_ugn/gnat_project_manager id45}@anchor{1a1}
20486 @subsection Variables
20489 @strong{Variables} store values (strings or list of strings) and can appear
20490 as part of an expression. The declaration of a variable creates the
20491 variable and assigns the value of the expression to it. The name of the
20492 variable is available immediately after the assignment symbol, if you
20493 need to reuse its old value to compute the new value. Before the completion
20494 of its first declaration, the value of a variable defaults to the empty
20497 A @strong{typed} variable can be used as part of a @strong{case} expression to
20498 compute the value, but it can only be declared once in the project file,
20499 so that all case constructions see the same value for the variable. This
20500 provides more consistency and makes the project easier to understand.
20501 The syntax for its declaration is identical to the Ada syntax for an
20502 object declaration. In effect, a typed variable acts as a constant.
20504 An @strong{untyped} variable can be declared and overridden multiple times
20505 within the same project. It is declared implicitly through an Ada
20506 assignment. The first declaration establishes the kind of the variable
20507 (string or list of strings) and successive declarations must respect
20508 the initial kind. Assignments are executed in the order in which they
20509 appear, so the new value replaces the old one and any subsequent reference
20510 to the variable uses the new value.
20512 A variable may be declared at the project file level, or within a package.
20515 typed_variable_declaration ::=
20516 *<typed_variable_>*simple_name : *<typed_string_>*name := string_expression;
20518 variable_declaration ::= *<variable_>*simple_name := expression;
20521 Here are some examples of variable declarations:
20524 This_OS : OS := external ("OS"); -- a typed variable declaration
20525 That_OS := "GNU/Linux"; -- an untyped variable declaration
20527 Name := "readme.txt";
20528 Save_Name := Name & ".saved";
20531 List_With_One_Element := ("-gnaty");
20532 List_With_Two_Elements := List_With_One_Element & "-gnatg";
20533 Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada");
20536 A @strong{variable reference} may take several forms:
20542 The simple variable name, for a variable in the current package (if any)
20543 or in the current project
20546 An expanded name, whose prefix is a context name.
20549 A @strong{context} may be one of the following:
20555 The name of an existing package in the current project
20558 The name of an imported project of the current project
20561 The name of an ancestor project (i.e., a project extended by the current
20562 project, either directly or indirectly)
20565 An expanded name whose prefix is an imported/parent project name, and
20566 whose selector is a package name in that project.
20569 @node Case Constructions,Attributes,Variables,Project File Reference
20570 @anchor{gnat_ugn/gnat_project_manager id46}@anchor{1a2}@anchor{gnat_ugn/gnat_project_manager case-constructions}@anchor{1a0}
20571 @subsection Case Constructions
20574 A @strong{case} construction is used in a project file to effect conditional
20575 behavior. Through this construction, you can set the value of attributes
20576 and variables depending on the value previously assigned to a typed
20579 All choices in a choice list must be distinct. Unlike Ada, the choice
20580 lists of all alternatives do not need to include all values of the type.
20581 An @cite{others} choice must appear last in the list of alternatives.
20583 The syntax of a @cite{case} construction is based on the Ada case construction
20584 (although the @cite{null} declaration for empty alternatives is optional).
20586 The case expression must be a string variable, either typed or not, whose value
20587 is often given by an external reference (see @ref{154,,External Values}).
20589 Each alternative starts with the reserved word @cite{when}, either a list of
20590 literal strings separated by the @cite{"|"} character or the reserved word
20591 @cite{others}, and the @cite{"=>"} token.
20592 When the case expression is a typed string variable, each literal string must
20593 belong to the string type that is the type of the case variable.
20594 After each @cite{=>}, there are zero or more declarations. The only
20595 declarations allowed in a case construction are other case constructions,
20596 attribute declarations and variable declarations. String type declarations and
20597 package declarations are not allowed. Variable declarations are restricted to
20598 variables that have already been declared before the case construction.
20601 case_construction ::=
20602 *case* *<variable_>*name *is* @{case_item@} *end case* ;
20605 *when* discrete_choice_list =>
20607 | attribute_declaration
20608 | variable_declaration
20609 | empty_declaration@}
20611 discrete_choice_list ::= string_literal @{| string_literal@} | *others*
20614 Here is a typical example, with a typed string variable:
20618 type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
20619 OS : OS_Type := external ("OS", "GNU/Linux");
20621 package Compiler is
20623 when "GNU/Linux" | "Unix" =>
20624 for Switches ("Ada")
20627 for Switches ("Ada")
20636 @node Attributes,,Case Constructions,Project File Reference
20637 @anchor{gnat_ugn/gnat_project_manager id47}@anchor{1a3}@anchor{gnat_ugn/gnat_project_manager attributes}@anchor{152}
20638 @subsection Attributes
20641 A project (and its packages) may have @strong{attributes} that define
20642 the project's properties. Some attributes have values that are strings;
20643 others have values that are string lists.
20646 attribute_declaration ::=
20647 simple_attribute_declaration | indexed_attribute_declaration
20649 simple_attribute_declaration ::= *for* attribute_designator *use* expression ;
20651 indexed_attribute_declaration ::=
20652 *for* *<indexed_attribute_>*simple_name ( string_literal) *use* expression ;
20654 attribute_designator ::=
20655 *<simple_attribute_>*simple_name
20656 | *<indexed_attribute_>*simple_name ( string_literal )
20659 There are two categories of attributes: @strong{simple attributes}
20660 and @strong{indexed attributes}.
20661 Each simple attribute has a default value: the empty string (for string
20662 attributes) and the empty list (for string list attributes).
20663 An attribute declaration defines a new value for an attribute, and overrides
20664 the previous value. The syntax of a simple attribute declaration is similar to
20665 that of an attribute definition clause in Ada.
20667 Some attributes are indexed. These attributes are mappings whose
20668 domain is a set of strings. They are declared one association
20669 at a time, by specifying a point in the domain and the corresponding image
20671 Like untyped variables and simple attributes, indexed attributes
20672 may be declared several times. Each declaration supplies a new value for the
20673 attribute, and replaces the previous setting.
20675 Here are some examples of attribute declarations:
20678 -- simple attributes
20679 for Object_Dir use "objects";
20680 for Source_Dirs use ("units", "test/drivers");
20682 -- indexed attributes
20683 for Body ("main") use "Main.ada";
20684 for Switches ("main.ada")
20685 use ("-v", "-gnatv");
20686 for Switches ("main.ada") use Builder'Switches ("main.ada") & "-g";
20688 -- indexed attributes copy (from package Builder in project Default)
20689 -- The package name must always be specified, even if it is the current
20691 for Default_Switches use Default.Builder'Default_Switches;
20694 Attributes references may appear anywhere in expressions, and are used
20695 to retrieve the value previously assigned to the attribute. If an attribute
20696 has not been set in a given package or project, its value defaults to the
20697 empty string or the empty list, with some exceptions.
20700 attribute_reference ::=
20701 attribute_prefix ' *<simple_attribute>_*simple_name [ (string_literal) ]
20702 attribute_prefix ::= *project*
20703 | *<project_>*simple_name
20704 | package_identifier
20705 | *<project_>*simple_name . package_identifier
20711 <project>'Object_Dir
20712 Naming'Dot_Replacement
20713 Imported_Project'Source_Dirs
20714 Imported_Project.Naming'Casing
20715 Builder'Default_Switches ("Ada")
20718 The exceptions to the empty defaults are:
20724 Object_Dir: default is "."
20727 Exec_Dir: default is 'Object_Dir, that is the value of attribute
20728 Object_Dir in the same project, declared or defaulted.
20731 Source_Dirs: default is (".")
20734 The prefix of an attribute may be:
20740 @cite{project} for an attribute of the current project
20743 The name of an existing package of the current project
20746 The name of an imported project
20749 The name of a parent project that is extended by the current project
20752 An expanded name whose prefix is imported/parent project name,
20753 and whose selector is a package name
20756 In the following sections, all predefined attributes are succinctly described,
20757 first the project level attributes, that is those attributes that are not in a
20758 package, then the attributes in the different packages.
20760 It is possible for different tools to dynamically create new packages with
20761 attributes, or new attributes in predefined packages. These attributes are
20762 not documented here.
20764 The attributes under Configuration headings are usually found only in
20765 configuration project files.
20767 The characteristics of each attribute are indicated as follows:
20773 @strong{Type of value}
20775 The value of an attribute may be a single string, indicated by the word
20776 "single", or a string list, indicated by the word "list".
20781 When the attribute is read-only, that is when it is not allowed to declare
20782 the attribute, this is indicated by the words "read-only".
20785 @strong{Optional index}
20787 If it is allowed in the value of the attribute (both single and list) to have
20788 an optional index, this is indicated by the words "optional index".
20791 @strong{Indexed attribute}
20793 When it is an indexed attribute, this is indicated by the word "indexed".
20796 @strong{Case-sensitivity of the index}
20798 For an indexed attribute, if the index is case-insensitive, this is indicated
20799 by the words "case-insensitive index".
20802 @strong{File name index}
20804 For an indexed attribute, when the index is a file name, this is indicated by
20805 the words "file name index". The index may or may not be case-sensitive,
20806 depending on the platform.
20809 @strong{others allowed in index}
20811 For an indexed attribute, if it is allowed to use @strong{others} as the index,
20812 this is indicated by the words "others allowed".
20814 When @strong{others} is used as the index of an indexed attribute, the value of
20815 the attribute indexed by @strong{others} is used when no other index would apply.
20819 * Project Level Attributes::
20820 * Package Binder Attributes::
20821 * Package Builder Attributes::
20822 * Package Clean Attributes::
20823 * Package Compiler Attributes::
20824 * Package Cross_Reference Attributes::
20825 * Package Finder Attributes::
20826 * Package gnatls Attributes::
20827 * Package IDE Attributes::
20828 * Package Install Attributes::
20829 * Package Linker Attributes::
20830 * Package Naming Attributes::
20831 * Package Remote Attributes::
20832 * Package Stack Attributes::
20833 * Package Synchronize Attributes::
20837 @node Project Level Attributes,Package Binder Attributes,,Attributes
20838 @anchor{gnat_ugn/gnat_project_manager project-level-attributes}@anchor{1a4}@anchor{gnat_ugn/gnat_project_manager id48}@anchor{1a5}
20839 @subsubsection Project Level Attributes
20852 @strong{Name}: single, read-only
20854 The name of the project.
20857 @strong{Project_Dir}: single, read-only
20859 The path name of the project directory.
20862 @strong{Main}: list, optional index
20864 The list of main sources for the executables.
20867 @strong{Languages}: list
20869 The list of languages of the sources of the project.
20872 @strong{Roots}: list, indexed, file name index
20874 The index is the file name of an executable source. Indicates the list of units
20875 from the main project that need to be bound and linked with their closures
20876 with the executable. The index is either a file name, a language name or "*".
20877 The roots for an executable source are those in @strong{Roots} with an index that
20878 is the executable source file name, if declared. Otherwise, they are those in
20879 @strong{Roots} with an index that is the language name of the executable source,
20880 if present. Otherwise, they are those in @strong{Roots ("*")}, if declared. If none
20881 of these three possibilities are declared, then there are no roots for the
20885 @strong{Externally_Built}: single
20887 Indicates if the project is externally built.
20888 Only case-insensitive values allowed are "true" and "false", the default.
20892 @strong{Directories}
20898 @strong{Object_Dir}: single
20900 Indicates the object directory for the project.
20903 @strong{Exec_Dir}: single
20905 Indicates the exec directory for the project, that is the directory where the
20909 @strong{Source_Dirs}: list
20911 The list of source directories of the project.
20914 @strong{Inherit_Source_Path}: list, indexed, case-insensitive index
20916 Index is a language name. Value is a list of language names. Indicates that
20917 in the source search path of the index language the source directories of
20918 the languages in the list should be included.
20923 for Inherit_Source_Path ("C++") use ("C");
20927 @strong{Exclude_Source_Dirs}: list
20929 The list of directories that are included in Source_Dirs but are not source
20930 directories of the project.
20933 @strong{Ignore_Source_Sub_Dirs}: list
20935 Value is a list of simple names for subdirectories that are removed from the
20936 list of source directories, including theur subdirectories.
20940 @strong{Source Files}
20946 @strong{Source_Files}: list
20948 Value is a list of source file simple names.
20951 @strong{Locally_Removed_Files}: list
20953 Obsolescent. Equivalent to Excluded_Source_Files.
20956 @strong{Excluded_Source_Files}: list
20958 Value is a list of simple file names that are not sources of the project.
20959 Allows to remove sources that are inherited or found in the source directories
20960 and that match the naming scheme.
20963 @strong{Source_List_File}: single
20965 Value is a text file name that contains a list of source file simple names,
20969 @strong{Excluded_Source_List_File}: single
20971 Value is a text file name that contains a list of file simple names that
20972 are not sources of the project.
20975 @strong{Interfaces}: list
20977 Value is a list of file names that constitutes the interfaces of the project.
20981 @strong{Aggregate Projects}
20987 @strong{Project_Files}: list
20989 Value is the list of aggregated projects.
20992 @strong{Project_Path}: list
20994 Value is a list of directories that are added to the project search path when
20995 looking for the aggregated projects.
20998 @strong{External}: single, indexed
21000 Index is the name of an external reference. Value is the value of the
21001 external reference to be used when parsing the aggregated projects.
21011 @strong{Library_Dir}: single
21013 Value is the name of the library directory. This attribute needs to be
21014 declared for each library project.
21017 @strong{Library_Name}: single
21019 Value is the name of the library. This attribute needs to be declared or
21020 inherited for each library project.
21023 @strong{Library_Kind}: single
21025 Specifies the kind of library: static library (archive) or shared library.
21026 Case-insensitive values must be one of "static" for archives (the default) or
21027 "dynamic" or "relocatable" for shared libraries.
21030 @strong{Library_Version}: single
21032 Value is the name of the library file.
21035 @strong{Library_Interface}: list
21037 Value is the list of unit names that constitutes the interfaces
21038 of a Stand-Alone Library project.
21041 @strong{Library_Standalone}: single
21043 Specifies if a Stand-Alone Library (SAL) is encapsulated or not.
21044 Only authorized case-insensitive values are "standard" for non encapsulated
21045 SALs, "encapsulated" for encapsulated SALs or "no" for non SAL library project.
21048 @strong{Library_Encapsulated_Options}: list
21050 Value is a list of options that need to be used when linking an encapsulated
21051 Stand-Alone Library.
21054 @strong{Library_Encapsulated_Supported}: single
21056 Indicates if encapsulated Stand-Alone Libraries are supported. Only
21057 authorized case-insensitive values are "true" and "false" (the default).
21060 @strong{Library_Auto_Init}: single
21062 Indicates if a Stand-Alone Library is auto-initialized. Only authorized
21063 case-insentive values are "true" and "false".
21066 @strong{Leading_Library_Options}: list
21068 Value is a list of options that are to be used at the beginning of
21069 the command line when linking a shared library.
21072 @strong{Library_Options}: list
21074 Value is a list of options that are to be used when linking a shared library.
21077 @strong{Library_Rpath_Options}: list, indexed, case-insensitive index
21079 Index is a language name. Value is a list of options for an invocation of the
21080 compiler of the language. This invocation is done for a shared library project
21081 with sources of the language. The output of the invocation is the path name
21082 of a shared library file. The directory name is to be put in the run path
21083 option switch when linking the shared library for the project.
21086 @strong{Library_Src_Dir}: single
21088 Value is the name of the directory where copies of the sources of the
21089 interfaces of a Stand-Alone Library are to be copied.
21092 @strong{Library_ALI_Dir}: single
21094 Value is the name of the directory where the ALI files of the interfaces
21095 of a Stand-Alone Library are to be copied. When this attribute is not declared,
21096 the directory is the library directory.
21099 @strong{Library_gcc}: single
21101 Obsolescent attribute. Specify the linker driver used to link a shared library.
21102 Use instead attribute Linker'Driver.
21105 @strong{Library_Symbol_File}: single
21107 Value is the name of the library symbol file.
21110 @strong{Library_Symbol_Policy}: single
21112 Indicates the symbol policy kind. Only authorized case-insensitive values are
21113 "autonomous", "default", "compliant", "controlled" or "direct".
21116 @strong{Library_Reference_Symbol_File}: single
21118 Value is the name of the reference symbol file.
21122 @strong{Configuration - General}
21128 @strong{Default_Language}: single
21130 Value is the case-insensitive name of the language of a project when attribute
21131 Languages is not specified.
21134 @strong{Run_Path_Option}: list
21136 Value is the list of switches to be used when specifying the run path option
21140 @strong{Run_Path_Origin}: single
21142 Value is the the string that may replace the path name of the executable
21143 directory in the run path options.
21146 @strong{Separate_Run_Path_Options}: single
21148 Indicates if there may be several run path options specified when linking an
21149 executable. Only authorized case-insensitive values are "true" or "false" (the
21153 @strong{Toolchain_Version}: single, indexed, case-insensitive index
21155 Index is a language name. Specify the version of a toolchain for a language.
21158 @strong{Toolchain_Description}: single, indexed, case-insensitive index
21160 Obsolescent. No longer used.
21163 @strong{Object_Generated}: single, indexed, case-insensitive index
21165 Index is a language name. Indicates if invoking the compiler for a language
21166 produces an object file. Only authorized case-insensitive values are "false"
21167 and "true" (the default).
21170 @strong{Objects_Linked}: single, indexed, case-insensitive index
21172 Index is a language name. Indicates if the object files created by the compiler
21173 for a language need to be linked in the executable. Only authorized
21174 case-insensitive values are "false" and "true" (the default).
21177 @strong{Target}: single
21179 Value is the name of the target platform. Taken into account only in the main
21183 @strong{Runtime}: single, indexed, case-insensitive index
21185 Index is a language name. Indicates the runtime directory that is to be used
21186 when using the compiler of the language. Taken into account only in the main
21191 @strong{Configuration - Libraries}
21197 @strong{Library_Builder}: single
21199 Value is the path name of the application that is to be used to build
21200 libraries. Usually the path name of "gprlib".
21203 @strong{Library_Support}: single
21205 Indicates the level of support of libraries. Only authorized case-insensitive
21206 values are "static_only", "full" or "none" (the default).
21210 @strong{Configuration - Archives}
21216 @strong{Archive_Builder}: list
21218 Value is the name of the application to be used to create a static library
21219 (archive), followed by the options to be used.
21222 @strong{Archive_Builder_Append_Option}: list
21224 Value is the list of options to be used when invoking the archive builder
21225 to add project files into an archive.
21228 @strong{Archive_Indexer}: list
21230 Value is the name of the archive indexer, followed by the required options.
21233 @strong{Archive_Suffix}: single
21235 Value is the extension of archives. When not declared, the extension is ".a".
21238 @strong{Library_Partial_Linker}: list
21240 Value is the name of the partial linker executable, followed by the required
21245 @strong{Configuration - Shared Libraries}
21251 @strong{Shared_Library_Prefix}: single
21253 Value is the prefix in the name of shared library files. When not declared,
21254 the prefix is "lib".
21257 @strong{Shared_Library_Suffix}: single
21259 Value is the the extension of the name of shared library files. When not
21260 declared, the extension is ".so".
21263 @strong{Symbolic_Link_Supported}: single
21265 Indicates if symbolic links are supported on the platform. Only authorized
21266 case-insensitive values are "true" and "false" (the default).
21269 @strong{Library_Major_Minor_Id_Supported}: single
21271 Indicates if major and minor ids for shared library names are supported on
21272 the platform. Only authorized case-insensitive values are "true" and "false"
21276 @strong{Library_Auto_Init_Supported}: single
21278 Indicates if auto-initialization of Stand-Alone Libraries is supported. Only
21279 authorized case-insensitive values are "true" and "false" (the default).
21282 @strong{Shared_Library_Minimum_Switches}: list
21284 Value is the list of required switches when linking a shared library.
21287 @strong{Library_Version_Switches}: list
21289 Value is the list of switches to specify a internal name for a shared library.
21292 @strong{Library_Install_Name_Option}: single
21294 Value is the name of the option that needs to be used, concatenated with the
21295 path name of the library file, when linking a shared library.
21298 @strong{Runtime_Library_Dir}: single, indexed, case-insensitive index
21300 Index is a language name. Value is the path name of the directory where the
21301 runtime libraries are located.
21304 @strong{Runtime_Source_Dir}: single, indexed, case-insensitive index
21306 Index is a language name. Value is the path name of the directory where the
21307 sources of runtime libraries are located.
21311 @node Package Binder Attributes,Package Builder Attributes,Project Level Attributes,Attributes
21312 @anchor{gnat_ugn/gnat_project_manager package-binder-attributes}@anchor{1a6}@anchor{gnat_ugn/gnat_project_manager id49}@anchor{1a7}
21313 @subsubsection Package Binder Attributes
21326 @strong{Default_Switches}: list, indexed, case-insensitive index
21328 Index is a language name. Value is the list of switches to be used when binding
21329 code of the language, if there is no applicable attribute Switches.
21332 @strong{Switches}: list, optional index, indexed,
21333 case-insensitive index, others allowed
21335 Index is either a language name or a source file name. Value is the list of
21336 switches to be used when binding code. Index is either the source file name
21337 of the executable to be bound or the language name of the code to be bound.
21341 @strong{Configuration - Binding}
21347 @strong{Driver}: single, indexed, case-insensitive index
21349 Index is a language name. Value is the name of the application to be used when
21350 binding code of the language.
21353 @strong{Required_Switches}: list, indexed, case-insensitive index
21355 Index is a language name. Value is the list of the required switches to be
21356 used when binding code of the language.
21359 @strong{Prefix}: single, indexed, case-insensitive index
21361 Index is a language name. Value is a prefix to be used for the binder exchange
21362 file name for the language. Used to have different binder exchange file names
21363 when binding different languages.
21366 @strong{Objects_Path}: single,indexed, case-insensitive index
21368 Index is a language name. Value is the name of the environment variable that
21369 contains the path for the object directories.
21372 @strong{Object_Path_File}: single,indexed, case-insensitive index
21374 Index is a language name. Value is the name of the environment variable. The
21375 value of the environment variable is the path name of a text file that
21376 contains the list of object directories.
21380 @node Package Builder Attributes,Package Clean Attributes,Package Binder Attributes,Attributes
21381 @anchor{gnat_ugn/gnat_project_manager package-builder-attributes}@anchor{1a8}@anchor{gnat_ugn/gnat_project_manager id50}@anchor{1a9}
21382 @subsubsection Package Builder Attributes
21389 @strong{Default_Switches}: list, indexed, case-insensitive index
21391 Index is a language name. Value is the list of builder switches to be used when
21392 building an executable of the language, if there is no applicable attribute
21396 @strong{Switches}: list, optional index, indexed, case-insensitive index,
21399 Index is either a language name or a source file name. Value is the list of
21400 builder switches to be used when building an executable. Index is either the
21401 source file name of the executable to be built or its language name.
21404 @strong{Global_Compilation_Switches}: list, optional index, indexed,
21405 case-insensitive index
21407 Index is either a language name or a source file name. Value is the list of
21408 compilation switches to be used when building an executable. Index is either
21409 the source file name of the executable to be built or its language name.
21412 @strong{Executable}: single, indexed, case-insensitive index
21414 Index is an executable source file name. Value is the simple file name of the
21415 executable to be built.
21418 @strong{Executable_Suffix}: single
21420 Value is the extension of the file names of executable. When not specified,
21421 the extension is the default extension of executables on the platform.
21424 @strong{Global_Configuration_Pragmas}: single
21426 Value is the file name of a configuration pragmas file that is specified to
21427 the Ada compiler when compiling any Ada source in the project tree.
21430 @strong{Global_Config_File}: single, indexed, case-insensitive index
21432 Index is a language name. Value is the file name of a configuration file that
21433 is specified to the compiler when compiling any source of the language in the
21438 @node Package Clean Attributes,Package Compiler Attributes,Package Builder Attributes,Attributes
21439 @anchor{gnat_ugn/gnat_project_manager package-clean-attributes}@anchor{1aa}@anchor{gnat_ugn/gnat_project_manager id52}@anchor{1ab}
21440 @subsubsection Package Clean Attributes
21447 @strong{Switches}: list
21449 Value is a list of switches to be used by the cleaning application.
21452 @strong{Source_Artifact_Extensions}: list, indexed, case-insensitive index
21454 Index is a language names. Value is the list of extensions for file names
21455 derived from object file names that need to be cleaned in the object
21456 directory of the project.
21459 @strong{Object_Artifact_Extensions}: list, indexed, case-insensitive index
21461 Index is a language names. Value is the list of extensions for file names
21462 derived from source file names that need to be cleaned in the object
21463 directory of the project.
21466 @strong{Artifacts_In_Object_Dir}: single
21468 Value is a list of file names expressed as regular expressions that are to be
21469 deleted by gprclean in the object directory of the project.
21472 @strong{Artifacts_In_Exec_Dir}: single
21474 Value is list of file names expressed as regular expressions that are to be
21475 deleted by gprclean in the exec directory of the main project.
21478 @node Package Compiler Attributes,Package Cross_Reference Attributes,Package Clean Attributes,Attributes
21479 @anchor{gnat_ugn/gnat_project_manager id53}@anchor{1ac}@anchor{gnat_ugn/gnat_project_manager package-compiler-attributes}@anchor{1ad}
21480 @subsubsection Package Compiler Attributes
21493 @strong{Default_Switches}: list, indexed, case-insensitive index
21495 Index is a language name. Value is a list of switches to be used when invoking
21496 the compiler for the language for a source of the project, if there is no
21497 applicable attribute Switches.
21500 @strong{Switches}: list, optional index, indexed, case-insensitive index,
21503 Index is a source file name or a language name. Value is the list of switches
21504 to be used when invoking the compiler for the source or for its language.
21507 @strong{Local_Configuration_Pragmas}: single
21509 Value is the file name of a configuration pragmas file that is specified to
21510 the Ada compiler when compiling any Ada source in the project.
21513 @strong{Local_Config_File}: single, indexed, case-insensitive index
21515 Index is a language name. Value is the file name of a configuration file that
21516 is specified to the compiler when compiling any source of the language in the
21521 @strong{Configuration - Compiling}
21527 @strong{Driver}: single, indexed, case-insensitive index
21529 Index is a language name. Value is the name of the executable for the compiler
21533 @strong{Language_Kind}: single, indexed, case-insensitive index
21535 Index is a language name. Indicates the kind of the language, either file based
21536 or unit based. Only authorized case-insensitive values are "unit_based" and
21537 "file_based" (the default).
21540 @strong{Dependency_Kind}: single, indexed, case-insensitive index
21542 Index is a language name. Indicates how the dependencies are handled for the
21543 language. Only authorized case-insensitive values are "makefile", "ali_file",
21544 "ali_closure" or "none" (the default).
21547 @strong{Required_Switches}: list, indexed, case-insensitive index
21549 Equivalent to attribute Leading_Required_Switches.
21552 @strong{Leading_Required_Switches}: list, indexed, case-insensitive index
21554 Index is a language name. Value is the list of the minimum switches to be used
21555 at the beginning of the command line when invoking the compiler for the
21559 @strong{Trailing_Required_Switches}: list, indexed, case-insensitive index
21561 Index is a language name. Value is the list of the minimum switches to be used
21562 at the end of the command line when invoking the compiler for the language.
21565 @strong{PIC_Option}: list, indexed, case-insensitive index
21567 Index is a language name. Value is the list of switches to be used when
21568 compiling a source of the language when the project is a shared library
21572 @strong{Path_Syntax}: single, indexed, case-insensitive index
21574 Index is a language name. Value is the kind of path syntax to be used when
21575 invoking the compiler for the language. Only authorized case-insensitive
21576 values are "canonical" and "host" (the default).
21579 @strong{Source_File_Switches}: single, indexed, case-insensitive index
21581 Index is a language name. Value is a list of switches to be used just before
21582 the path name of the source to compile when invoking the compiler for a source
21586 @strong{Object_File_Suffix}: single, indexed, case-insensitive index
21588 Index is a language name. Value is the extension of the object files created
21589 by the compiler of the language. When not specified, the extension is the
21590 default one for the platform.
21593 @strong{Object_File_Switches}: list, indexed, case-insensitive index
21595 Index is a language name. Value is the list of switches to be used by the
21596 compiler of the language to specify the path name of the object file. When not
21597 specified, the switch used is "-o".
21600 @strong{Multi_Unit_Switches}: list, indexed, case-insensitive index
21602 Index is a language name. Value is the list of switches to be used to compile
21603 a unit in a multi unit source of the language. The index of the unit in the
21604 source is concatenated with the last switches in the list.
21607 @strong{Multi_Unit_Object_Separator}: single, indexed, case-insensitive index
21609 Index is a language name. Value is the string to be used in the object file
21610 name before the index of the unit, when compiling a unit in a multi unit source
21615 @strong{Configuration - Mapping Files}
21621 @strong{Mapping_File_Switches}: list, indexed, case-insensitive index
21623 Index is a language name. Value is the list of switches to be used to specify
21624 a mapping file when invoking the compiler for a source of the language.
21627 @strong{Mapping_Spec_Suffix}: single, indexed, case-insensitive index
21629 Index is a language name. Value is the suffix to be used in a mapping file
21630 to indicate that the source is a spec.
21633 @strong{Mapping_Body_Suffix}: single, indexed, case-insensitive index
21635 Index is a language name. Value is the suffix to be used in a mapping file
21636 to indicate that the source is a body.
21640 @strong{Configuration - Config Files}
21646 @strong{Config_File_Switches}: list: single, indexed, case-insensitive index
21648 Index is a language name. Value is the list of switches to specify to the
21649 compiler of the language a configuration file.
21652 @strong{Config_Body_File_Name}: single, indexed, case-insensitive index
21654 Index is a language name. Value is the template to be used to indicate a
21655 configuration specific to a body of the language in a configuration
21659 @strong{Config_Body_File_Name_Index}: single, indexed, case-insensitive index
21661 Index is a language name. Value is the template to be used to indicate a
21662 configuration specific to the body a unit in a multi unit source of the
21663 language in a configuration file.
21666 @strong{Config_Body_File_Name_Pattern}: single, indexed,
21667 case-insensitive index
21669 Index is a language name. Value is the template to be used to indicate a
21670 configuration for all bodies of the languages in a configuration file.
21673 @strong{Config_Spec_File_Name}: single, indexed, case-insensitive index
21675 Index is a language name. Value is the template to be used to indicate a
21676 configuration specific to a spec of the language in a configuration
21680 @strong{Config_Spec_File_Name_Index}: single, indexed, case-insensitive index
21682 Index is a language name. Value is the template to be used to indicate a
21683 configuration specific to the spec a unit in a multi unit source of the
21684 language in a configuration file.
21687 @strong{Config_Spec_File_Name_Pattern}: single, indexed,
21688 case-insensitive index
21690 Index is a language name. Value is the template to be used to indicate a
21691 configuration for all specs of the languages in a configuration file.
21694 @strong{Config_File_Unique}: single, indexed, case-insensitive index
21696 Index is a language name. Indicates if there should be only one configuration
21697 file specified to the compiler of the language. Only authorized
21698 case-insensitive values are "true" and "false" (the default).
21702 @strong{Configuration - Dependencies}
21708 @strong{Dependency_Switches}: list, indexed, case-insensitive index
21710 Index is a language name. Value is the list of switches to be used to specify
21711 to the compiler the dependency file when the dependency kind of the language is
21712 file based, and when Dependency_Driver is not specified for the language.
21715 @strong{Dependency_Driver}: list, indexed, case-insensitive index
21717 Index is a language name. Value is the name of the executable to be used to
21718 create the dependency file for a source of the language, followed by the
21723 @strong{Configuration - Search Paths}
21729 @strong{Include_Switches}: list, indexed, case-insensitive index
21731 Index is a language name. Value is the list of switches to specify to the
21732 compiler of the language to indicate a directory to look for sources.
21735 @strong{Include_Path}: single, indexed, case-insensitive index
21737 Index is a language name. Value is the name of an environment variable that
21738 contains the path of all the directories that the compiler of the language
21739 may search for sources.
21742 @strong{Include_Path_File}: single, indexed, case-insensitive index
21744 Index is a language name. Value is the name of an environment variable the
21745 value of which is the path name of a text file that contains the directories
21746 that the compiler of the language may search for sources.
21749 @strong{Object_Path_Switches}: list, indexed, case-insensitive index
21751 Index is a language name. Value is the list of switches to specify to the
21752 compiler of the language the name of a text file that contains the list of
21753 object directories. When this attribute is not declared, the text file is
21758 @node Package Cross_Reference Attributes,Package Finder Attributes,Package Compiler Attributes,Attributes
21759 @anchor{gnat_ugn/gnat_project_manager id54}@anchor{1ae}@anchor{gnat_ugn/gnat_project_manager package-cross-reference-attributes}@anchor{1af}
21760 @subsubsection Package Cross_Reference Attributes
21767 @strong{Default_Switches}: list, indexed, case-insensitive index
21769 Index is a language name. Value is a list of switches to be used when invoking
21770 @cite{gnatxref} for a source of the language, if there is no applicable
21771 attribute Switches.
21774 @strong{Switches}: list, optional index, indexed, case-insensitive index,
21777 Index is a source file name. Value is the list of switches to be used when
21778 invoking @cite{gnatxref} for the source.
21782 @node Package Finder Attributes,Package gnatls Attributes,Package Cross_Reference Attributes,Attributes
21783 @anchor{gnat_ugn/gnat_project_manager id56}@anchor{1b0}@anchor{gnat_ugn/gnat_project_manager package-finder-attributes}@anchor{1b1}
21784 @subsubsection Package Finder Attributes
21791 @strong{Default_Switches}: list, indexed, case-insensitive index
21793 Index is a language name. Value is a list of switches to be used when invoking
21794 @cite{gnatfind} for a source of the language, if there is no applicable
21795 attribute Switches.
21798 @strong{Switches}: list, optional index, indexed, case-insensitive index,
21801 Index is a source file name. Value is the list of switches to be used when
21802 invoking @cite{gnatfind} for the source.
21805 @node Package gnatls Attributes,Package IDE Attributes,Package Finder Attributes,Attributes
21806 @anchor{gnat_ugn/gnat_project_manager package-gnatls-attributes}@anchor{1b2}@anchor{gnat_ugn/gnat_project_manager id57}@anchor{1b3}
21807 @subsubsection Package gnatls Attributes
21814 @strong{Switches}: list
21816 Value is a list of switches to be used when invoking @cite{gnatls}.
21820 @node Package IDE Attributes,Package Install Attributes,Package gnatls Attributes,Attributes
21821 @anchor{gnat_ugn/gnat_project_manager id58}@anchor{1b4}@anchor{gnat_ugn/gnat_project_manager package-ide-attributes}@anchor{1b5}
21822 @subsubsection Package IDE Attributes
21829 @strong{Default_Switches}: list, indexed
21831 Index is the name of an external tool that the GNAT Programming System (GPS)
21832 is supporting. Value is a list of switches to use when invoking that tool.
21835 @strong{Remote_Host}: single
21837 Value is a string that designates the remote host in a cross-compilation
21838 environment, to be used for remote compilation and debugging. This attribute
21839 should not be specified when running on the local machine.
21842 @strong{Program_Host}: single
21844 Value is a string that specifies the name of IP address of the embedded target
21845 in a cross-compilation environment, on which the program should execute.
21848 @strong{Communication_Protocol}: single
21850 Value is the name of the protocol to use to communicate with the target
21851 in a cross-compilation environment, for example @cite{"wtx"} or
21855 @strong{Compiler_Command}: single, indexed, case-insensitive index
21857 Index is a language Name. Value is a string that denotes the command to be
21858 used to invoke the compiler. For historical reasons, the value of
21859 @cite{Compiler_Command ("Ada")} is expected to be a reference to @emph{gnatmake} or
21860 @emph{cross-gnatmake}.
21863 @strong{Debugger_Command}: single
21865 Value is a string that specifies the name of the debugger to be used, such as
21866 gdb, powerpc-wrs-vxworks-gdb or gdb-4.
21869 @strong{gnatlist}: single
21871 Value is a string that specifies the name of the @emph{gnatls} utility
21872 to be used to retrieve information about the predefined path; for example,
21873 @cite{"gnatls"}, @cite{"powerpc-wrs-vxworks-gnatls"}.
21876 @strong{VCS_Kind}: single
21878 Value is a string used to specify the Version Control System (VCS) to be used
21879 for this project, for example "Subversion", "ClearCase". If the
21880 value is set to "Auto", the IDE will try to detect the actual VCS used
21881 on the list of supported ones.
21884 @strong{VCS_File_Check}: single
21886 Value is a string that specifies the command used by the VCS to check
21887 the validity of a file, either when the user explicitly asks for a check,
21888 or as a sanity check before doing the check-in.
21891 @strong{VCS_Log_Check}: single
21893 Value is a string that specifies the command used by the VCS to check
21894 the validity of a log file.
21897 @strong{Documentation_Dir}: single
21899 Value is the directory used to generate the documentation of source code.
21902 @node Package Install Attributes,Package Linker Attributes,Package IDE Attributes,Attributes
21903 @anchor{gnat_ugn/gnat_project_manager package-install-attributes}@anchor{1b6}@anchor{gnat_ugn/gnat_project_manager id59}@anchor{1b7}
21904 @subsubsection Package Install Attributes
21911 @strong{Artifacts}: list, indexed
21913 An array attribute to declare a set of files not part of the sources
21914 to be installed. The array discriminant is the directory where the
21915 file is to be installed. If a relative directory then Prefix (see
21916 below) is prepended.
21919 @strong{Prefix}: single
21921 Value is the install destination directory.
21924 @strong{Sources_Subdir}: single
21926 Value is the sources directory or subdirectory of Prefix.
21929 @strong{Exec_Subdir}: single
21931 Value is the executables directory or subdirectory of Prefix.
21934 @strong{Lib_Subdir}: single
21936 Value is library directory or subdirectory of Prefix.
21939 @strong{Project_Subdir}: single
21941 Value is the project directory or subdirectory of Prefix.
21944 @strong{Active}: single
21946 Indicates that the project is to be installed or not. Case-insensitive value
21947 "false" means that the project is not to be installed, all other values mean
21948 that the project is to be installed.
21951 @strong{Mode}: single
21953 Value is the installation mode, it is either @strong{dev} (default) or @strong{usage}.
21956 @strong{Install_Name}: single
21958 Specify the name to use for recording the installation. The default is
21959 the project name without the extension.
21962 @node Package Linker Attributes,Package Naming Attributes,Package Install Attributes,Attributes
21963 @anchor{gnat_ugn/gnat_project_manager id60}@anchor{1b8}@anchor{gnat_ugn/gnat_project_manager package-linker-attributes}@anchor{1b9}
21964 @subsubsection Package Linker Attributes
21977 @strong{Required_Switches}: list
21979 Value is a list of switches that are required when invoking the linker to link
21983 @strong{Default_Switches}: list, indexed, case-insensitive index
21985 Index is a language name. Value is a list of switches for the linker when
21986 linking an executable for a main source of the language, when there is no
21987 applicable Switches.
21990 @strong{Leading_Switches}: list, optional index, indexed,
21991 case-insensitive index, others allowed
21993 Index is a source file name or a language name. Value is the list of switches
21994 to be used at the beginning of the command line when invoking the linker to
21995 build an executable for the source or for its language.
21998 @strong{Switches}: list, optional index, indexed, case-insensitive index,
22001 Index is a source file name or a language name. Value is the list of switches
22002 to be used when invoking the linker to build an executable for the source or
22006 @strong{Trailing_Switches}: list, optional index, indexed,
22007 case-insensitive index, others allowed
22009 Index is a source file name or a language name. Value is the list of switches
22010 to be used at the end of the command line when invoking the linker to
22011 build an executable for the source or for its language. These switches may
22012 override the Required_Switches.
22015 @strong{Linker_Options}: list
22017 Value is a list of switches/options that are to be added when linking an
22018 executable from a project importing the current project directly or indirectly.
22019 Linker_Options are not used when linking an executable from the current
22023 @strong{Map_File_Option}: single
22025 Value is the switch to specify the map file name that the linker needs to
22030 @strong{Configuration - Linking}
22036 @strong{Driver}: single
22038 Value is the name of the linker executable.
22042 @strong{Configuration - Response Files}
22048 @strong{Max_Command_Line_Length}: single
22050 Value is the maximum number of character in the command line when invoking
22051 the linker to link an executable.
22054 @strong{Response_File_Format}: single
22056 Indicates the kind of response file to create when the length of the linking
22057 command line is too large. Only authorized case-insensitive values are "none",
22058 "gnu", "object_list", "gcc_gnu", "gcc_option_list" and "gcc_object_list".
22061 @strong{Response_File_Switches}: list
22063 Value is the list of switches to specify a response file to the linker.
22069 @c .. _Package_Metrics_Attribute:
22071 @c Package Metrics Attribute
22072 @c ^^^^^^^^^^^^^^^^^^^^^^^^^
22074 @c * **Default_Switches**: list, indexed, case-insensitive index
22076 @c Index is a language name. Value is a list of switches to be used when invoking
22077 @c `gnatmetric` for a source of the language, if there is no applicable
22078 @c attribute Switches.
22080 @c * **Switches**: list, optional index, indexed, case-insensitive index,
22083 @c Index is a source file name. Value is the list of switches to be used when
22084 @c invoking `gnatmetric` for the source.
22086 @node Package Naming Attributes,Package Remote Attributes,Package Linker Attributes,Attributes
22087 @anchor{gnat_ugn/gnat_project_manager package-naming-attributes}@anchor{1ba}@anchor{gnat_ugn/gnat_project_manager id61}@anchor{1bb}
22088 @subsubsection Package Naming Attributes
22095 @strong{Specification_Suffix}: single, indexed, case-insensitive index
22097 Equivalent to attribute Spec_Suffix.
22100 @strong{Spec_Suffix}: single, indexed, case-insensitive index
22102 Index is a language name. Value is the extension of file names for specs of
22106 @strong{Implementation_Suffix}: single, indexed, case-insensitive index
22108 Equivalent to attribute Body_Suffix.
22111 @strong{Body_Suffix}: single, indexed, case-insensitive index
22113 Index is a language name. Value is the extension of file names for bodies of
22117 @strong{Separate_Suffix}: single
22119 Value is the extension of file names for subunits of Ada.
22122 @strong{Casing}: single
22124 Indicates the casing of sources of the Ada language. Only authorized
22125 case-insensitive values are "lowercase", "uppercase" and "mixedcase".
22128 @strong{Dot_Replacement}: single
22130 Value is the string that replace the dot of unit names in the source file names
22131 of the Ada language.
22134 @strong{Specification}: single, optional index, indexed,
22135 case-insensitive index
22137 Equivalent to attribute Spec.
22140 @strong{Spec}: single, optional index, indexed, case-insensitive index
22142 Index is a unit name. Value is the file name of the spec of the unit.
22145 @strong{Implementation}: single, optional index, indexed,
22146 case-insensitive index
22148 Equivalent to attribute Body.
22151 @strong{Body}: single, optional index, indexed, case-insensitive index
22153 Index is a unit name. Value is the file name of the body of the unit.
22156 @strong{Specification_Exceptions}: list, indexed, case-insensitive index
22158 Index is a language name. Value is a list of specs for the language that do not
22159 necessarily follow the naming scheme for the language and that may or may not
22160 be found in the source directories of the project.
22163 @strong{Implementation_Exceptions}: list, indexed, case-insensitive index
22165 Index is a language name. Value is a list of bodies for the language that do not
22166 necessarily follow the naming scheme for the language and that may or may not
22167 be found in the source directories of the project.
22171 @node Package Remote Attributes,Package Stack Attributes,Package Naming Attributes,Attributes
22172 @anchor{gnat_ugn/gnat_project_manager package-remote-attributes}@anchor{1bc}@anchor{gnat_ugn/gnat_project_manager id63}@anchor{1bd}
22173 @subsubsection Package Remote Attributes
22180 @strong{Included_Patterns}: list
22182 If this attribute is defined it sets the patterns to
22183 synchronized from the master to the slaves. It is exclusive
22184 with Excluded_Patterns, that is it is an error to define
22188 @strong{Included_Artifact_Patterns}: list
22190 If this attribute is defined it sets the patterns of compilation
22191 artifacts to synchronized from the slaves to the build master.
22192 This attribute replace the default hard-coded patterns.
22195 @strong{Excluded_Patterns}: list
22197 Set of patterns to ignore when synchronizing sources from the build
22198 master to the slaves. A set of predefined patterns are supported
22199 (e.g. *.o, *.ali, *.exe, etc.), this attributes make it possible to
22200 add some more patterns.
22203 @strong{Root_Dir}: single
22205 Value is the root directory used by the slave machines.
22208 @node Package Stack Attributes,Package Synchronize Attributes,Package Remote Attributes,Attributes
22209 @anchor{gnat_ugn/gnat_project_manager id64}@anchor{1be}@anchor{gnat_ugn/gnat_project_manager package-stack-attributes}@anchor{1bf}
22210 @subsubsection Package Stack Attributes
22217 @strong{Switches}: list
22219 Value is the list of switches to be used when invoking @cite{gnatstack}.
22222 @node Package Synchronize Attributes,,Package Stack Attributes,Attributes
22223 @anchor{gnat_ugn/gnat_project_manager package-synchronize-attributes}@anchor{1c0}
22224 @subsubsection Package Synchronize Attributes
22231 @strong{Default_Switches}: list, indexed, case-insensitive index
22233 Index is a language name. Value is a list of switches to be used when invoking
22234 @cite{gnatsync} for a source of the language, if there is no applicable
22235 attribute Switches.
22238 @strong{Switches}: list, optional index, indexed, case-insensitive index,
22241 Index is a source file name. Value is the list of switches to be used when
22242 invoking @cite{gnatsync} for the source.
22245 @node Tools Supporting Project Files,GNAT Utility Programs,GNAT Project Manager,Top
22246 @anchor{gnat_ugn/tools_supporting_project_files doc}@anchor{1c1}@anchor{gnat_ugn/tools_supporting_project_files tools-supporting-project-files}@anchor{c}@anchor{gnat_ugn/tools_supporting_project_files id1}@anchor{1c2}
22247 @chapter Tools Supporting Project Files
22250 This section describes how project files can be used in conjunction with a number of
22254 * gnatmake and Project Files::
22255 * The GNAT Driver and Project Files::
22259 @node gnatmake and Project Files,The GNAT Driver and Project Files,,Tools Supporting Project Files
22260 @anchor{gnat_ugn/tools_supporting_project_files id2}@anchor{1c3}@anchor{gnat_ugn/tools_supporting_project_files gnatmake-and-project-files}@anchor{e1}
22261 @section gnatmake and Project Files
22264 This section covers several topics related to @emph{gnatmake} and
22265 project files: defining switches for @emph{gnatmake}
22266 and for the tools that it invokes; specifying configuration pragmas;
22267 the use of the @cite{Main} attribute; building and rebuilding library project
22271 * Switches Related to Project Files::
22272 * Switches and Project Files::
22273 * Specifying Configuration Pragmas::
22274 * Project Files and Main Subprograms::
22275 * Library Project Files::
22279 @node Switches Related to Project Files,Switches and Project Files,,gnatmake and Project Files
22280 @anchor{gnat_ugn/tools_supporting_project_files switches-related-to-project-files}@anchor{e3}@anchor{gnat_ugn/tools_supporting_project_files id3}@anchor{1c4}
22281 @subsection Switches Related to Project Files
22284 The following switches are used by GNAT tools that support project files:
22288 @geindex -P (any project-aware tool)
22294 @item @code{-P@emph{project}}
22296 Indicates the name of a project file. This project file will be parsed with
22297 the verbosity indicated by @emph{-vP*x*},
22298 if any, and using the external references indicated
22299 by @emph{-X} switches, if any.
22300 There may zero, one or more spaces between @emph{-P} and @cite{project}.
22302 There must be only one @emph{-P} switch on the command line.
22304 Since the Project Manager parses the project file only after all the switches
22305 on the command line are checked, the order of the switches
22308 or @emph{-X} is not significant.
22310 @geindex -X (any project-aware tool)
22312 @item @code{-X@emph{name}=@emph{value}}
22314 Indicates that external variable @cite{name} has the value @cite{value}.
22315 The Project Manager will use this value for occurrences of
22316 @cite{external(name)} when parsing the project file.
22318 If @cite{name} or @cite{value} includes a space, then @cite{name=value} should be
22319 put between quotes.
22326 Several @emph{-X} switches can be used simultaneously.
22327 If several @emph{-X} switches specify the same
22328 @cite{name}, only the last one is used.
22330 An external variable specified with a @emph{-X} switch
22331 takes precedence over the value of the same name in the environment.
22333 @geindex -vP (any project-aware tool)
22335 @item @code{-vP@emph{x}}
22337 Indicates the verbosity of the parsing of GNAT project files.
22339 @emph{-vP0} means Default;
22340 @emph{-vP1} means Medium;
22341 @emph{-vP2} means High.
22343 The default is Default: no output for syntactically correct
22345 If several @emph{-vP*x*} switches are present,
22346 only the last one is used.
22348 @geindex -aP (any project-aware tool)
22350 @item @code{-aP@emph{dir}}
22352 Add directory @cite{dir} at the beginning of the project search path, in order,
22353 after the current working directory.
22355 @geindex -eL (any project-aware tool)
22359 Follow all symbolic links when processing project files.
22361 @geindex --subdirs= (gnatmake and gnatclean)
22363 @item @code{--subdirs=@emph{subdir}}
22365 This switch is recognized by @emph{gnatmake} and @emph{gnatclean}. It
22366 indicate that the real directories (except the source directories) are the
22367 subdirectories @cite{subdir} of the directories specified in the project files.
22368 This applies in particular to object directories, library directories and
22369 exec directories. If the subdirectories do not exist, they are created
22373 @node Switches and Project Files,Specifying Configuration Pragmas,Switches Related to Project Files,gnatmake and Project Files
22374 @anchor{gnat_ugn/tools_supporting_project_files id4}@anchor{1c5}@anchor{gnat_ugn/tools_supporting_project_files switches-and-project-files}@anchor{1c6}
22375 @subsection Switches and Project Files
22378 For each of the packages @cite{Builder}, @cite{Compiler}, @cite{Binder}, and
22379 @cite{Linker}, you can specify a @cite{Default_Switches}
22380 attribute, a @cite{Switches} attribute, or both;
22381 as their names imply, these switch-related
22382 attributes affect the switches that are used for each of these GNAT
22384 @emph{gnatmake} is invoked. As will be explained below, these
22385 component-specific switches precede
22386 the switches provided on the @emph{gnatmake} command line.
22388 The @cite{Default_Switches} attribute is an attribute
22389 indexed by language name (case insensitive) whose value is a string list.
22395 package Compiler is
22396 for Default_Switches ("Ada")
22403 The @cite{Switches} attribute is indexed on a file name (which may or may
22404 not be case sensitive, depending
22405 on the operating system) whose value is a string list. For example:
22411 for Switches ("main1.adb")
22413 for Switches ("main2.adb")
22419 For the @cite{Builder} package, the file names must designate source files
22420 for main subprograms. For the @cite{Binder} and @cite{Linker} packages, the
22421 file names must designate @code{ALI} or source files for main subprograms.
22422 In each case just the file name without an explicit extension is acceptable.
22424 For each tool used in a program build (@emph{gnatmake}, the compiler, the
22425 binder, and the linker), the corresponding package @@dfn@{contributes@} a set of
22426 switches for each file on which the tool is invoked, based on the
22427 switch-related attributes defined in the package.
22428 In particular, the switches
22429 that each of these packages contributes for a given file @cite{f} comprise:
22435 the value of attribute @cite{Switches (`f})`,
22436 if it is specified in the package for the given file,
22439 otherwise, the value of @cite{Default_Switches ("Ada")},
22440 if it is specified in the package.
22443 If neither of these attributes is defined in the package, then the package does
22444 not contribute any switches for the given file.
22446 When @emph{gnatmake} is invoked on a file, the switches comprise
22447 two sets, in the following order: those contributed for the file
22448 by the @cite{Builder} package;
22449 and the switches passed on the command line.
22451 When @emph{gnatmake} invokes a tool (compiler, binder, linker) on a file,
22452 the switches passed to the tool comprise three sets,
22453 in the following order:
22459 the applicable switches contributed for the file
22460 by the @cite{Builder} package in the project file supplied on the command line;
22463 those contributed for the file by the package (in the relevant project file --
22464 see below) corresponding to the tool; and
22467 the applicable switches passed on the command line.
22470 The term @emph{applicable switches} reflects the fact that
22471 @emph{gnatmake} switches may or may not be passed to individual
22472 tools, depending on the individual switch.
22474 @emph{gnatmake} may invoke the compiler on source files from different
22475 projects. The Project Manager will use the appropriate project file to
22476 determine the @cite{Compiler} package for each source file being compiled.
22477 Likewise for the @cite{Binder} and @cite{Linker} packages.
22479 As an example, consider the following package in a project file:
22485 package Compiler is
22486 for Default_Switches ("Ada")
22488 for Switches ("a.adb")
22490 for Switches ("b.adb")
22498 If @emph{gnatmake} is invoked with this project file, and it needs to
22499 compile, say, the files @code{a.adb}, @code{b.adb}, and @code{c.adb}, then
22500 @code{a.adb} will be compiled with the switch @emph{-O1},
22501 @code{b.adb} with switches @emph{-O2} and @emph{-gnaty},
22502 and @code{c.adb} with @emph{-g}.
22504 The following example illustrates the ordering of the switches
22505 contributed by different packages:
22512 for Switches ("main.adb")
22518 package Compiler is
22519 for Switches ("main.adb")
22526 If you issue the command:
22531 $ gnatmake -Pproj2 -O0 main
22535 then the compiler will be invoked on @code{main.adb} with the following
22536 sequence of switches
22545 with the last @emph{-O}
22546 switch having precedence over the earlier ones;
22547 several other switches
22548 (such as @emph{-c}) are added implicitly.
22550 The switches @emph{-g}
22551 and @emph{-O1} are contributed by package
22552 @cite{Builder}, @emph{-O2} is contributed
22553 by the package @cite{Compiler}
22554 and @emph{-O0} comes from the command line.
22556 The @emph{-g} switch will also be passed in the invocation of
22559 A final example illustrates switch contributions from packages in different
22566 for Source_Files use ("pack.ads", "pack.adb");
22567 package Compiler is
22568 for Default_Switches ("Ada")
22575 for Source_Files use ("foo_main.adb", "bar_main.adb");
22577 for Switches ("foo_main.adb")
22585 -- Ada source file:
22587 procedure Foo_Main is
22598 $ gnatmake -PProj4 foo_main.adb -cargs -gnato
22602 then the switches passed to the compiler for @code{foo_main.adb} are
22603 @emph{-g} (contributed by the package @cite{Proj4.Builder}) and
22604 @emph{-gnato} (passed on the command line).
22605 When the imported package @cite{Pack} is compiled, the switches used
22606 are @emph{-g} from @cite{Proj4.Builder},
22607 @emph{-gnata} (contributed from package @cite{Proj3.Compiler},
22608 and @emph{-gnato} from the command line.
22610 When using @emph{gnatmake} with project files, some switches or
22611 arguments may be expressed as relative paths. As the working directory where
22612 compilation occurs may change, these relative paths are converted to absolute
22613 paths. For the switches found in a project file, the relative paths
22614 are relative to the project file directory, for the switches on the command
22615 line, they are relative to the directory where @emph{gnatmake} is invoked.
22616 The switches for which this occurs are:
22622 -aI, as well as all arguments that are not switches (arguments to
22624 -o, object files specified in package @cite{Linker} or after
22625 -largs on the command line). The exception to this rule is the switch
22626 --RTS= for which a relative path argument is never converted.
22628 @node Specifying Configuration Pragmas,Project Files and Main Subprograms,Switches and Project Files,gnatmake and Project Files
22629 @anchor{gnat_ugn/tools_supporting_project_files id5}@anchor{1c7}@anchor{gnat_ugn/tools_supporting_project_files specifying-configuration-pragmas}@anchor{7d}
22630 @subsection Specifying Configuration Pragmas
22633 When using @emph{gnatmake} with project files, if there exists a file
22634 @code{gnat.adc} that contains configuration pragmas, this file will be
22637 Configuration pragmas can be defined by means of the following attributes in
22638 project files: @cite{Global_Configuration_Pragmas} in package @cite{Builder}
22639 and @cite{Local_Configuration_Pragmas} in package @cite{Compiler}.
22641 Both these attributes are single string attributes. Their values is the path
22642 name of a file containing configuration pragmas. If a path name is relative,
22643 then it is relative to the project directory of the project file where the
22644 attribute is defined.
22646 When compiling a source, the configuration pragmas used are, in order,
22647 those listed in the file designated by attribute
22648 @cite{Global_Configuration_Pragmas} in package @cite{Builder} of the main
22649 project file, if it is specified, and those listed in the file designated by
22650 attribute @cite{Local_Configuration_Pragmas} in package @cite{Compiler} of
22651 the project file of the source, if it exists.
22653 @node Project Files and Main Subprograms,Library Project Files,Specifying Configuration Pragmas,gnatmake and Project Files
22654 @anchor{gnat_ugn/tools_supporting_project_files id6}@anchor{1c8}@anchor{gnat_ugn/tools_supporting_project_files project-files-and-main-subprograms}@anchor{e2}
22655 @subsection Project Files and Main Subprograms
22658 When using a project file, you can invoke @emph{gnatmake}
22659 with one or several main subprograms, by specifying their source files on the
22665 $ gnatmake -Pprj main1.adb main2.adb main3.adb
22669 Each of these needs to be a source file of the same project, except
22670 when the switch @cite{-u} is used.
22672 When @cite{-u} is not used, all the mains need to be sources of the
22673 same project, one of the project in the tree rooted at the project specified
22674 on the command line. The package @cite{Builder} of this common project, the
22675 "main project" is the one that is considered by @emph{gnatmake}.
22677 When @cite{-u} is used, the specified source files may be in projects
22678 imported directly or indirectly by the project specified on the command line.
22679 Note that if such a source file is not part of the project specified on the
22680 command line, the switches found in package @cite{Builder} of the
22681 project specified on the command line, if any, that are transmitted
22682 to the compiler will still be used, not those found in the project file of
22685 When using a project file, you can also invoke @emph{gnatmake} without
22686 explicitly specifying any main, and the effect depends on whether you have
22687 defined the @cite{Main} attribute. This attribute has a string list value,
22688 where each element in the list is the name of a source file (the file
22689 extension is optional) that contains a unit that can be a main subprogram.
22691 If the @cite{Main} attribute is defined in a project file as a non-empty
22692 string list and the switch @emph{-u} is not used on the command
22693 line, then invoking @emph{gnatmake} with this project file but without any
22694 main on the command line is equivalent to invoking @emph{gnatmake} with all
22695 the file names in the @cite{Main} attribute on the command line.
22703 for Main use ("main1.adb", "main2.adb", "main3.adb");
22708 With this project file, @cite{"gnatmake -Pprj"}
22710 @cite{"gnatmake -Pprj main1.adb main2.adb main3.adb"}.
22712 When the project attribute @cite{Main} is not specified, or is specified
22713 as an empty string list, or when the switch @emph{-u} is used on the command
22714 line, then invoking @emph{gnatmake} with no main on the command line will
22715 result in all immediate sources of the project file being checked, and
22716 potentially recompiled. Depending on the presence of the switch @emph{-u},
22717 sources from other project files on which the immediate sources of the main
22718 project file depend are also checked and potentially recompiled. In other
22719 words, the @emph{-u} switch is applied to all of the immediate sources of the
22722 When no main is specified on the command line and attribute @cite{Main} exists
22723 and includes several mains, or when several mains are specified on the
22724 command line, the default switches in package @cite{Builder} will
22725 be used for all mains, even if there are specific switches
22726 specified for one or several mains.
22728 But the switches from package @cite{Binder} or @cite{Linker} will be
22729 the specific switches for each main, if they are specified.
22731 @node Library Project Files,,Project Files and Main Subprograms,gnatmake and Project Files
22732 @anchor{gnat_ugn/tools_supporting_project_files id7}@anchor{1c9}@anchor{gnat_ugn/tools_supporting_project_files library-project-files}@anchor{1ca}
22733 @subsection Library Project Files
22736 When @emph{gnatmake} is invoked with a main project file that is a library
22737 project file, it is not allowed to specify one or more mains on the command
22740 When a library project file is specified, switches @cite{-b} and
22741 @cite{-l} have special meanings.
22747 @cite{-b} is only allowed for stand-alone libraries. It indicates
22748 to @emph{gnatmake} that @emph{gnatbind} should be invoked for the
22752 @cite{-l} may be used for all library projects. It indicates
22753 to @emph{gnatmake} that the binder generated file should be compiled
22754 (in the case of a stand-alone library) and that the library should be built.
22757 @node The GNAT Driver and Project Files,,gnatmake and Project Files,Tools Supporting Project Files
22758 @anchor{gnat_ugn/tools_supporting_project_files id8}@anchor{1cb}@anchor{gnat_ugn/tools_supporting_project_files the-gnat-driver-and-project-files}@anchor{11f}
22759 @section The GNAT Driver and Project Files
22762 A number of GNAT tools beyond @emph{gnatmake}
22763 can benefit from project files:
22788 However, none of these tools can be invoked
22789 directly with a project file switch (@emph{-P}).
22790 They must be invoked through the @emph{gnat} driver.
22792 The @emph{gnat} driver is a wrapper that accepts a number of commands and
22793 calls the corresponding tool. It was designed initially for VMS platforms (to
22794 convert VMS qualifiers to Unix-style switches), but it is now available on all
22797 On non-VMS platforms, the @emph{gnat} driver accepts the following commands
22798 (case insensitive):
22805 BIND to invoke @emph{gnatbind}
22808 CHOP to invoke @emph{gnatchop}
22811 CLEAN to invoke @emph{gnatclean}
22814 COMP or COMPILE to invoke the compiler
22817 FIND to invoke @emph{gnatfind}
22820 KR or KRUNCH to invoke @emph{gnatkr}
22823 LINK to invoke @emph{gnatlink}
22826 LS or LIST to invoke @emph{gnatls}
22829 MAKE to invoke @emph{gnatmake}
22832 NAME to invoke @emph{gnatname}
22835 PREP or PREPROCESS to invoke @emph{gnatprep}
22838 XREF to invoke @emph{gnatxref}
22841 Note that the command
22842 @emph{gnatmake -c -f -u} is used to invoke the compiler.
22844 On non-VMS platforms, between @emph{gnat} and the command, two
22845 special switches may be used:
22851 @emph{-v} to display the invocation of the tool.
22854 @emph{-dn} to prevent the @emph{gnat} driver from removing
22855 the temporary files it has created. These temporary files are
22856 configuration files and temporary file list files.
22859 The command may be followed by switches and arguments for the invoked
22865 $ gnat bind -C main.ali
22867 $ gnat chop foo.txt
22871 Switches may also be put in text files, one switch per line, and the text
22872 files may be specified with their path name preceded by '@@'.
22877 $ gnat bind @@args.txt main.ali
22881 In addition, for the following commands the project file related switches
22882 (@emph{-P}, @emph{-X} and @emph{-vPx}) may be used in addition to
22883 the switches of the invoking tool:
22909 For each of the following commands, there is optionally a corresponding
22910 package in the main project.
22917 package @cite{Binder} for command BIND (invoking @cite{gnatbind})
22920 package @cite{Compiler} for command COMP or COMPILE (invoking the compiler)
22923 package @cite{Cross_Reference} for command XREF (invoking @cite{gnatxref})
22926 package @cite{Finder} for command FIND (invoking @cite{gnatfind})
22929 package @cite{Gnatls} for command LS or LIST (invoking @cite{gnatls})
22932 package @cite{Linker} for command LINK (invoking @cite{gnatlink})
22935 Package @cite{Gnatls} has a unique attribute @cite{Switches},
22936 a simple variable with a string list value. It contains switches
22937 for the invocation of @cite{gnatls}.
22952 All other packages have two attribute @cite{Switches} and
22953 @cite{Default_Switches}.
22955 @cite{Switches} is an indexed attribute, indexed by the
22956 source file name, that has a string list value: the switches to be
22957 used when the tool corresponding to the package is invoked for the specific
22960 @cite{Default_Switches} is an attribute,
22961 indexed by the programming language that has a string list value.
22962 @cite{Default_Switches ("Ada")} contains the
22963 switches for the invocation of the tool corresponding
22964 to the package, except if a specific @cite{Switches} attribute
22965 is specified for the source file.
22972 for Source_Dirs use ("");
22980 package Compiler is
22981 for Default_Switches ("Ada")
22987 for Default_Switches ("Ada")
22993 for Default_Switches ("Ada")
22995 for Switches ("main.adb")
23002 for Default_Switches ("Ada")
23007 package Cross_Reference is
23008 for Default_Switches ("Ada")
23013 end Cross_Reference;
23018 With the above project file, commands such as
23023 $ gnat comp -Pproj main
23024 $ gnat ls -Pproj main
23025 $ gnat xref -Pproj main
23026 $ gnat bind -Pproj main.ali
23027 $ gnat link -Pproj main.ali
23031 will set up the environment properly and invoke the tool with the switches
23032 found in the package corresponding to the tool:
23033 @cite{Default_Switches ("Ada")} for all tools,
23034 except @cite{Switches ("main.adb")}
23035 for @cite{gnatlink}.
23038 @node GNAT Utility Programs,GNAT and Program Execution,Tools Supporting Project Files,Top
23039 @anchor{gnat_ugn/gnat_utility_programs doc}@anchor{1cc}@anchor{gnat_ugn/gnat_utility_programs gnat-utility-programs}@anchor{d}@anchor{gnat_ugn/gnat_utility_programs id1}@anchor{1cd}
23040 @chapter GNAT Utility Programs
23043 This chapter describes a number of utility programs:
23050 @ref{22,,The File Cleanup Utility gnatclean}
23053 @ref{23,,The GNAT Library Browser gnatls}
23056 @ref{24,,The Cross-Referencing Tools gnatxref and gnatfind}
23059 @ref{25,,The Ada to HTML Converter gnathtml}
23062 Other GNAT utilities are described elsewhere in this manual:
23068 @ref{5b,,Handling Arbitrary File Naming Conventions with gnatname}
23071 @ref{65,,File Name Krunching with gnatkr}
23074 @ref{38,,Renaming Files with gnatchop}
23077 @ref{19,,Preprocessing with gnatprep}
23081 * The File Cleanup Utility gnatclean::
23082 * The GNAT Library Browser gnatls::
23083 * The Cross-Referencing Tools gnatxref and gnatfind::
23084 * The Ada to HTML Converter gnathtml::
23088 @node The File Cleanup Utility gnatclean,The GNAT Library Browser gnatls,,GNAT Utility Programs
23089 @anchor{gnat_ugn/gnat_utility_programs id2}@anchor{1ce}@anchor{gnat_ugn/gnat_utility_programs the-file-cleanup-utility-gnatclean}@anchor{22}
23090 @section The File Cleanup Utility @emph{gnatclean}
23093 @geindex File cleanup tool
23097 @cite{gnatclean} is a tool that allows the deletion of files produced by the
23098 compiler, binder and linker, including ALI files, object files, tree files,
23099 expanded source files, library files, interface copy source files, binder
23100 generated files and executable files.
23103 * Running gnatclean::
23104 * Switches for gnatclean::
23108 @node Running gnatclean,Switches for gnatclean,,The File Cleanup Utility gnatclean
23109 @anchor{gnat_ugn/gnat_utility_programs running-gnatclean}@anchor{1cf}@anchor{gnat_ugn/gnat_utility_programs id3}@anchor{1d0}
23110 @subsection Running @cite{gnatclean}
23113 The @cite{gnatclean} command has the form:
23118 $ gnatclean switches `names`
23122 where @cite{names} is a list of source file names. Suffixes @code{.ads} and
23123 @code{adb} may be omitted. If a project file is specified using switch
23124 @code{-P}, then @cite{names} may be completely omitted.
23126 In normal mode, @cite{gnatclean} delete the files produced by the compiler and,
23127 if switch @cite{-c} is not specified, by the binder and
23128 the linker. In informative-only mode, specified by switch
23129 @cite{-n}, the list of files that would have been deleted in
23130 normal mode is listed, but no file is actually deleted.
23132 @node Switches for gnatclean,,Running gnatclean,The File Cleanup Utility gnatclean
23133 @anchor{gnat_ugn/gnat_utility_programs id4}@anchor{1d1}@anchor{gnat_ugn/gnat_utility_programs switches-for-gnatclean}@anchor{1d2}
23134 @subsection Switches for @cite{gnatclean}
23137 @cite{gnatclean} recognizes the following switches:
23139 @geindex --version (gnatclean)
23144 @item @code{--version}
23146 Display Copyright and version, then exit disregarding all other options.
23149 @geindex --help (gnatclean)
23154 @item @code{--help}
23156 If @emph{--version} was not used, display usage, then exit disregarding
23159 @item @code{--subdirs=@emph{subdir}}
23161 Actual object directory of each project file is the subdirectory subdir of the
23162 object directory specified or defaulted in the project file.
23164 @item @code{--unchecked-shared-lib-imports}
23166 By default, shared library projects are not allowed to import static library
23167 projects. When this switch is used on the command line, this restriction is
23171 @geindex -c (gnatclean)
23178 Only attempt to delete the files produced by the compiler, not those produced
23179 by the binder or the linker. The files that are not to be deleted are library
23180 files, interface copy files, binder generated files and executable files.
23183 @geindex -D (gnatclean)
23188 @item @code{-D @emph{dir}}
23190 Indicate that ALI and object files should normally be found in directory @cite{dir}.
23193 @geindex -F (gnatclean)
23200 When using project files, if some errors or warnings are detected during
23201 parsing and verbose mode is not in effect (no use of switch
23202 -v), then error lines start with the full path name of the project
23203 file, rather than its simple file name.
23206 @geindex -h (gnatclean)
23213 Output a message explaining the usage of @cite{gnatclean}.
23216 @geindex -n (gnatclean)
23223 Informative-only mode. Do not delete any files. Output the list of the files
23224 that would have been deleted if this switch was not specified.
23227 @geindex -P (gnatclean)
23232 @item @code{-P@emph{project}}
23234 Use project file @cite{project}. Only one such switch can be used.
23235 When cleaning a project file, the files produced by the compilation of the
23236 immediate sources or inherited sources of the project files are to be
23237 deleted. This is not depending on the presence or not of executable names
23238 on the command line.
23241 @geindex -q (gnatclean)
23248 Quiet output. If there are no errors, do not output anything, except in
23249 verbose mode (switch -v) or in informative-only mode
23253 @geindex -r (gnatclean)
23260 When a project file is specified (using switch -P),
23261 clean all imported and extended project files, recursively. If this switch
23262 is not specified, only the files related to the main project file are to be
23263 deleted. This switch has no effect if no project file is specified.
23266 @geindex -v (gnatclean)
23276 @geindex -vP (gnatclean)
23281 @item @code{-vP@emph{x}}
23283 Indicates the verbosity of the parsing of GNAT project files.
23284 @ref{e3,,Switches Related to Project Files}.
23287 @geindex -X (gnatclean)
23292 @item @code{-X@emph{name}=@emph{value}}
23294 Indicates that external variable @cite{name} has the value @cite{value}.
23295 The Project Manager will use this value for occurrences of
23296 @cite{external(name)} when parsing the project file.
23297 @ref{e3,,Switches Related to Project Files}.
23300 @geindex -aO (gnatclean)
23305 @item @code{-aO@emph{dir}}
23307 When searching for ALI and object files, look in directory @cite{dir}.
23310 @geindex -I (gnatclean)
23315 @item @code{-I@emph{dir}}
23317 Equivalent to @code{-aO@emph{dir}}.
23320 @geindex -I- (gnatclean)
23322 @geindex Source files
23323 @geindex suppressing search
23330 Do not look for ALI or object files in the directory
23331 where @cite{gnatclean} was invoked.
23334 @node The GNAT Library Browser gnatls,The Cross-Referencing Tools gnatxref and gnatfind,The File Cleanup Utility gnatclean,GNAT Utility Programs
23335 @anchor{gnat_ugn/gnat_utility_programs the-gnat-library-browser-gnatls}@anchor{23}@anchor{gnat_ugn/gnat_utility_programs id5}@anchor{1d3}
23336 @section The GNAT Library Browser @cite{gnatls}
23339 @geindex Library browser
23343 @cite{gnatls} is a tool that outputs information about compiled
23344 units. It gives the relationship between objects, unit names and source
23345 files. It can also be used to check the source dependencies of a unit
23346 as well as various characteristics.
23348 Note: to invoke @cite{gnatls} with a project file, use the @cite{gnat}
23349 driver (see @ref{11f,,The GNAT Driver and Project Files}).
23353 * Switches for gnatls::
23354 * Example of gnatls Usage::
23358 @node Running gnatls,Switches for gnatls,,The GNAT Library Browser gnatls
23359 @anchor{gnat_ugn/gnat_utility_programs id6}@anchor{1d4}@anchor{gnat_ugn/gnat_utility_programs running-gnatls}@anchor{1d5}
23360 @subsection Running @cite{gnatls}
23363 The @cite{gnatls} command has the form
23368 $ gnatls switches `object_or_ali_file`
23372 The main argument is the list of object or @code{ali} files
23373 (see @ref{44,,The Ada Library Information Files})
23374 for which information is requested.
23376 In normal mode, without additional option, @cite{gnatls} produces a
23377 four-column listing. Each line represents information for a specific
23378 object. The first column gives the full path of the object, the second
23379 column gives the name of the principal unit in this object, the third
23380 column gives the status of the source and the fourth column gives the
23381 full path of the source representing this unit.
23382 Here is a simple example of use:
23388 ./demo1.o demo1 DIF demo1.adb
23389 ./demo2.o demo2 OK demo2.adb
23390 ./hello.o h1 OK hello.adb
23391 ./instr-child.o instr.child MOK instr-child.adb
23392 ./instr.o instr OK instr.adb
23393 ./tef.o tef DIF tef.adb
23394 ./text_io_example.o text_io_example OK text_io_example.adb
23395 ./tgef.o tgef DIF tgef.adb
23399 The first line can be interpreted as follows: the main unit which is
23401 object file @code{demo1.o} is demo1, whose main source is in
23402 @code{demo1.adb}. Furthermore, the version of the source used for the
23403 compilation of demo1 has been modified (DIF). Each source file has a status
23404 qualifier which can be:
23409 @item @emph{OK (unchanged)}
23411 The version of the source file used for the compilation of the
23412 specified unit corresponds exactly to the actual source file.
23414 @item @emph{MOK (slightly modified)}
23416 The version of the source file used for the compilation of the
23417 specified unit differs from the actual source file but not enough to
23418 require recompilation. If you use gnatmake with the qualifier
23419 @emph{-m (minimal recompilation)}, a file marked
23420 MOK will not be recompiled.
23422 @item @emph{DIF (modified)}
23424 No version of the source found on the path corresponds to the source
23425 used to build this object.
23427 @item @emph{??? (file not found)}
23429 No source file was found for this unit.
23431 @item @emph{HID (hidden, unchanged version not first on PATH)}
23433 The version of the source that corresponds exactly to the source used
23434 for compilation has been found on the path but it is hidden by another
23435 version of the same source that has been modified.
23438 @node Switches for gnatls,Example of gnatls Usage,Running gnatls,The GNAT Library Browser gnatls
23439 @anchor{gnat_ugn/gnat_utility_programs id7}@anchor{1d6}@anchor{gnat_ugn/gnat_utility_programs switches-for-gnatls}@anchor{1d7}
23440 @subsection Switches for @cite{gnatls}
23443 @cite{gnatls} recognizes the following switches:
23445 @geindex --version (gnatls)
23450 @item @code{--version}
23452 Display Copyright and version, then exit disregarding all other options.
23455 @geindex --help (gnatls)
23460 @item @code{*--help}
23462 If @emph{--version} was not used, display usage, then exit disregarding
23466 @geindex -a (gnatls)
23473 Consider all units, including those of the predefined Ada library.
23474 Especially useful with @emph{-d}.
23477 @geindex -d (gnatls)
23484 List sources from which specified units depend on.
23487 @geindex -h (gnatls)
23494 Output the list of options.
23497 @geindex -o (gnatls)
23504 Only output information about object files.
23507 @geindex -s (gnatls)
23514 Only output information about source files.
23517 @geindex -u (gnatls)
23524 Only output information about compilation units.
23527 @geindex -files (gnatls)
23532 @item @code{-files=@emph{file}}
23534 Take as arguments the files listed in text file @cite{file}.
23535 Text file @cite{file} may contain empty lines that are ignored.
23536 Each nonempty line should contain the name of an existing file.
23537 Several such switches may be specified simultaneously.
23540 @geindex -aO (gnatls)
23542 @geindex -aI (gnatls)
23544 @geindex -I (gnatls)
23546 @geindex -I- (gnatls)
23551 @item @code{-aO@emph{dir}}, @code{-aI@emph{dir}}, @code{-I@emph{dir}}, @code{-I-}, @code{-nostdinc}
23553 Source path manipulation. Same meaning as the equivalent @emph{gnatmake}
23554 flags (@ref{df,,Switches for gnatmake}).
23557 @geindex -aP (gnatls)
23562 @item @code{-aP@emph{dir}}
23564 Add @cite{dir} at the beginning of the project search dir.
23567 @geindex --RTS (gnatls)
23572 @item @code{--RTS=@emph{rts-path}`}
23574 Specifies the default location of the runtime library. Same meaning as the
23575 equivalent @emph{gnatmake} flag (@ref{df,,Switches for gnatmake}).
23578 @geindex -v (gnatls)
23585 Verbose mode. Output the complete source, object and project paths. Do not use
23586 the default column layout but instead use long format giving as much as
23587 information possible on each requested units, including special
23588 characteristics such as:
23594 @emph{Preelaborable}: The unit is preelaborable in the Ada sense.
23597 @emph{No_Elab_Code}: No elaboration code has been produced by the compiler for this unit.
23600 @emph{Pure}: The unit is pure in the Ada sense.
23603 @emph{Elaborate_Body}: The unit contains a pragma Elaborate_Body.
23606 @emph{Remote_Types}: The unit contains a pragma Remote_Types.
23609 @emph{Shared_Passive}: The unit contains a pragma Shared_Passive.
23612 @emph{Predefined}: This unit is part of the predefined environment and cannot be modified
23616 @emph{Remote_Call_Interface}: The unit contains a pragma Remote_Call_Interface.
23620 @node Example of gnatls Usage,,Switches for gnatls,The GNAT Library Browser gnatls
23621 @anchor{gnat_ugn/gnat_utility_programs id8}@anchor{1d8}@anchor{gnat_ugn/gnat_utility_programs example-of-gnatls-usage}@anchor{1d9}
23622 @subsection Example of @cite{gnatls} Usage
23625 Example of using the verbose switch. Note how the source and
23626 object paths are affected by the -I switch.
23631 $ gnatls -v -I.. demo1.o
23633 GNATLS 5.03w (20041123-34)
23634 Copyright 1997-2004 Free Software Foundation, Inc.
23636 Source Search Path:
23637 <Current_Directory>
23639 /home/comar/local/adainclude/
23641 Object Search Path:
23642 <Current_Directory>
23644 /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
23646 Project Search Path:
23647 <Current_Directory>
23648 /home/comar/local/lib/gnat/
23653 Kind => subprogram body
23654 Flags => No_Elab_Code
23655 Source => demo1.adb modified
23659 The following is an example of use of the dependency list.
23660 Note the use of the -s switch
23661 which gives a straight list of source files. This can be useful for
23662 building specialized scripts.
23667 $ gnatls -d demo2.o
23668 ./demo2.o demo2 OK demo2.adb
23674 $ gnatls -d -s -a demo1.o
23676 /home/comar/local/adainclude/ada.ads
23677 /home/comar/local/adainclude/a-finali.ads
23678 /home/comar/local/adainclude/a-filico.ads
23679 /home/comar/local/adainclude/a-stream.ads
23680 /home/comar/local/adainclude/a-tags.ads
23683 /home/comar/local/adainclude/gnat.ads
23684 /home/comar/local/adainclude/g-io.ads
23686 /home/comar/local/adainclude/system.ads
23687 /home/comar/local/adainclude/s-exctab.ads
23688 /home/comar/local/adainclude/s-finimp.ads
23689 /home/comar/local/adainclude/s-finroo.ads
23690 /home/comar/local/adainclude/s-secsta.ads
23691 /home/comar/local/adainclude/s-stalib.ads
23692 /home/comar/local/adainclude/s-stoele.ads
23693 /home/comar/local/adainclude/s-stratt.ads
23694 /home/comar/local/adainclude/s-tasoli.ads
23695 /home/comar/local/adainclude/s-unstyp.ads
23696 /home/comar/local/adainclude/unchconv.ads
23700 @node The Cross-Referencing Tools gnatxref and gnatfind,The Ada to HTML Converter gnathtml,The GNAT Library Browser gnatls,GNAT Utility Programs
23701 @anchor{gnat_ugn/gnat_utility_programs the-cross-referencing-tools-gnatxref-and-gnatfind}@anchor{24}@anchor{gnat_ugn/gnat_utility_programs id9}@anchor{1da}
23702 @section The Cross-Referencing Tools @cite{gnatxref} and @cite{gnatfind}
23709 The compiler generates cross-referencing information (unless
23710 you set the @code{-gnatx} switch), which are saved in the @code{.ali} files.
23711 This information indicates where in the source each entity is declared and
23712 referenced. Note that entities in package Standard are not included, but
23713 entities in all other predefined units are included in the output.
23715 Before using any of these two tools, you need to compile successfully your
23716 application, so that GNAT gets a chance to generate the cross-referencing
23719 The two tools @cite{gnatxref} and @cite{gnatfind} take advantage of this
23720 information to provide the user with the capability to easily locate the
23721 declaration and references to an entity. These tools are quite similar,
23722 the difference being that @cite{gnatfind} is intended for locating
23723 definitions and/or references to a specified entity or entities, whereas
23724 @cite{gnatxref} is oriented to generating a full report of all
23727 To use these tools, you must not compile your application using the
23728 @emph{-gnatx} switch on the @emph{gnatmake} command line
23729 (see @ref{1d,,Building with gnatmake}). Otherwise, cross-referencing
23730 information will not be generated.
23732 Note: to invoke @cite{gnatxref} or @cite{gnatfind} with a project file,
23733 use the @cite{gnat} driver (see @ref{11f,,The GNAT Driver and Project Files}).
23736 * gnatxref Switches::
23737 * gnatfind Switches::
23738 * Project Files for gnatxref and gnatfind::
23739 * Regular Expressions in gnatfind and gnatxref::
23740 * Examples of gnatxref Usage::
23741 * Examples of gnatfind Usage::
23745 @node gnatxref Switches,gnatfind Switches,,The Cross-Referencing Tools gnatxref and gnatfind
23746 @anchor{gnat_ugn/gnat_utility_programs id10}@anchor{1db}@anchor{gnat_ugn/gnat_utility_programs gnatxref-switches}@anchor{1dc}
23747 @subsection @cite{gnatxref} Switches
23750 The command invocation for @cite{gnatxref} is:
23755 $ gnatxref [`switches`] `sourcefile1` [`sourcefile2` ...]
23764 @item @emph{sourcefile1} [, @emph{sourcefile2} ...]
23766 identify the source files for which a report is to be generated. The
23767 'with'ed units will be processed too. You must provide at least one file.
23769 These file names are considered to be regular expressions, so for instance
23770 specifying @code{source*.adb} is the same as giving every file in the current
23771 directory whose name starts with @code{source} and whose extension is
23774 You shouldn't specify any directory name, just base names. @emph{gnatxref}
23775 and @emph{gnatfind} will be able to locate these files by themselves using
23776 the source path. If you specify directories, no result is produced.
23779 The following switches are available for @emph{gnatxref}:
23781 @geindex --version (gnatxref)
23786 @item @code{-version}
23788 Display Copyright and version, then exit disregarding all other options.
23791 @geindex --help (gnatxref)
23798 If @emph{--version} was not used, display usage, then exit disregarding
23802 @geindex -a (gnatxref)
23809 If this switch is present, @cite{gnatfind} and @cite{gnatxref} will parse
23810 the read-only files found in the library search path. Otherwise, these files
23811 will be ignored. This option can be used to protect Gnat sources or your own
23812 libraries from being parsed, thus making @cite{gnatfind} and @cite{gnatxref}
23813 much faster, and their output much smaller. Read-only here refers to access
23814 or permissions status in the file system for the current user.
23817 @geindex -aIDIR (gnatxref)
23822 @item @code{aI@emph{DIR}}
23824 When looking for source files also look in directory DIR. The order in which
23825 source file search is undertaken is the same as for @emph{gnatmake}.
23828 @geindex -aODIR (gnatxref)
23833 @item @code{aO@emph{DIR}}
23835 When searching for library and object files, look in directory
23836 DIR. The order in which library files are searched is the same as for
23840 @geindex -nostdinc (gnatxref)
23845 @item @code{nostdinc}
23847 Do not look for sources in the system default directory.
23850 @geindex -nostdlib (gnatxref)
23855 @item @code{nostdlib}
23857 Do not look for library files in the system default directory.
23860 @geindex --ext (gnatxref)
23865 @item @code{-ext=@emph{extension}}
23867 Specify an alternate ali file extension. The default is @cite{ali} and other
23868 extensions (e.g. @cite{gli} for C/C++ sources when using @emph{-fdump-xref})
23869 may be specified via this switch. Note that if this switch overrides the
23870 default, which means that only the new extension will be considered.
23873 @geindex --RTS (gnatxref)
23878 @item @code{-RTS=@emph{rts-path}}
23880 Specifies the default location of the runtime library. Same meaning as the
23881 equivalent @emph{gnatmake} flag (@ref{df,,Switches for gnatmake}).
23884 @geindex -d (gnatxref)
23891 If this switch is set @cite{gnatxref} will output the parent type
23892 reference for each matching derived types.
23895 @geindex -f (gnatxref)
23902 If this switch is set, the output file names will be preceded by their
23903 directory (if the file was found in the search path). If this switch is
23904 not set, the directory will not be printed.
23907 @geindex -g (gnatxref)
23914 If this switch is set, information is output only for library-level
23915 entities, ignoring local entities. The use of this switch may accelerate
23916 @cite{gnatfind} and @cite{gnatxref}.
23919 @geindex -IDIR (gnatxref)
23924 @item @code{I@emph{DIR}}
23926 Equivalent to @code{-aODIR -aIDIR}.
23929 @geindex -pFILE (gnatxref)
23934 @item @code{p@emph{FILE}}
23936 Specify a project file to use @ref{b,,GNAT Project Manager}.
23937 If you need to use the @code{.gpr}
23938 project files, you should use gnatxref through the GNAT driver
23939 (@emph{gnat xref -Pproject}).
23941 By default, @cite{gnatxref} and @cite{gnatfind} will try to locate a
23942 project file in the current directory.
23944 If a project file is either specified or found by the tools, then the content
23945 of the source directory and object directory lines are added as if they
23946 had been specified respectively by @code{-aI}
23951 Output only unused symbols. This may be really useful if you give your
23952 main compilation unit on the command line, as @cite{gnatxref} will then
23953 display every unused entity and 'with'ed package.
23957 Instead of producing the default output, @cite{gnatxref} will generate a
23958 @code{tags} file that can be used by vi. For examples how to use this
23959 feature, see @ref{1dd,,Examples of gnatxref Usage}. The tags file is output
23960 to the standard output, thus you will have to redirect it to a file.
23963 All these switches may be in any order on the command line, and may even
23964 appear after the file names. They need not be separated by spaces, thus
23965 you can say @code{gnatxref -ag} instead of @code{gnatxref -a -g}.
23967 @node gnatfind Switches,Project Files for gnatxref and gnatfind,gnatxref Switches,The Cross-Referencing Tools gnatxref and gnatfind
23968 @anchor{gnat_ugn/gnat_utility_programs id11}@anchor{1de}@anchor{gnat_ugn/gnat_utility_programs gnatfind-switches}@anchor{1df}
23969 @subsection @cite{gnatfind} Switches
23972 The command invocation for @cite{gnatfind} is:
23977 $ gnatfind [`switches`] `pattern`[:`sourcefile`[:`line`[:`column`]]]
23978 [`file1` `file2` ...]
23982 with the following iterpretation of the command arguments:
23987 @item @emph{pattern}
23989 An entity will be output only if it matches the regular expression found
23990 in @cite{pattern}, see @ref{1e0,,Regular Expressions in gnatfind and gnatxref}.
23992 Omitting the pattern is equivalent to specifying @code{*}, which
23993 will match any entity. Note that if you do not provide a pattern, you
23994 have to provide both a sourcefile and a line.
23996 Entity names are given in Latin-1, with uppercase/lowercase equivalence
23997 for matching purposes. At the current time there is no support for
23998 8-bit codes other than Latin-1, or for wide characters in identifiers.
24000 @item @emph{sourcefile}
24002 @cite{gnatfind} will look for references, bodies or declarations
24003 of symbols referenced in @code{sourcefile}, at line @cite{line}
24004 and column @cite{column}. See @ref{1e1,,Examples of gnatfind Usage}
24005 for syntax examples.
24009 A decimal integer identifying the line number containing
24010 the reference to the entity (or entities) to be located.
24012 @item @emph{column}
24014 A decimal integer identifying the exact location on the
24015 line of the first character of the identifier for the
24016 entity reference. Columns are numbered from 1.
24018 @item @emph{file1 file2 ...}
24020 The search will be restricted to these source files. If none are given, then
24021 the search will be conducted for every library file in the search path.
24022 These files must appear only after the pattern or sourcefile.
24024 These file names are considered to be regular expressions, so for instance
24025 specifying @code{source*.adb} is the same as giving every file in the current
24026 directory whose name starts with @code{source} and whose extension is
24029 The location of the spec of the entity will always be displayed, even if it
24030 isn't in one of @code{file1}, @code{file2}, ... The
24031 occurrences of the entity in the separate units of the ones given on the
24032 command line will also be displayed.
24034 Note that if you specify at least one file in this part, @cite{gnatfind} may
24035 sometimes not be able to find the body of the subprograms.
24038 At least one of 'sourcefile' or 'pattern' has to be present on
24041 The following switches are available:
24043 @geindex --version (gnatfind)
24048 @item @code{--version}
24050 Display Copyright and version, then exit disregarding all other options.
24053 @geindex --help (gnatfind)
24060 If @emph{--version} was not used, display usage, then exit disregarding
24064 @geindex -a (gnatfind)
24071 If this switch is present, @cite{gnatfind} and @cite{gnatxref} will parse
24072 the read-only files found in the library search path. Otherwise, these files
24073 will be ignored. This option can be used to protect Gnat sources or your own
24074 libraries from being parsed, thus making @cite{gnatfind} and @cite{gnatxref}
24075 much faster, and their output much smaller. Read-only here refers to access
24076 or permission status in the file system for the current user.
24079 @geindex -aIDIR (gnatfind)
24084 @item @code{aI@emph{DIR}}
24086 When looking for source files also look in directory DIR. The order in which
24087 source file search is undertaken is the same as for @emph{gnatmake}.
24090 @geindex -aODIR (gnatfind)
24095 @item @code{aO@emph{DIR}}
24097 When searching for library and object files, look in directory
24098 DIR. The order in which library files are searched is the same as for
24102 @geindex -nostdinc (gnatfind)
24107 @item @code{nostdinc}
24109 Do not look for sources in the system default directory.
24112 @geindex -nostdlib (gnatfind)
24117 @item @code{nostdlib}
24119 Do not look for library files in the system default directory.
24122 @geindex --ext (gnatfind)
24127 @item @code{-ext=@emph{extension}}
24129 Specify an alternate ali file extension. The default is @cite{ali} and other
24130 extensions (e.g. @cite{gli} for C/C++ sources when using @emph{-fdump-xref})
24131 may be specified via this switch. Note that if this switch overrides the
24132 default, which means that only the new extension will be considered.
24135 @geindex --RTS (gnatfind)
24140 @item @code{-RTS=@emph{rts-path}}
24142 Specifies the default location of the runtime library. Same meaning as the
24143 equivalent @emph{gnatmake} flag (@ref{df,,Switches for gnatmake}).
24146 @geindex -d (gnatfind)
24153 If this switch is set, then @cite{gnatfind} will output the parent type
24154 reference for each matching derived types.
24157 @geindex -e (gnatfind)
24164 By default, @cite{gnatfind} accept the simple regular expression set for
24165 @cite{pattern}. If this switch is set, then the pattern will be
24166 considered as full Unix-style regular expression.
24169 @geindex -f (gnatfind)
24176 If this switch is set, the output file names will be preceded by their
24177 directory (if the file was found in the search path). If this switch is
24178 not set, the directory will not be printed.
24181 @geindex -g (gnatfind)
24188 If this switch is set, information is output only for library-level
24189 entities, ignoring local entities. The use of this switch may accelerate
24190 @cite{gnatfind} and @cite{gnatxref}.
24193 @geindex -IDIR (gnatfind)
24198 @item @code{I@emph{DIR}}
24200 Equivalent to @code{-aODIR -aIDIR}.
24203 @geindex -pFILE (gnatfind)
24208 @item @code{p@emph{FILE}}
24210 Specify a project file (@ref{b,,GNAT Project Manager}) to use.
24211 By default, @cite{gnatxref} and @cite{gnatfind} will try to locate a
24212 project file in the current directory.
24214 If a project file is either specified or found by the tools, then the content
24215 of the source directory and object directory lines are added as if they
24216 had been specified respectively by @code{-aI} and
24220 @geindex -r (gnatfind)
24227 By default, @cite{gnatfind} will output only the information about the
24228 declaration, body or type completion of the entities. If this switch is
24229 set, the @cite{gnatfind} will locate every reference to the entities in
24230 the files specified on the command line (or in every file in the search
24231 path if no file is given on the command line).
24234 @geindex -s (gnatfind)
24241 If this switch is set, then @cite{gnatfind} will output the content
24242 of the Ada source file lines were the entity was found.
24245 @geindex -t (gnatfind)
24252 If this switch is set, then @cite{gnatfind} will output the type hierarchy for
24253 the specified type. It act like -d option but recursively from parent
24254 type to parent type. When this switch is set it is not possible to
24255 specify more than one file.
24258 All these switches may be in any order on the command line, and may even
24259 appear after the file names. They need not be separated by spaces, thus
24260 you can say @code{gnatxref -ag} instead of
24261 @code{gnatxref -a -g}.
24263 As stated previously, gnatfind will search in every directory in the
24264 search path. You can force it to look only in the current directory if
24265 you specify @cite{*} at the end of the command line.
24267 @node Project Files for gnatxref and gnatfind,Regular Expressions in gnatfind and gnatxref,gnatfind Switches,The Cross-Referencing Tools gnatxref and gnatfind
24268 @anchor{gnat_ugn/gnat_utility_programs project-files-for-gnatxref-and-gnatfind}@anchor{1e2}@anchor{gnat_ugn/gnat_utility_programs id12}@anchor{1e3}
24269 @subsection Project Files for @emph{gnatxref} and @emph{gnatfind}
24272 Project files allow a programmer to specify how to compile its
24273 application, where to find sources, etc. These files are used
24274 primarily by GPS, but they can also be used
24275 by the two tools @cite{gnatxref} and @cite{gnatfind}.
24277 A project file name must end with @code{.gpr}. If a single one is
24278 present in the current directory, then @cite{gnatxref} and @cite{gnatfind} will
24279 extract the information from it. If multiple project files are found, none of
24280 them is read, and you have to use the @code{-p} switch to specify the one
24283 The following lines can be included, even though most of them have default
24284 values which can be used in most cases.
24285 The lines can be entered in any order in the file.
24286 Except for @code{src_dir} and @code{obj_dir}, you can only have one instance of
24287 each line. If you have multiple instances, only the last one is taken into
24297 @item @emph{src_dir=DIR}
24299 [default: @cite{"./"}].
24300 Specifies a directory where to look for source files. Multiple @cite{src_dir}
24301 lines can be specified and they will be searched in the order they
24309 @item @emph{obj_dir=DIR}
24311 [default: @cite{"./"}].
24312 Specifies a directory where to look for object and library files. Multiple
24313 @cite{obj_dir} lines can be specified, and they will be searched in the order
24321 @item @emph{comp_opt=SWITCHES}
24323 [default: @cite{""}].
24324 Creates a variable which can be referred to subsequently by using
24325 the @cite{$@{comp_opt@}} notation. This is intended to store the default
24326 switches given to @emph{gnatmake} and @emph{gcc}.
24333 @item @emph{bind_opt=SWITCHES}
24335 [default: @cite{""}].
24336 Creates a variable which can be referred to subsequently by using
24337 the @code{$@emph{bind_opt}} notation. This is intended to store the default
24338 switches given to @emph{gnatbind}.
24345 @item @emph{link_opt=SWITCHES}
24347 [default: @cite{""}].
24348 Creates a variable which can be referred to subsequently by using
24349 the @code{$@emph{link_opt}} notation. This is intended to store the default
24350 switches given to @emph{gnatlink}.
24357 @item @emph{main=EXECUTABLE}
24359 [default: @cite{""}].
24360 Specifies the name of the executable for the application. This variable can
24361 be referred to in the following lines by using the @code{@emph{$@{main}} notation.
24368 @item @emph{comp_cmd=COMMAND}
24370 [default: @cite{"gcc -c -I$@{src_dir@} -g -gnatq"}].
24371 Specifies the command used to compile a single file in the application.
24378 @item @emph{make_cmd=COMMAND}
24380 [default: @cite{"gnatmake $@{main@} -aI$@{src_dir@} -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@} -bargs $@{bind_opt@} -largs $@{link_opt@}"}].
24381 Specifies the command used to recompile the whole application.
24388 @item @emph{run_cmd=COMMAND}
24390 [default: @cite{"$@{main@}"}].
24391 Specifies the command used to run the application.
24398 @item @emph{debug_cmd=COMMAND}
24400 [default: @cite{"gdb $@{main@}"}].
24401 Specifies the command used to debug the application
24405 @emph{gnatxref} and @emph{gnatfind} only take into account the
24406 @cite{src_dir} and @cite{obj_dir} lines, and ignore the others.
24408 @node Regular Expressions in gnatfind and gnatxref,Examples of gnatxref Usage,Project Files for gnatxref and gnatfind,The Cross-Referencing Tools gnatxref and gnatfind
24409 @anchor{gnat_ugn/gnat_utility_programs id13}@anchor{1e4}@anchor{gnat_ugn/gnat_utility_programs regular-expressions-in-gnatfind-and-gnatxref}@anchor{1e0}
24410 @subsection Regular Expressions in @cite{gnatfind} and @cite{gnatxref}
24413 As specified in the section about @emph{gnatfind}, the pattern can be a
24414 regular expression. Two kinds of regular expressions
24424 @item @emph{Globbing pattern}
24426 These are the most common regular expression. They are the same as are
24427 generally used in a Unix shell command line, or in a DOS session.
24429 Here is a more formal grammar:
24433 term ::= elmt -- matches elmt
24434 term ::= elmt elmt -- concatenation (elmt then elmt)
24435 term ::= * -- any string of 0 or more characters
24436 term ::= ? -- matches any character
24437 term ::= [char @{char@}] -- matches any character listed
24438 term ::= [char - char] -- matches any character in range
24446 @item @emph{Full regular expression}
24448 The second set of regular expressions is much more powerful. This is the
24449 type of regular expressions recognized by utilities such as @code{grep}.
24451 The following is the form of a regular expression, expressed in same BNF
24452 style as is found in the Ada Reference Manual:
24455 regexp ::= term @{| term@} -- alternation (term or term ...)
24457 term ::= item @{item@} -- concatenation (item then item)
24459 item ::= elmt -- match elmt
24460 item ::= elmt * -- zero or more elmt's
24461 item ::= elmt + -- one or more elmt's
24462 item ::= elmt ? -- matches elmt or nothing
24464 elmt ::= nschar -- matches given character
24465 elmt ::= [nschar @{nschar@}] -- matches any character listed
24466 elmt ::= [^ nschar @{nschar@}] -- matches any character not listed
24467 elmt ::= [char - char] -- matches chars in given range
24468 elmt ::= \\ char -- matches given character
24469 elmt ::= . -- matches any single character
24470 elmt ::= ( regexp ) -- parens used for grouping
24472 char ::= any character, including special characters
24473 nschar ::= any character except ()[].*+?^
24476 Here are a few examples:
24483 @item @code{abcde|fghi}
24485 will match any of the two strings @code{abcde} and @code{fghi},
24489 will match any string like @code{abd}, @code{abcd}, @code{abccd},
24490 @code{abcccd}, and so on,
24492 @item @code{[a-z]+}
24494 will match any string which has only lowercase characters in it (and at
24495 least one character.
24501 @node Examples of gnatxref Usage,Examples of gnatfind Usage,Regular Expressions in gnatfind and gnatxref,The Cross-Referencing Tools gnatxref and gnatfind
24502 @anchor{gnat_ugn/gnat_utility_programs examples-of-gnatxref-usage}@anchor{1dd}@anchor{gnat_ugn/gnat_utility_programs id14}@anchor{1e5}
24503 @subsection Examples of @cite{gnatxref} Usage
24508 * Using gnatxref with vi::
24512 @node General Usage,Using gnatxref with vi,,Examples of gnatxref Usage
24513 @anchor{gnat_ugn/gnat_utility_programs general-usage}@anchor{1e6}
24514 @subsubsection General Usage
24517 For the following examples, we will consider the following units:
24525 3: procedure Foo (B : in Integer);
24532 1: package body Main is
24533 2: procedure Foo (B : in Integer) is
24544 2: procedure Print (B : Integer);
24549 The first thing to do is to recompile your application (for instance, in
24550 that case just by doing a @code{gnatmake main}, so that GNAT generates
24551 the cross-referencing information.
24552 You can then issue any of the following commands:
24560 @code{gnatxref main.adb}
24561 @cite{gnatxref} generates cross-reference information for main.adb
24562 and every unit 'with'ed by main.adb.
24564 The output would be:
24572 Decl: main.ads 3:20
24573 Body: main.adb 2:20
24574 Ref: main.adb 4:13 5:13 6:19
24577 Ref: main.adb 6:8 7:8
24587 Decl: main.ads 3:15
24588 Body: main.adb 2:15
24591 Body: main.adb 1:14
24594 Ref: main.adb 6:12 7:12
24598 This shows that the entity @cite{Main} is declared in main.ads, line 2, column 9,
24599 its body is in main.adb, line 1, column 14 and is not referenced any where.
24601 The entity @cite{Print} is declared in bar.ads, line 2, column 15 and it
24602 is referenced in main.adb, line 6 column 12 and line 7 column 12.
24605 @code{gnatxref package1.adb package2.ads}
24606 @cite{gnatxref} will generates cross-reference information for
24607 package1.adb, package2.ads and any other package 'with'ed by any
24612 @node Using gnatxref with vi,,General Usage,Examples of gnatxref Usage
24613 @anchor{gnat_ugn/gnat_utility_programs using-gnatxref-with-vi}@anchor{1e7}
24614 @subsubsection Using gnatxref with vi
24617 @cite{gnatxref} can generate a tags file output, which can be used
24618 directly from @emph{vi}. Note that the standard version of @emph{vi}
24619 will not work properly with overloaded symbols. Consider using another
24620 free implementation of @emph{vi}, such as @emph{vim}.
24625 $ gnatxref -v gnatfind.adb > tags
24629 The following command will generate the tags file for @cite{gnatfind} itself
24630 (if the sources are in the search path!):
24635 $ gnatxref -v gnatfind.adb > tags
24639 From @emph{vi}, you can then use the command @code{:tag @emph{entity}}
24640 (replacing @cite{entity} by whatever you are looking for), and vi will
24641 display a new file with the corresponding declaration of entity.
24643 @node Examples of gnatfind Usage,,Examples of gnatxref Usage,The Cross-Referencing Tools gnatxref and gnatfind
24644 @anchor{gnat_ugn/gnat_utility_programs id15}@anchor{1e8}@anchor{gnat_ugn/gnat_utility_programs examples-of-gnatfind-usage}@anchor{1e1}
24645 @subsection Examples of @cite{gnatfind} Usage
24652 @code{gnatfind -f xyz:main.adb}
24653 Find declarations for all entities xyz referenced at least once in
24654 main.adb. The references are search in every library file in the search
24657 The directories will be printed as well (as the @code{-f}
24660 The output will look like:
24665 directory/main.ads:106:14: xyz <= declaration
24666 directory/main.adb:24:10: xyz <= body
24667 directory/foo.ads:45:23: xyz <= declaration
24671 I.e., one of the entities xyz found in main.adb is declared at
24672 line 12 of main.ads (and its body is in main.adb), and another one is
24673 declared at line 45 of foo.ads
24676 @code{gnatfind -fs xyz:main.adb}
24677 This is the same command as the previous one, but @cite{gnatfind} will
24678 display the content of the Ada source file lines.
24680 The output will look like:
24683 directory/main.ads:106:14: xyz <= declaration
24685 directory/main.adb:24:10: xyz <= body
24687 directory/foo.ads:45:23: xyz <= declaration
24691 This can make it easier to find exactly the location your are looking
24695 @code{gnatfind -r "*x*":main.ads:123 foo.adb}
24696 Find references to all entities containing an x that are
24697 referenced on line 123 of main.ads.
24698 The references will be searched only in main.ads and foo.adb.
24701 @code{gnatfind main.ads:123}
24702 Find declarations and bodies for all entities that are referenced on
24703 line 123 of main.ads.
24705 This is the same as @code{gnatfind "*":main.adb:123`}
24708 @code{gnatfind mydir/main.adb:123:45}
24709 Find the declaration for the entity referenced at column 45 in
24710 line 123 of file main.adb in directory mydir. Note that it
24711 is usual to omit the identifier name when the column is given,
24712 since the column position identifies a unique reference.
24714 The column has to be the beginning of the identifier, and should not
24715 point to any character in the middle of the identifier.
24718 @node The Ada to HTML Converter gnathtml,,The Cross-Referencing Tools gnatxref and gnatfind,GNAT Utility Programs
24719 @anchor{gnat_ugn/gnat_utility_programs the-ada-to-html-converter-gnathtml}@anchor{25}@anchor{gnat_ugn/gnat_utility_programs id16}@anchor{1e9}
24720 @section The Ada to HTML Converter @cite{gnathtml}
24725 @emph{gnathtml} is a Perl script that allows Ada source files to be browsed using
24726 standard Web browsers. For installation information, see @ref{1ea,,Installing gnathtml}.
24728 Ada reserved keywords are highlighted in a bold font and Ada comments in
24729 a blue font. Unless your program was compiled with the gcc @emph{-gnatx}
24730 switch to suppress the generation of cross-referencing information, user
24731 defined variables and types will appear in a different color; you will
24732 be able to click on any identifier and go to its declaration.
24735 * Invoking gnathtml::
24736 * Installing gnathtml::
24740 @node Invoking gnathtml,Installing gnathtml,,The Ada to HTML Converter gnathtml
24741 @anchor{gnat_ugn/gnat_utility_programs invoking-gnathtml}@anchor{1eb}@anchor{gnat_ugn/gnat_utility_programs id17}@anchor{1ec}
24742 @subsection Invoking @emph{gnathtml}
24745 The command line is as follows:
24750 $ perl gnathtml.pl [`switches`] `ada-files`
24754 You can specify as many Ada files as you want. @cite{gnathtml} will generate
24755 an html file for every ada file, and a global file called @code{index.htm}.
24756 This file is an index of every identifier defined in the files.
24758 The following switches are available:
24760 @geindex -83 (gnathtml)
24767 Only the Ada 83 subset of keywords will be highlighted.
24770 @geindex -cc (gnathtml)
24775 @item @code{cc @emph{color}}
24777 This option allows you to change the color used for comments. The default
24778 value is green. The color argument can be any name accepted by html.
24781 @geindex -d (gnathtml)
24788 If the Ada files depend on some other files (for instance through
24789 @cite{with} clauses, the latter files will also be converted to html.
24790 Only the files in the user project will be converted to html, not the files
24791 in the run-time library itself.
24794 @geindex -D (gnathtml)
24801 This command is the same as @emph{-d} above, but @emph{gnathtml} will
24802 also look for files in the run-time library, and generate html files for them.
24805 @geindex -ext (gnathtml)
24810 @item @code{ext @emph{extension}}
24812 This option allows you to change the extension of the generated HTML files.
24813 If you do not specify an extension, it will default to @code{htm}.
24816 @geindex -f (gnathtml)
24823 By default, gnathtml will generate html links only for global entities
24824 ('with'ed units, global variables and types,...). If you specify
24825 @emph{-f} on the command line, then links will be generated for local
24829 @geindex -l (gnathtml)
24834 @item @code{l @emph{number}}
24836 If this switch is provided and @cite{number} is not 0, then
24837 @cite{gnathtml} will number the html files every @cite{number} line.
24840 @geindex -I (gnathtml)
24845 @item @code{I @emph{dir}}
24847 Specify a directory to search for library files (@code{.ALI} files) and
24848 source files. You can provide several -I switches on the command line,
24849 and the directories will be parsed in the order of the command line.
24852 @geindex -o (gnathtml)
24857 @item @code{o @emph{dir}}
24859 Specify the output directory for html files. By default, gnathtml will
24860 saved the generated html files in a subdirectory named @code{html/}.
24863 @geindex -p (gnathtml)
24868 @item @code{p @emph{file}}
24870 If you are using Emacs and the most recent Emacs Ada mode, which provides
24871 a full Integrated Development Environment for compiling, checking,
24872 running and debugging applications, you may use @code{.gpr} files
24873 to give the directories where Emacs can find sources and object files.
24875 Using this switch, you can tell gnathtml to use these files.
24876 This allows you to get an html version of your application, even if it
24877 is spread over multiple directories.
24880 @geindex -sc (gnathtml)
24885 @item @code{sc @emph{color}}
24887 This switch allows you to change the color used for symbol
24889 The default value is red. The color argument can be any name accepted by html.
24892 @geindex -t (gnathtml)
24897 @item @code{t @emph{file}}
24899 This switch provides the name of a file. This file contains a list of
24900 file names to be converted, and the effect is exactly as though they had
24901 appeared explicitly on the command line. This
24902 is the recommended way to work around the command line length limit on some
24906 @node Installing gnathtml,,Invoking gnathtml,The Ada to HTML Converter gnathtml
24907 @anchor{gnat_ugn/gnat_utility_programs installing-gnathtml}@anchor{1ea}@anchor{gnat_ugn/gnat_utility_programs id18}@anchor{1ed}
24908 @subsection Installing @cite{gnathtml}
24911 @cite{Perl} needs to be installed on your machine to run this script.
24912 @cite{Perl} is freely available for almost every architecture and
24913 operating system via the Internet.
24915 On Unix systems, you may want to modify the first line of the script
24916 @cite{gnathtml}, to explicitly specify where Perl
24917 is located. The syntax of this line is:
24922 #!full_path_name_to_perl
24926 Alternatively, you may run the script using the following command line:
24931 $ perl gnathtml.pl [`switches`] `files`
24935 @c -- +---------------------------------------------------------------------+
24937 @c -- | The following sections are present only in the PRO and GPL editions |
24939 @c -- +---------------------------------------------------------------------+
24947 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
24949 @node GNAT and Program Execution,Platform-Specific Information,GNAT Utility Programs,Top
24950 @anchor{gnat_ugn/gnat_and_program_execution gnat-and-program-execution}@anchor{e}@anchor{gnat_ugn/gnat_and_program_execution doc}@anchor{1ee}@anchor{gnat_ugn/gnat_and_program_execution id1}@anchor{1ef}
24951 @chapter GNAT and Program Execution
24954 This chapter covers several topics:
24960 @ref{1f0,,Running and Debugging Ada Programs}
24963 @ref{1f1,,Code Coverage and Profiling}
24966 @ref{1f2,,Improving Performance}
24969 @ref{1f3,,Overflow Check Handling in GNAT}
24972 @ref{1f4,,Performing Dimensionality Analysis in GNAT}
24975 @ref{1f5,,Stack Related Facilities}
24978 @ref{1f6,,Memory Management Issues}
24982 * Running and Debugging Ada Programs::
24983 * Code Coverage and Profiling::
24984 * Improving Performance::
24985 * Overflow Check Handling in GNAT::
24986 * Performing Dimensionality Analysis in GNAT::
24987 * Stack Related Facilities::
24988 * Memory Management Issues::
24992 @node Running and Debugging Ada Programs,Code Coverage and Profiling,,GNAT and Program Execution
24993 @anchor{gnat_ugn/gnat_and_program_execution id2}@anchor{1f0}@anchor{gnat_ugn/gnat_and_program_execution running-and-debugging-ada-programs}@anchor{26}
24994 @section Running and Debugging Ada Programs
24999 This section discusses how to debug Ada programs.
25001 An incorrect Ada program may be handled in three ways by the GNAT compiler:
25007 The illegality may be a violation of the static semantics of Ada. In
25008 that case GNAT diagnoses the constructs in the program that are illegal.
25009 It is then a straightforward matter for the user to modify those parts of
25013 The illegality may be a violation of the dynamic semantics of Ada. In
25014 that case the program compiles and executes, but may generate incorrect
25015 results, or may terminate abnormally with some exception.
25018 When presented with a program that contains convoluted errors, GNAT
25019 itself may terminate abnormally without providing full diagnostics on
25020 the incorrect user program.
25028 * The GNAT Debugger GDB::
25030 * Introduction to GDB Commands::
25031 * Using Ada Expressions::
25032 * Calling User-Defined Subprograms::
25033 * Using the next Command in a Function::
25034 * Stopping When Ada Exceptions Are Raised::
25036 * Debugging Generic Units::
25037 * Remote Debugging with gdbserver::
25038 * GNAT Abnormal Termination or Failure to Terminate::
25039 * Naming Conventions for GNAT Source Files::
25040 * Getting Internal Debugging Information::
25041 * Stack Traceback::
25045 @node The GNAT Debugger GDB,Running GDB,,Running and Debugging Ada Programs
25046 @anchor{gnat_ugn/gnat_and_program_execution the-gnat-debugger-gdb}@anchor{1f7}@anchor{gnat_ugn/gnat_and_program_execution id3}@anchor{1f8}
25047 @subsection The GNAT Debugger GDB
25050 @cite{GDB} is a general purpose, platform-independent debugger that
25051 can be used to debug mixed-language programs compiled with @emph{gcc},
25052 and in particular is capable of debugging Ada programs compiled with
25053 GNAT. The latest versions of @cite{GDB} are Ada-aware and can handle
25054 complex Ada data structures.
25056 See @cite{Debugging with GDB},
25057 for full details on the usage of @cite{GDB}, including a section on
25058 its usage on programs. This manual should be consulted for full
25059 details. The section that follows is a brief introduction to the
25060 philosophy and use of @cite{GDB}.
25062 When GNAT programs are compiled, the compiler optionally writes debugging
25063 information into the generated object file, including information on
25064 line numbers, and on declared types and variables. This information is
25065 separate from the generated code. It makes the object files considerably
25066 larger, but it does not add to the size of the actual executable that
25067 will be loaded into memory, and has no impact on run-time performance. The
25068 generation of debug information is triggered by the use of the
25069 -g switch in the @emph{gcc} or @emph{gnatmake} command
25070 used to carry out the compilations. It is important to emphasize that
25071 the use of these options does not change the generated code.
25073 The debugging information is written in standard system formats that
25074 are used by many tools, including debuggers and profilers. The format
25075 of the information is typically designed to describe C types and
25076 semantics, but GNAT implements a translation scheme which allows full
25077 details about Ada types and variables to be encoded into these
25078 standard C formats. Details of this encoding scheme may be found in
25079 the file exp_dbug.ads in the GNAT source distribution. However, the
25080 details of this encoding are, in general, of no interest to a user,
25081 since @cite{GDB} automatically performs the necessary decoding.
25083 When a program is bound and linked, the debugging information is
25084 collected from the object files, and stored in the executable image of
25085 the program. Again, this process significantly increases the size of
25086 the generated executable file, but it does not increase the size of
25087 the executable program itself. Furthermore, if this program is run in
25088 the normal manner, it runs exactly as if the debug information were
25089 not present, and takes no more actual memory.
25091 However, if the program is run under control of @cite{GDB}, the
25092 debugger is activated. The image of the program is loaded, at which
25093 point it is ready to run. If a run command is given, then the program
25094 will run exactly as it would have if @cite{GDB} were not present. This
25095 is a crucial part of the @cite{GDB} design philosophy. @cite{GDB} is
25096 entirely non-intrusive until a breakpoint is encountered. If no
25097 breakpoint is ever hit, the program will run exactly as it would if no
25098 debugger were present. When a breakpoint is hit, @cite{GDB} accesses
25099 the debugging information and can respond to user commands to inspect
25100 variables, and more generally to report on the state of execution.
25102 @node Running GDB,Introduction to GDB Commands,The GNAT Debugger GDB,Running and Debugging Ada Programs
25103 @anchor{gnat_ugn/gnat_and_program_execution id4}@anchor{1f9}@anchor{gnat_ugn/gnat_and_program_execution running-gdb}@anchor{1fa}
25104 @subsection Running GDB
25107 This section describes how to initiate the debugger.
25109 The debugger can be launched from a @cite{GPS} menu or
25110 directly from the command line. The description below covers the latter use.
25111 All the commands shown can be used in the @cite{GPS} debug console window,
25112 but there are usually more GUI-based ways to achieve the same effect.
25114 The command to run @cite{GDB} is
25123 where @cite{program} is the name of the executable file. This
25124 activates the debugger and results in a prompt for debugger commands.
25125 The simplest command is simply @cite{run}, which causes the program to run
25126 exactly as if the debugger were not present. The following section
25127 describes some of the additional commands that can be given to @cite{GDB}.
25129 @node Introduction to GDB Commands,Using Ada Expressions,Running GDB,Running and Debugging Ada Programs
25130 @anchor{gnat_ugn/gnat_and_program_execution introduction-to-gdb-commands}@anchor{1fb}@anchor{gnat_ugn/gnat_and_program_execution id5}@anchor{1fc}
25131 @subsection Introduction to GDB Commands
25134 @cite{GDB} contains a large repertoire of commands.
25135 See @cite{Debugging with GDB} for extensive documentation on the use
25136 of these commands, together with examples of their use. Furthermore,
25137 the command @emph{help} invoked from within GDB activates a simple help
25138 facility which summarizes the available commands and their options.
25139 In this section we summarize a few of the most commonly
25140 used commands to give an idea of what @cite{GDB} is about. You should create
25141 a simple program with debugging information and experiment with the use of
25142 these @cite{GDB} commands on the program as you read through the
25152 @item @emph{set args `arguments`}
25154 The @cite{arguments} list above is a list of arguments to be passed to
25155 the program on a subsequent run command, just as though the arguments
25156 had been entered on a normal invocation of the program. The @cite{set args}
25157 command is not needed if the program does not require arguments.
25166 The @cite{run} command causes execution of the program to start from
25167 the beginning. If the program is already running, that is to say if
25168 you are currently positioned at a breakpoint, then a prompt will ask
25169 for confirmation that you want to abandon the current execution and
25177 @item @emph{breakpoint `location`}
25179 The breakpoint command sets a breakpoint, that is to say a point at which
25180 execution will halt and @cite{GDB} will await further
25181 commands. @cite{location} is
25182 either a line number within a file, given in the format @cite{file:linenumber},
25183 or it is the name of a subprogram. If you request that a breakpoint be set on
25184 a subprogram that is overloaded, a prompt will ask you to specify on which of
25185 those subprograms you want to breakpoint. You can also
25186 specify that all of them should be breakpointed. If the program is run
25187 and execution encounters the breakpoint, then the program
25188 stops and @cite{GDB} signals that the breakpoint was encountered by
25189 printing the line of code before which the program is halted.
25196 @item @emph{catch exception `name`}
25198 This command causes the program execution to stop whenever exception
25199 @cite{name} is raised. If @cite{name} is omitted, then the execution is
25200 suspended when any exception is raised.
25207 @item @emph{print `expression`}
25209 This will print the value of the given expression. Most simple
25210 Ada expression formats are properly handled by @cite{GDB}, so the expression
25211 can contain function calls, variables, operators, and attribute references.
25218 @item @emph{continue}
25220 Continues execution following a breakpoint, until the next breakpoint or the
25221 termination of the program.
25230 Executes a single line after a breakpoint. If the next statement
25231 is a subprogram call, execution continues into (the first statement of)
25232 the called subprogram.
25241 Executes a single line. If this line is a subprogram call, executes and
25242 returns from the call.
25251 Lists a few lines around the current source location. In practice, it
25252 is usually more convenient to have a separate edit window open with the
25253 relevant source file displayed. Successive applications of this command
25254 print subsequent lines. The command can be given an argument which is a
25255 line number, in which case it displays a few lines around the specified one.
25262 @item @emph{backtrace}
25264 Displays a backtrace of the call chain. This command is typically
25265 used after a breakpoint has occurred, to examine the sequence of calls that
25266 leads to the current breakpoint. The display includes one line for each
25267 activation record (frame) corresponding to an active subprogram.
25276 At a breakpoint, @cite{GDB} can display the values of variables local
25277 to the current frame. The command @cite{up} can be used to
25278 examine the contents of other active frames, by moving the focus up
25279 the stack, that is to say from callee to caller, one frame at a time.
25288 Moves the focus of @cite{GDB} down from the frame currently being
25289 examined to the frame of its callee (the reverse of the previous command),
25296 @item @emph{frame `n`}
25298 Inspect the frame with the given number. The value 0 denotes the frame
25299 of the current breakpoint, that is to say the top of the call stack.
25308 Kills the child process in which the program is running under GDB.
25309 This may be useful for several purposes:
25315 It allows you to recompile and relink your program, since on many systems
25316 you cannot regenerate an executable file while it is running in a process.
25319 You can run your program outside the debugger, on systems that do not
25320 permit executing a program outside GDB while breakpoints are set
25324 It allows you to debug a core dump rather than a running process.
25329 The above list is a very short introduction to the commands that
25330 @cite{GDB} provides. Important additional capabilities, including conditional
25331 breakpoints, the ability to execute command sequences on a breakpoint,
25332 the ability to debug at the machine instruction level and many other
25333 features are described in detail in @cite{Debugging with GDB}.
25334 Note that most commands can be abbreviated
25335 (for example, c for continue, bt for backtrace).
25337 @node Using Ada Expressions,Calling User-Defined Subprograms,Introduction to GDB Commands,Running and Debugging Ada Programs
25338 @anchor{gnat_ugn/gnat_and_program_execution id6}@anchor{1fd}@anchor{gnat_ugn/gnat_and_program_execution using-ada-expressions}@anchor{1fe}
25339 @subsection Using Ada Expressions
25342 @geindex Ada expressions (in gdb)
25344 @cite{GDB} supports a fairly large subset of Ada expression syntax, with some
25345 extensions. The philosophy behind the design of this subset is
25353 That @cite{GDB} should provide basic literals and access to operations for
25354 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
25355 leaving more sophisticated computations to subprograms written into the
25356 program (which therefore may be called from @cite{GDB}).
25359 That type safety and strict adherence to Ada language restrictions
25360 are not particularly relevant in a debugging context.
25363 That brevity is important to the @cite{GDB} user.
25367 Thus, for brevity, the debugger acts as if there were
25368 implicit @cite{with} and @cite{use} clauses in effect for all user-written
25369 packages, thus making it unnecessary to fully qualify most names with
25370 their packages, regardless of context. Where this causes ambiguity,
25371 @cite{GDB} asks the user's intent.
25373 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
25375 @node Calling User-Defined Subprograms,Using the next Command in a Function,Using Ada Expressions,Running and Debugging Ada Programs
25376 @anchor{gnat_ugn/gnat_and_program_execution id7}@anchor{1ff}@anchor{gnat_ugn/gnat_and_program_execution calling-user-defined-subprograms}@anchor{200}
25377 @subsection Calling User-Defined Subprograms
25380 An important capability of @cite{GDB} is the ability to call user-defined
25381 subprograms while debugging. This is achieved simply by entering
25382 a subprogram call statement in the form:
25387 call subprogram-name (parameters)
25391 The keyword @cite{call} can be omitted in the normal case where the
25392 @cite{subprogram-name} does not coincide with any of the predefined
25393 @cite{GDB} commands.
25395 The effect is to invoke the given subprogram, passing it the
25396 list of parameters that is supplied. The parameters can be expressions and
25397 can include variables from the program being debugged. The
25398 subprogram must be defined
25399 at the library level within your program, and @cite{GDB} will call the
25400 subprogram within the environment of your program execution (which
25401 means that the subprogram is free to access or even modify variables
25402 within your program).
25404 The most important use of this facility is in allowing the inclusion of
25405 debugging routines that are tailored to particular data structures
25406 in your program. Such debugging routines can be written to provide a suitably
25407 high-level description of an abstract type, rather than a low-level dump
25408 of its physical layout. After all, the standard
25409 @cite{GDB print} command only knows the physical layout of your
25410 types, not their abstract meaning. Debugging routines can provide information
25411 at the desired semantic level and are thus enormously useful.
25413 For example, when debugging GNAT itself, it is crucial to have access to
25414 the contents of the tree nodes used to represent the program internally.
25415 But tree nodes are represented simply by an integer value (which in turn
25416 is an index into a table of nodes).
25417 Using the @cite{print} command on a tree node would simply print this integer
25418 value, which is not very useful. But the PN routine (defined in file
25419 treepr.adb in the GNAT sources) takes a tree node as input, and displays
25420 a useful high level representation of the tree node, which includes the
25421 syntactic category of the node, its position in the source, the integers
25422 that denote descendant nodes and parent node, as well as varied
25423 semantic information. To study this example in more detail, you might want to
25424 look at the body of the PN procedure in the stated file.
25426 Another useful application of this capability is to deal with situations of
25427 complex data which are not handled suitably by GDB. For example, if you specify
25428 Convention Fortran for a multi-dimensional array, GDB does not know that
25429 the ordering of array elements has been switched and will not properly
25430 address the array elements. In such a case, instead of trying to print the
25431 elements directly from GDB, you can write a callable procedure that prints
25432 the elements in the desired format.
25434 @node Using the next Command in a Function,Stopping When Ada Exceptions Are Raised,Calling User-Defined Subprograms,Running and Debugging Ada Programs
25435 @anchor{gnat_ugn/gnat_and_program_execution using-the-next-command-in-a-function}@anchor{201}@anchor{gnat_ugn/gnat_and_program_execution id8}@anchor{202}
25436 @subsection Using the @emph{next} Command in a Function
25439 When you use the @cite{next} command in a function, the current source
25440 location will advance to the next statement as usual. A special case
25441 arises in the case of a @cite{return} statement.
25443 Part of the code for a return statement is the 'epilogue' of the function.
25444 This is the code that returns to the caller. There is only one copy of
25445 this epilogue code, and it is typically associated with the last return
25446 statement in the function if there is more than one return. In some
25447 implementations, this epilogue is associated with the first statement
25450 The result is that if you use the @cite{next} command from a return
25451 statement that is not the last return statement of the function you
25452 may see a strange apparent jump to the last return statement or to
25453 the start of the function. You should simply ignore this odd jump.
25454 The value returned is always that from the first return statement
25455 that was stepped through.
25457 @node Stopping When Ada Exceptions Are Raised,Ada Tasks,Using the next Command in a Function,Running and Debugging Ada Programs
25458 @anchor{gnat_ugn/gnat_and_program_execution stopping-when-ada-exceptions-are-raised}@anchor{203}@anchor{gnat_ugn/gnat_and_program_execution id9}@anchor{204}
25459 @subsection Stopping When Ada Exceptions Are Raised
25462 @geindex Exceptions (in gdb)
25464 You can set catchpoints that stop the program execution when your program
25465 raises selected exceptions.
25474 @item @emph{catch exception}
25476 Set a catchpoint that stops execution whenever (any task in the) program
25477 raises any exception.
25484 @item @emph{catch exception `name`}
25486 Set a catchpoint that stops execution whenever (any task in the) program
25487 raises the exception @cite{name}.
25494 @item @emph{catch exception unhandled}
25496 Set a catchpoint that stops executing whenever (any task in the) program
25497 raises an exception for which there is no handler.
25504 @item @emph{info exceptions}, @emph{info exceptions `regexp`}
25506 The @cite{info exceptions} command permits the user to examine all defined
25507 exceptions within Ada programs. With a regular expression, @cite{regexp}, as
25508 argument, prints out only those exceptions whose name matches @cite{regexp}.
25512 @geindex Tasks (in gdb)
25514 @node Ada Tasks,Debugging Generic Units,Stopping When Ada Exceptions Are Raised,Running and Debugging Ada Programs
25515 @anchor{gnat_ugn/gnat_and_program_execution ada-tasks}@anchor{205}@anchor{gnat_ugn/gnat_and_program_execution id10}@anchor{206}
25516 @subsection Ada Tasks
25519 @cite{GDB} allows the following task-related commands:
25528 @item @emph{info tasks}
25530 This command shows a list of current Ada tasks, as in the following example:
25534 ID TID P-ID Thread Pri State Name
25535 1 8088000 0 807e000 15 Child Activation Wait main_task
25536 2 80a4000 1 80ae000 15 Accept/Select Wait b
25537 3 809a800 1 80a4800 15 Child Activation Wait a
25538 * 4 80ae800 3 80b8000 15 Running c
25541 In this listing, the asterisk before the first task indicates it to be the
25542 currently running task. The first column lists the task ID that is used
25543 to refer to tasks in the following commands.
25547 @geindex Breakpoints and tasks
25553 @emph{break `linespec` task `taskid`}, @emph{break `linespec` task `taskid` if ...}
25557 These commands are like the @cite{break ... thread ...}.
25558 @cite{linespec} specifies source lines.
25560 Use the qualifier @code{task @emph{taskid}} with a breakpoint command
25561 to specify that you only want @cite{GDB} to stop the program when a
25562 particular Ada task reaches this breakpoint. @cite{taskid} is one of the
25563 numeric task identifiers assigned by @cite{GDB}, shown in the first
25564 column of the @code{info tasks} display.
25566 If you do not specify @code{task @emph{taskid}} when you set a
25567 breakpoint, the breakpoint applies to @emph{all} tasks of your
25570 You can use the @cite{task} qualifier on conditional breakpoints as
25571 well; in this case, place @code{task @emph{taskid}} before the
25572 breakpoint condition (before the @cite{if}).
25576 @geindex Task switching (in gdb)
25582 @emph{task `taskno`}
25586 This command allows switching to the task referred by @cite{taskno}. In
25587 particular, this allows browsing of the backtrace of the specified
25588 task. It is advisable to switch back to the original task before
25589 continuing execution otherwise the scheduling of the program may be
25594 For more detailed information on the tasking support,
25595 see @cite{Debugging with GDB}.
25597 @geindex Debugging Generic Units
25601 @node Debugging Generic Units,Remote Debugging with gdbserver,Ada Tasks,Running and Debugging Ada Programs
25602 @anchor{gnat_ugn/gnat_and_program_execution debugging-generic-units}@anchor{207}@anchor{gnat_ugn/gnat_and_program_execution id11}@anchor{208}
25603 @subsection Debugging Generic Units
25606 GNAT always uses code expansion for generic instantiation. This means that
25607 each time an instantiation occurs, a complete copy of the original code is
25608 made, with appropriate substitutions of formals by actuals.
25610 It is not possible to refer to the original generic entities in
25611 @cite{GDB}, but it is always possible to debug a particular instance of
25612 a generic, by using the appropriate expanded names. For example, if we have
25619 generic package k is
25620 procedure kp (v1 : in out integer);
25624 procedure kp (v1 : in out integer) is
25630 package k1 is new k;
25631 package k2 is new k;
25633 var : integer := 1;
25644 Then to break on a call to procedure kp in the k2 instance, simply
25650 (gdb) break g.k2.kp
25654 When the breakpoint occurs, you can step through the code of the
25655 instance in the normal manner and examine the values of local variables, as for
25658 @geindex Remote Debugging with gdbserver
25660 @node Remote Debugging with gdbserver,GNAT Abnormal Termination or Failure to Terminate,Debugging Generic Units,Running and Debugging Ada Programs
25661 @anchor{gnat_ugn/gnat_and_program_execution remote-debugging-with-gdbserver}@anchor{209}@anchor{gnat_ugn/gnat_and_program_execution id12}@anchor{20a}
25662 @subsection Remote Debugging with gdbserver
25665 On platforms where gdbserver is supported, it is possible to use this tool
25666 to debug your application remotely. This can be useful in situations
25667 where the program needs to be run on a target host that is different
25668 from the host used for development, particularly when the target has
25669 a limited amount of resources (either CPU and/or memory).
25671 To do so, start your program using gdbserver on the target machine.
25672 gdbserver then automatically suspends the execution of your program
25673 at its entry point, waiting for a debugger to connect to it. The
25674 following commands starts an application and tells gdbserver to
25675 wait for a connection with the debugger on localhost port 4444.
25680 $ gdbserver localhost:4444 program
25681 Process program created; pid = 5685
25682 Listening on port 4444
25686 Once gdbserver has started listening, we can tell the debugger to establish
25687 a connection with this gdbserver, and then start the same debugging session
25688 as if the program was being debugged on the same host, directly under
25689 the control of GDB.
25695 (gdb) target remote targethost:4444
25696 Remote debugging using targethost:4444
25697 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
25699 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
25703 Breakpoint 1, foo () at foo.adb:4
25708 It is also possible to use gdbserver to attach to an already running
25709 program, in which case the execution of that program is simply suspended
25710 until the connection between the debugger and gdbserver is established.
25712 For more information on how to use gdbserver, see the @emph{Using the gdbserver Program}
25713 section in @cite{Debugging with GDB}.
25714 GNAT provides support for gdbserver on x86-linux, x86-windows and x86_64-linux.
25716 @geindex Abnormal Termination or Failure to Terminate
25718 @node GNAT Abnormal Termination or Failure to Terminate,Naming Conventions for GNAT Source Files,Remote Debugging with gdbserver,Running and Debugging Ada Programs
25719 @anchor{gnat_ugn/gnat_and_program_execution gnat-abnormal-termination-or-failure-to-terminate}@anchor{20b}@anchor{gnat_ugn/gnat_and_program_execution id13}@anchor{20c}
25720 @subsection GNAT Abnormal Termination or Failure to Terminate
25723 When presented with programs that contain serious errors in syntax
25725 GNAT may on rare occasions experience problems in operation, such
25727 segmentation fault or illegal memory access, raising an internal
25728 exception, terminating abnormally, or failing to terminate at all.
25729 In such cases, you can activate
25730 various features of GNAT that can help you pinpoint the construct in your
25731 program that is the likely source of the problem.
25733 The following strategies are presented in increasing order of
25734 difficulty, corresponding to your experience in using GNAT and your
25735 familiarity with compiler internals.
25741 Run @emph{gcc} with the @emph{-gnatf}. This first
25742 switch causes all errors on a given line to be reported. In its absence,
25743 only the first error on a line is displayed.
25745 The @emph{-gnatdO} switch causes errors to be displayed as soon as they
25746 are encountered, rather than after compilation is terminated. If GNAT
25747 terminates prematurely or goes into an infinite loop, the last error
25748 message displayed may help to pinpoint the culprit.
25751 Run @emph{gcc} with the @emph{-v (verbose)} switch. In this
25752 mode, @emph{gcc} produces ongoing information about the progress of the
25753 compilation and provides the name of each procedure as code is
25754 generated. This switch allows you to find which Ada procedure was being
25755 compiled when it encountered a code generation problem.
25758 @geindex -gnatdc switch
25764 Run @emph{gcc} with the @emph{-gnatdc} switch. This is a GNAT specific
25765 switch that does for the front-end what @emph{-v} does
25766 for the back end. The system prints the name of each unit,
25767 either a compilation unit or nested unit, as it is being analyzed.
25770 Finally, you can start
25771 @cite{gdb} directly on the @cite{gnat1} executable. @cite{gnat1} is the
25772 front-end of GNAT, and can be run independently (normally it is just
25773 called from @emph{gcc}). You can use @cite{gdb} on @cite{gnat1} as you
25774 would on a C program (but @ref{1f7,,The GNAT Debugger GDB} for caveats). The
25775 @cite{where} command is the first line of attack; the variable
25776 @cite{lineno} (seen by @cite{print lineno}), used by the second phase of
25777 @cite{gnat1} and by the @emph{gcc} backend, indicates the source line at
25778 which the execution stopped, and @cite{input_file name} indicates the name of
25782 @node Naming Conventions for GNAT Source Files,Getting Internal Debugging Information,GNAT Abnormal Termination or Failure to Terminate,Running and Debugging Ada Programs
25783 @anchor{gnat_ugn/gnat_and_program_execution naming-conventions-for-gnat-source-files}@anchor{20d}@anchor{gnat_ugn/gnat_and_program_execution id14}@anchor{20e}
25784 @subsection Naming Conventions for GNAT Source Files
25787 In order to examine the workings of the GNAT system, the following
25788 brief description of its organization may be helpful:
25794 Files with prefix @code{sc} contain the lexical scanner.
25797 All files prefixed with @code{par} are components of the parser. The
25798 numbers correspond to chapters of the Ada Reference Manual. For example,
25799 parsing of select statements can be found in @code{par-ch9.adb}.
25802 All files prefixed with @code{sem} perform semantic analysis. The
25803 numbers correspond to chapters of the Ada standard. For example, all
25804 issues involving context clauses can be found in @code{sem_ch10.adb}. In
25805 addition, some features of the language require sufficient special processing
25806 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
25807 dynamic dispatching, etc.
25810 All files prefixed with @code{exp} perform normalization and
25811 expansion of the intermediate representation (abstract syntax tree, or AST).
25812 these files use the same numbering scheme as the parser and semantics files.
25813 For example, the construction of record initialization procedures is done in
25814 @code{exp_ch3.adb}.
25817 The files prefixed with @code{bind} implement the binder, which
25818 verifies the consistency of the compilation, determines an order of
25819 elaboration, and generates the bind file.
25822 The files @code{atree.ads} and @code{atree.adb} detail the low-level
25823 data structures used by the front-end.
25826 The files @code{sinfo.ads} and @code{sinfo.adb} detail the structure of
25827 the abstract syntax tree as produced by the parser.
25830 The files @code{einfo.ads} and @code{einfo.adb} detail the attributes of
25831 all entities, computed during semantic analysis.
25834 Library management issues are dealt with in files with prefix
25837 @geindex Annex A (in Ada Reference Manual)
25840 Ada files with the prefix @code{a-} are children of @cite{Ada}, as
25841 defined in Annex A.
25843 @geindex Annex B (in Ada reference Manual)
25846 Files with prefix @code{i-} are children of @cite{Interfaces}, as
25847 defined in Annex B.
25849 @geindex System (package in Ada Reference Manual)
25852 Files with prefix @code{s-} are children of @cite{System}. This includes
25853 both language-defined children and GNAT run-time routines.
25855 @geindex GNAT (package)
25858 Files with prefix @code{g-} are children of @cite{GNAT}. These are useful
25859 general-purpose packages, fully documented in their specs. All
25860 the other @code{.c} files are modifications of common @emph{gcc} files.
25863 @node Getting Internal Debugging Information,Stack Traceback,Naming Conventions for GNAT Source Files,Running and Debugging Ada Programs
25864 @anchor{gnat_ugn/gnat_and_program_execution id15}@anchor{20f}@anchor{gnat_ugn/gnat_and_program_execution getting-internal-debugging-information}@anchor{210}
25865 @subsection Getting Internal Debugging Information
25868 Most compilers have internal debugging switches and modes. GNAT
25869 does also, except GNAT internal debugging switches and modes are not
25870 secret. A summary and full description of all the compiler and binder
25871 debug flags are in the file @code{debug.adb}. You must obtain the
25872 sources of the compiler to see the full detailed effects of these flags.
25874 The switches that print the source of the program (reconstructed from
25875 the internal tree) are of general interest for user programs, as are the
25877 the full internal tree, and the entity table (the symbol table
25878 information). The reconstructed source provides a readable version of the
25879 program after the front-end has completed analysis and expansion,
25880 and is useful when studying the performance of specific constructs.
25881 For example, constraint checks are indicated, complex aggregates
25882 are replaced with loops and assignments, and tasking primitives
25883 are replaced with run-time calls.
25887 @geindex stack traceback
25889 @geindex stack unwinding
25891 @node Stack Traceback,,Getting Internal Debugging Information,Running and Debugging Ada Programs
25892 @anchor{gnat_ugn/gnat_and_program_execution stack-traceback}@anchor{211}@anchor{gnat_ugn/gnat_and_program_execution id16}@anchor{212}
25893 @subsection Stack Traceback
25896 Traceback is a mechanism to display the sequence of subprogram calls that
25897 leads to a specified execution point in a program. Often (but not always)
25898 the execution point is an instruction at which an exception has been raised.
25899 This mechanism is also known as @emph{stack unwinding} because it obtains
25900 its information by scanning the run-time stack and recovering the activation
25901 records of all active subprograms. Stack unwinding is one of the most
25902 important tools for program debugging.
25904 The first entry stored in traceback corresponds to the deepest calling level,
25905 that is to say the subprogram currently executing the instruction
25906 from which we want to obtain the traceback.
25908 Note that there is no runtime performance penalty when stack traceback
25909 is enabled, and no exception is raised during program execution.
25912 @geindex non-symbolic
25915 * Non-Symbolic Traceback::
25916 * Symbolic Traceback::
25920 @node Non-Symbolic Traceback,Symbolic Traceback,,Stack Traceback
25921 @anchor{gnat_ugn/gnat_and_program_execution non-symbolic-traceback}@anchor{213}@anchor{gnat_ugn/gnat_and_program_execution id17}@anchor{214}
25922 @subsubsection Non-Symbolic Traceback
25925 Note: this feature is not supported on all platforms. See
25926 @code{GNAT.Traceback} spec in @code{g-traceb.ads}
25927 for a complete list of supported platforms.
25929 @subsubheading Tracebacks From an Unhandled Exception
25932 A runtime non-symbolic traceback is a list of addresses of call instructions.
25933 To enable this feature you must use the @emph{-E}
25934 @cite{gnatbind}'s option. With this option a stack traceback is stored as part
25935 of exception information. You can retrieve this information using the
25936 @cite{addr2line} tool.
25938 Here is a simple example:
25947 raise Constraint_Error;
25961 $ gnatmake stb -bargs -E
25964 Execution terminated by unhandled exception
25965 Exception name: CONSTRAINT_ERROR
25967 Call stack traceback locations:
25968 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
25972 As we see the traceback lists a sequence of addresses for the unhandled
25973 exception @cite{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
25974 guess that this exception come from procedure P1. To translate these
25975 addresses into the source lines where the calls appear, the
25976 @cite{addr2line} tool, described below, is invaluable. The use of this tool
25977 requires the program to be compiled with debug information.
25982 $ gnatmake -g stb -bargs -E
25985 Execution terminated by unhandled exception
25986 Exception name: CONSTRAINT_ERROR
25988 Call stack traceback locations:
25989 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
25991 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
25992 0x4011f1 0x77e892a4
25994 00401373 at d:/stb/stb.adb:5
25995 0040138B at d:/stb/stb.adb:10
25996 0040139C at d:/stb/stb.adb:14
25997 00401335 at d:/stb/b~stb.adb:104
25998 004011C4 at /build/.../crt1.c:200
25999 004011F1 at /build/.../crt1.c:222
26000 77E892A4 in ?? at ??:0
26004 The @cite{addr2line} tool has several other useful options:
26009 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
26016 to get the function name corresponding to any location
26020 @code{--demangle=gnat}
26024 to use the gnat decoding mode for the function names.
26025 Note that for binutils version 2.9.x the option is
26026 simply @code{--demangle}.
26032 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
26033 0x40139c 0x401335 0x4011c4 0x4011f1
26035 00401373 in stb.p1 at d:/stb/stb.adb:5
26036 0040138B in stb.p2 at d:/stb/stb.adb:10
26037 0040139C in stb at d:/stb/stb.adb:14
26038 00401335 in main at d:/stb/b~stb.adb:104
26039 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
26040 004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
26044 From this traceback we can see that the exception was raised in
26045 @code{stb.adb} at line 5, which was reached from a procedure call in
26046 @code{stb.adb} at line 10, and so on. The @code{b~std.adb} is the binder file,
26047 which contains the call to the main program.
26048 @ref{120,,Running gnatbind}. The remaining entries are assorted runtime routines,
26049 and the output will vary from platform to platform.
26051 It is also possible to use @cite{GDB} with these traceback addresses to debug
26052 the program. For example, we can break at a given code location, as reported
26053 in the stack traceback:
26062 Furthermore, this feature is not implemented inside Windows DLL. Only
26063 the non-symbolic traceback is reported in this case.
26068 (gdb) break *0x401373
26069 Breakpoint 1 at 0x401373: file stb.adb, line 5.
26073 It is important to note that the stack traceback addresses
26074 do not change when debug information is included. This is particularly useful
26075 because it makes it possible to release software without debug information (to
26076 minimize object size), get a field report that includes a stack traceback
26077 whenever an internal bug occurs, and then be able to retrieve the sequence
26078 of calls with the same program compiled with debug information.
26080 @subsubheading Tracebacks From Exception Occurrences
26083 Non-symbolic tracebacks are obtained by using the @emph{-E} binder argument.
26084 The stack traceback is attached to the exception information string, and can
26085 be retrieved in an exception handler within the Ada program, by means of the
26086 Ada facilities defined in @cite{Ada.Exceptions}. Here is a simple example:
26092 with Ada.Exceptions;
26097 use Ada.Exceptions;
26105 Text_IO.Put_Line (Exception_Information (E));
26119 This program will output:
26126 Exception name: CONSTRAINT_ERROR
26127 Message: stb.adb:12
26128 Call stack traceback locations:
26129 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
26133 @subsubheading Tracebacks From Anywhere in a Program
26136 It is also possible to retrieve a stack traceback from anywhere in a
26137 program. For this you need to
26138 use the @cite{GNAT.Traceback} API. This package includes a procedure called
26139 @cite{Call_Chain} that computes a complete stack traceback, as well as useful
26140 display procedures described below. It is not necessary to use the
26141 @emph{-E gnatbind} option in this case, because the stack traceback mechanism
26142 is invoked explicitly.
26144 In the following example we compute a traceback at a specific location in
26145 the program, and we display it using @cite{GNAT.Debug_Utilities.Image} to
26146 convert addresses to strings:
26152 with GNAT.Traceback;
26153 with GNAT.Debug_Utilities;
26159 use GNAT.Traceback;
26162 TB : Tracebacks_Array (1 .. 10);
26163 -- We are asking for a maximum of 10 stack frames.
26165 -- Len will receive the actual number of stack frames returned.
26167 Call_Chain (TB, Len);
26169 Text_IO.Put ("In STB.P1 : ");
26171 for K in 1 .. Len loop
26172 Text_IO.Put (Debug_Utilities.Image (TB (K)));
26193 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
26194 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
26198 You can then get further information by invoking the @cite{addr2line}
26199 tool as described earlier (note that the hexadecimal addresses
26200 need to be specified in C format, with a leading '0x').
26205 @node Symbolic Traceback,,Non-Symbolic Traceback,Stack Traceback
26206 @anchor{gnat_ugn/gnat_and_program_execution id18}@anchor{215}@anchor{gnat_ugn/gnat_and_program_execution symbolic-traceback}@anchor{216}
26207 @subsubsection Symbolic Traceback
26210 A symbolic traceback is a stack traceback in which procedure names are
26211 associated with each code location.
26213 Note that this feature is not supported on all platforms. See
26214 @code{GNAT.Traceback.Symbolic} spec in @code{g-trasym.ads} for a complete
26215 list of currently supported platforms.
26217 Note that the symbolic traceback requires that the program be compiled
26218 with debug information. If it is not compiled with debug information
26219 only the non-symbolic information will be valid.
26221 @subsubheading Tracebacks From Exception Occurrences
26224 Here is an example:
26230 with GNAT.Traceback.Symbolic;
26236 raise Constraint_Error;
26253 Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
26258 $ gnatmake -g .\stb -bargs -E
26261 0040149F in stb.p1 at stb.adb:8
26262 004014B7 in stb.p2 at stb.adb:13
26263 004014CF in stb.p3 at stb.adb:18
26264 004015DD in ada.stb at stb.adb:22
26265 00401461 in main at b~stb.adb:168
26266 004011C4 in __mingw_CRTStartup at crt1.c:200
26267 004011F1 in mainCRTStartup at crt1.c:222
26268 77E892A4 in ?? at ??:0
26272 In the above example the @code{.\} syntax in the @emph{gnatmake} command
26273 is currently required by @emph{addr2line} for files that are in
26274 the current working directory.
26275 Moreover, the exact sequence of linker options may vary from platform
26277 The above @emph{-largs} section is for Windows platforms. By contrast,
26278 under Unix there is no need for the @emph{-largs} section.
26279 Differences across platforms are due to details of linker implementation.
26281 @subsubheading Tracebacks From Anywhere in a Program
26284 It is possible to get a symbolic stack traceback
26285 from anywhere in a program, just as for non-symbolic tracebacks.
26286 The first step is to obtain a non-symbolic
26287 traceback, and then call @cite{Symbolic_Traceback} to compute the symbolic
26288 information. Here is an example:
26294 with GNAT.Traceback;
26295 with GNAT.Traceback.Symbolic;
26300 use GNAT.Traceback;
26301 use GNAT.Traceback.Symbolic;
26304 TB : Tracebacks_Array (1 .. 10);
26305 -- We are asking for a maximum of 10 stack frames.
26307 -- Len will receive the actual number of stack frames returned.
26309 Call_Chain (TB, Len);
26310 Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
26324 @geindex Code Coverage
26328 @node Code Coverage and Profiling,Improving Performance,Running and Debugging Ada Programs,GNAT and Program Execution
26329 @anchor{gnat_ugn/gnat_and_program_execution id19}@anchor{1f1}@anchor{gnat_ugn/gnat_and_program_execution code-coverage-and-profiling}@anchor{27}
26330 @section Code Coverage and Profiling
26333 This section describes how to use the @cite{gcov} coverage testing tool and
26334 the @cite{gprof} profiler tool on Ada programs.
26339 * Code Coverage of Ada Programs with gcov::
26340 * Profiling an Ada Program with gprof::
26344 @node Code Coverage of Ada Programs with gcov,Profiling an Ada Program with gprof,,Code Coverage and Profiling
26345 @anchor{gnat_ugn/gnat_and_program_execution id20}@anchor{217}@anchor{gnat_ugn/gnat_and_program_execution code-coverage-of-ada-programs-with-gcov}@anchor{218}
26346 @subsection Code Coverage of Ada Programs with gcov
26349 @cite{gcov} is a test coverage program: it analyzes the execution of a given
26350 program on selected tests, to help you determine the portions of the program
26351 that are still untested.
26353 @cite{gcov} is part of the GCC suite, and is described in detail in the GCC
26354 User's Guide. You can refer to this documentation for a more complete
26357 This chapter provides a quick startup guide, and
26358 details some GNAT-specific features.
26361 * Quick startup guide::
26366 @node Quick startup guide,GNAT specifics,,Code Coverage of Ada Programs with gcov
26367 @anchor{gnat_ugn/gnat_and_program_execution id21}@anchor{219}@anchor{gnat_ugn/gnat_and_program_execution quick-startup-guide}@anchor{21a}
26368 @subsubsection Quick startup guide
26371 In order to perform coverage analysis of a program using @cite{gcov}, several
26378 Instrument the code during the compilation process,
26381 Execute the instrumented program, and
26384 Invoke the @cite{gcov} tool to generate the coverage results.
26387 @geindex -fprofile-arcs (gcc)
26389 @geindex -ftest-coverage (gcc
26391 @geindex -fprofile-arcs (gnatbind)
26393 The code instrumentation needed by gcov is created at the object level.
26394 The source code is not modified in any way, because the instrumentation code is
26395 inserted by gcc during the compilation process. To compile your code with code
26396 coverage activated, you need to recompile your whole project using the
26398 @cite{-fprofile-arcs} and @cite{-ftest-coverage}, and link it using
26399 @cite{-fprofile-arcs}.
26404 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \\
26405 -largs -fprofile-arcs
26409 This compilation process will create @code{.gcno} files together with
26410 the usual object files.
26412 Once the program is compiled with coverage instrumentation, you can
26413 run it as many times as needed -- on portions of a test suite for
26414 example. The first execution will produce @code{.gcda} files at the
26415 same location as the @code{.gcno} files. Subsequent executions
26416 will update those files, so that a cumulative result of the covered
26417 portions of the program is generated.
26419 Finally, you need to call the @cite{gcov} tool. The different options of
26420 @cite{gcov} are described in the GCC User's Guide, section 'Invoking gcov'.
26422 This will create annotated source files with a @code{.gcov} extension:
26423 @code{my_main.adb} file will be analyzed in @code{my_main.adb.gcov}.
26425 @node GNAT specifics,,Quick startup guide,Code Coverage of Ada Programs with gcov
26426 @anchor{gnat_ugn/gnat_and_program_execution gnat-specifics}@anchor{21b}@anchor{gnat_ugn/gnat_and_program_execution id22}@anchor{21c}
26427 @subsubsection GNAT specifics
26430 Because of Ada semantics, portions of the source code may be shared among
26431 several object files. This is the case for example when generics are
26432 involved, when inlining is active or when declarations generate initialisation
26433 calls. In order to take
26434 into account this shared code, you need to call @cite{gcov} on all
26435 source files of the tested program at once.
26437 The list of source files might exceed the system's maximum command line
26438 length. In order to bypass this limitation, a new mechanism has been
26439 implemented in @cite{gcov}: you can now list all your project's files into a
26440 text file, and provide this file to gcov as a parameter, preceded by a @code{@@}
26441 (e.g. @code{gcov @@mysrclist.txt}).
26443 Note that on AIX compiling a static library with @cite{-fprofile-arcs} is
26444 not supported as there can be unresolved symbols during the final link.
26450 @node Profiling an Ada Program with gprof,,Code Coverage of Ada Programs with gcov,Code Coverage and Profiling
26451 @anchor{gnat_ugn/gnat_and_program_execution profiling-an-ada-program-with-gprof}@anchor{21d}@anchor{gnat_ugn/gnat_and_program_execution id23}@anchor{21e}
26452 @subsection Profiling an Ada Program with gprof
26455 This section is not meant to be an exhaustive documentation of @cite{gprof}.
26456 Full documentation for it can be found in the @cite{GNU Profiler User's Guide}
26457 documentation that is part of this GNAT distribution.
26459 Profiling a program helps determine the parts of a program that are executed
26460 most often, and are therefore the most time-consuming.
26462 @cite{gprof} is the standard GNU profiling tool; it has been enhanced to
26463 better handle Ada programs and multitasking.
26464 It is currently supported on the following platforms
26473 solaris sparc/sparc64/x86
26479 In order to profile a program using @cite{gprof}, several steps are needed:
26485 Instrument the code, which requires a full recompilation of the project with the
26489 Execute the program under the analysis conditions, i.e. with the desired
26493 Analyze the results using the @cite{gprof} tool.
26496 The following sections detail the different steps, and indicate how
26497 to interpret the results.
26500 * Compilation for profiling::
26501 * Program execution::
26503 * Interpretation of profiling results::
26507 @node Compilation for profiling,Program execution,,Profiling an Ada Program with gprof
26508 @anchor{gnat_ugn/gnat_and_program_execution id24}@anchor{21f}@anchor{gnat_ugn/gnat_and_program_execution compilation-for-profiling}@anchor{220}
26509 @subsubsection Compilation for profiling
26513 @geindex for profiling
26515 @geindex -pg (gnatlink)
26516 @geindex for profiling
26518 In order to profile a program the first step is to tell the compiler
26519 to generate the necessary profiling information. The compiler switch to be used
26520 is @code{-pg}, which must be added to other compilation switches. This
26521 switch needs to be specified both during compilation and link stages, and can
26522 be specified once when using gnatmake:
26527 $ gnatmake -f -pg -P my_project
26531 Note that only the objects that were compiled with the @code{-pg} switch will
26532 be profiled; if you need to profile your whole project, use the @code{-f}
26533 gnatmake switch to force full recompilation.
26535 @node Program execution,Running gprof,Compilation for profiling,Profiling an Ada Program with gprof
26536 @anchor{gnat_ugn/gnat_and_program_execution program-execution}@anchor{221}@anchor{gnat_ugn/gnat_and_program_execution id25}@anchor{222}
26537 @subsubsection Program execution
26540 Once the program has been compiled for profiling, you can run it as usual.
26542 The only constraint imposed by profiling is that the program must terminate
26543 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
26546 Once the program completes execution, a data file called @code{gmon.out} is
26547 generated in the directory where the program was launched from. If this file
26548 already exists, it will be overwritten.
26550 @node Running gprof,Interpretation of profiling results,Program execution,Profiling an Ada Program with gprof
26551 @anchor{gnat_ugn/gnat_and_program_execution running-gprof}@anchor{223}@anchor{gnat_ugn/gnat_and_program_execution id26}@anchor{224}
26552 @subsubsection Running gprof
26555 The @cite{gprof} tool is called as follow:
26560 $ gprof my_prog gmon.out
26573 The complete form of the gprof command line is the following:
26578 $ gprof [switches] [executable [data-file]]
26582 @cite{gprof} supports numerous switches. The order of these
26583 switch does not matter. The full list of options can be found in
26584 the GNU Profiler User's Guide documentation that comes with this documentation.
26586 The following is the subset of those switches that is most relevant:
26588 @geindex --demangle (gprof)
26593 @item @code{--demangle[=@emph{style}]}, @code{--no-demangle}
26595 These options control whether symbol names should be demangled when
26596 printing output. The default is to demangle C++ symbols. The
26597 @code{--no-demangle} option may be used to turn off demangling. Different
26598 compilers have different mangling styles. The optional demangling style
26599 argument can be used to choose an appropriate demangling style for your
26600 compiler, in particular Ada symbols generated by GNAT can be demangled using
26601 @code{--demangle=gnat}.
26604 @geindex -e (gprof)
26609 @item @code{-e @emph{function_name}}
26611 The @code{-e @emph{function}} option tells @cite{gprof} not to print
26612 information about the function @cite{function_name} (and its
26613 children...) in the call graph. The function will still be listed
26614 as a child of any functions that call it, but its index number will be
26615 shown as @code{[not printed]}. More than one @code{-e} option may be
26616 given; only one @cite{function_name} may be indicated with each @code{-e}
26620 @geindex -E (gprof)
26625 @item @code{-E @emph{function_name}}
26627 The @code{-E @emph{function}} option works like the @code{-e} option, but
26628 execution time spent in the function (and children who were not called from
26629 anywhere else), will not be used to compute the percentages-of-time for
26630 the call graph. More than one @code{-E} option may be given; only one
26631 @cite{function_name} may be indicated with each @code{-E} option.
26634 @geindex -f (gprof)
26639 @item @code{-f @emph{function_name}}
26641 The @code{-f @emph{function}} option causes @cite{gprof} to limit the
26642 call graph to the function @cite{function_name} and its children (and
26643 their children...). More than one @code{-f} option may be given;
26644 only one @cite{function_name} may be indicated with each @code{-f}
26648 @geindex -F (gprof)
26653 @item @code{-F @emph{function_name}}
26655 The @code{-F @emph{function}} option works like the @code{-f} option, but
26656 only time spent in the function and its children (and their
26657 children...) will be used to determine total-time and
26658 percentages-of-time for the call graph. More than one @code{-F} option
26659 may be given; only one @cite{function_name} may be indicated with each
26660 @code{-F} option. The @code{-F} option overrides the @code{-E} option.
26663 @node Interpretation of profiling results,,Running gprof,Profiling an Ada Program with gprof
26664 @anchor{gnat_ugn/gnat_and_program_execution id27}@anchor{225}@anchor{gnat_ugn/gnat_and_program_execution interpretation-of-profiling-results}@anchor{226}
26665 @subsubsection Interpretation of profiling results
26668 The results of the profiling analysis are represented by two arrays: the
26669 'flat profile' and the 'call graph'. Full documentation of those outputs
26670 can be found in the GNU Profiler User's Guide.
26672 The flat profile shows the time spent in each function of the program, and how
26673 many time it has been called. This allows you to locate easily the most
26674 time-consuming functions.
26676 The call graph shows, for each subprogram, the subprograms that call it,
26677 and the subprograms that it calls. It also provides an estimate of the time
26678 spent in each of those callers/called subprograms.
26680 @node Improving Performance,Overflow Check Handling in GNAT,Code Coverage and Profiling,GNAT and Program Execution
26681 @anchor{gnat_ugn/gnat_and_program_execution improving-performance}@anchor{28}@anchor{gnat_ugn/gnat_and_program_execution id28}@anchor{1f2}
26682 @section Improving Performance
26685 @geindex Improving performance
26687 This section presents several topics related to program performance.
26688 It first describes some of the tradeoffs that need to be considered
26689 and some of the techniques for making your program run faster.
26692 It then documents the unused subprogram/data elimination feature,
26693 which can reduce the size of program executables.
26696 * Performance Considerations::
26697 * Text_IO Suggestions::
26698 * Reducing Size of Executables with Unused Subprogram/Data Elimination::
26702 @node Performance Considerations,Text_IO Suggestions,,Improving Performance
26703 @anchor{gnat_ugn/gnat_and_program_execution id29}@anchor{227}@anchor{gnat_ugn/gnat_and_program_execution performance-considerations}@anchor{228}
26704 @subsection Performance Considerations
26707 The GNAT system provides a number of options that allow a trade-off
26714 performance of the generated code
26717 speed of compilation
26720 minimization of dependences and recompilation
26723 the degree of run-time checking.
26726 The defaults (if no options are selected) aim at improving the speed
26727 of compilation and minimizing dependences, at the expense of performance
26728 of the generated code:
26737 no inlining of subprogram calls
26740 all run-time checks enabled except overflow and elaboration checks
26743 These options are suitable for most program development purposes. This
26744 section describes how you can modify these choices, and also provides
26745 some guidelines on debugging optimized code.
26748 * Controlling Run-Time Checks::
26749 * Use of Restrictions::
26750 * Optimization Levels::
26751 * Debugging Optimized Code::
26752 * Inlining of Subprograms::
26753 * Floating_Point_Operations::
26754 * Vectorization of loops::
26755 * Other Optimization Switches::
26756 * Optimization and Strict Aliasing::
26757 * Aliased Variables and Optimization::
26758 * Atomic Variables and Optimization::
26759 * Passive Task Optimization::
26763 @node Controlling Run-Time Checks,Use of Restrictions,,Performance Considerations
26764 @anchor{gnat_ugn/gnat_and_program_execution controlling-run-time-checks}@anchor{229}@anchor{gnat_ugn/gnat_and_program_execution id30}@anchor{22a}
26765 @subsubsection Controlling Run-Time Checks
26768 By default, GNAT generates all run-time checks, except integer overflow
26769 checks, stack overflow checks, and checks for access before elaboration on
26770 subprogram calls. The latter are not required in default mode, because all
26771 necessary checking is done at compile time.
26773 @geindex -gnatp (gcc)
26775 @geindex -gnato (gcc)
26777 Two gnat switches, @emph{-gnatp} and @emph{-gnato} allow this default to
26778 be modified. See @ref{fe,,Run-Time Checks}.
26780 Our experience is that the default is suitable for most development
26783 We treat integer overflow specially because these
26784 are quite expensive and in our experience are not as important as other
26785 run-time checks in the development process. Note that division by zero
26786 is not considered an overflow check, and divide by zero checks are
26787 generated where required by default.
26789 Elaboration checks are off by default, and also not needed by default, since
26790 GNAT uses a static elaboration analysis approach that avoids the need for
26791 run-time checking. This manual contains a full chapter discussing the issue
26792 of elaboration checks, and if the default is not satisfactory for your use,
26793 you should read this chapter.
26795 For validity checks, the minimal checks required by the Ada Reference
26796 Manual (for case statements and assignments to array elements) are on
26797 by default. These can be suppressed by use of the @emph{-gnatVn} switch.
26798 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
26799 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
26800 it may be reasonable to routinely use @emph{-gnatVn}. Validity checks
26801 are also suppressed entirely if @emph{-gnatp} is used.
26803 @geindex Overflow checks
26810 @geindex Unsuppress
26812 @geindex pragma Suppress
26814 @geindex pragma Unsuppress
26816 Note that the setting of the switches controls the default setting of
26817 the checks. They may be modified using either @cite{pragma Suppress} (to
26818 remove checks) or @cite{pragma Unsuppress} (to add back suppressed
26819 checks) in the program source.
26821 @node Use of Restrictions,Optimization Levels,Controlling Run-Time Checks,Performance Considerations
26822 @anchor{gnat_ugn/gnat_and_program_execution use-of-restrictions}@anchor{22b}@anchor{gnat_ugn/gnat_and_program_execution id31}@anchor{22c}
26823 @subsubsection Use of Restrictions
26826 The use of pragma Restrictions allows you to control which features are
26827 permitted in your program. Apart from the obvious point that if you avoid
26828 relatively expensive features like finalization (enforceable by the use
26829 of pragma Restrictions (No_Finalization), the use of this pragma does not
26830 affect the generated code in most cases.
26832 One notable exception to this rule is that the possibility of task abort
26833 results in some distributed overhead, particularly if finalization or
26834 exception handlers are used. The reason is that certain sections of code
26835 have to be marked as non-abortable.
26837 If you use neither the @cite{abort} statement, nor asynchronous transfer
26838 of control (@cite{select ... then abort}), then this distributed overhead
26839 is removed, which may have a general positive effect in improving
26840 overall performance. Especially code involving frequent use of tasking
26841 constructs and controlled types will show much improved performance.
26842 The relevant restrictions pragmas are
26847 pragma Restrictions (No_Abort_Statements);
26848 pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
26852 It is recommended that these restriction pragmas be used if possible. Note
26853 that this also means that you can write code without worrying about the
26854 possibility of an immediate abort at any point.
26856 @node Optimization Levels,Debugging Optimized Code,Use of Restrictions,Performance Considerations
26857 @anchor{gnat_ugn/gnat_and_program_execution id32}@anchor{22d}@anchor{gnat_ugn/gnat_and_program_execution optimization-levels}@anchor{101}
26858 @subsubsection Optimization Levels
26863 Without any optimization option,
26864 the compiler's goal is to reduce the cost of
26865 compilation and to make debugging produce the expected results.
26866 Statements are independent: if you stop the program with a breakpoint between
26867 statements, you can then assign a new value to any variable or change
26868 the program counter to any other statement in the subprogram and get exactly
26869 the results you would expect from the source code.
26871 Turning on optimization makes the compiler attempt to improve the
26872 performance and/or code size at the expense of compilation time and
26873 possibly the ability to debug the program.
26875 If you use multiple
26876 -O options, with or without level numbers,
26877 the last such option is the one that is effective.
26879 The default is optimization off. This results in the fastest compile
26880 times, but GNAT makes absolutely no attempt to optimize, and the
26881 generated programs are considerably larger and slower than when
26882 optimization is enabled. You can use the
26883 @emph{-O} switch (the permitted forms are @emph{-O0}, @emph{-O1}
26884 @emph{-O2}, @emph{-O3}, and @emph{-Os})
26885 to @emph{gcc} to control the optimization level:
26896 No optimization (the default);
26897 generates unoptimized code but has
26898 the fastest compilation time.
26900 Note that many other compilers do fairly extensive optimization
26901 even if 'no optimization' is specified. With gcc, it is
26902 very unusual to use -O0 for production if
26903 execution time is of any concern, since -O0
26904 really does mean no optimization at all. This difference between
26905 gcc and other compilers should be kept in mind when doing
26906 performance comparisons.
26915 Moderate optimization;
26916 optimizes reasonably well but does not
26917 degrade compilation time significantly.
26927 generates highly optimized code and has
26928 the slowest compilation time.
26937 Full optimization as in @emph{-O2};
26938 also uses more aggressive automatic inlining of subprograms within a unit
26939 (@ref{114,,Inlining of Subprograms}) and attempts to vectorize loops.
26948 Optimize space usage (code and data) of resulting program.
26952 Higher optimization levels perform more global transformations on the
26953 program and apply more expensive analysis algorithms in order to generate
26954 faster and more compact code. The price in compilation time, and the
26955 resulting improvement in execution time,
26956 both depend on the particular application and the hardware environment.
26957 You should experiment to find the best level for your application.
26959 Since the precise set of optimizations done at each level will vary from
26960 release to release (and sometime from target to target), it is best to think
26961 of the optimization settings in general terms.
26962 See the @emph{Options That Control Optimization} section in
26963 @cite{Using the GNU Compiler Collection (GCC)}
26965 the @emph{-O} settings and a number of @emph{-f} options that
26966 individually enable or disable specific optimizations.
26968 Unlike some other compilation systems, @emph{gcc} has
26969 been tested extensively at all optimization levels. There are some bugs
26970 which appear only with optimization turned on, but there have also been
26971 bugs which show up only in @emph{unoptimized} code. Selecting a lower
26972 level of optimization does not improve the reliability of the code
26973 generator, which in practice is highly reliable at all optimization
26976 Note regarding the use of @emph{-O3}: The use of this optimization level
26977 is generally discouraged with GNAT, since it often results in larger
26978 executables which may run more slowly. See further discussion of this point
26979 in @ref{114,,Inlining of Subprograms}.
26981 @node Debugging Optimized Code,Inlining of Subprograms,Optimization Levels,Performance Considerations
26982 @anchor{gnat_ugn/gnat_and_program_execution id33}@anchor{22e}@anchor{gnat_ugn/gnat_and_program_execution debugging-optimized-code}@anchor{22f}
26983 @subsubsection Debugging Optimized Code
26986 @geindex Debugging optimized code
26988 @geindex Optimization and debugging
26990 Although it is possible to do a reasonable amount of debugging at
26991 nonzero optimization levels,
26992 the higher the level the more likely that
26993 source-level constructs will have been eliminated by optimization.
26994 For example, if a loop is strength-reduced, the loop
26995 control variable may be completely eliminated and thus cannot be
26996 displayed in the debugger.
26997 This can only happen at @emph{-O2} or @emph{-O3}.
26998 Explicit temporary variables that you code might be eliminated at
26999 level @emph{-O1} or higher.
27003 The use of the @emph{-g} switch,
27004 which is needed for source-level debugging,
27005 affects the size of the program executable on disk,
27006 and indeed the debugging information can be quite large.
27007 However, it has no effect on the generated code (and thus does not
27008 degrade performance)
27010 Since the compiler generates debugging tables for a compilation unit before
27011 it performs optimizations, the optimizing transformations may invalidate some
27012 of the debugging data. You therefore need to anticipate certain
27013 anomalous situations that may arise while debugging optimized code.
27014 These are the most common cases:
27020 @emph{The 'hopping Program Counter':} Repeated @cite{step} or @cite{next}
27022 the PC bouncing back and forth in the code. This may result from any of
27023 the following optimizations:
27029 @emph{Common subexpression elimination:} using a single instance of code for a
27030 quantity that the source computes several times. As a result you
27031 may not be able to stop on what looks like a statement.
27034 @emph{Invariant code motion:} moving an expression that does not change within a
27035 loop, to the beginning of the loop.
27038 @emph{Instruction scheduling:} moving instructions so as to
27039 overlap loads and stores (typically) with other code, or in
27040 general to move computations of values closer to their uses. Often
27041 this causes you to pass an assignment statement without the assignment
27042 happening and then later bounce back to the statement when the
27043 value is actually needed. Placing a breakpoint on a line of code
27044 and then stepping over it may, therefore, not always cause all the
27045 expected side-effects.
27049 @emph{The 'big leap':} More commonly known as @emph{cross-jumping}, in which
27050 two identical pieces of code are merged and the program counter suddenly
27051 jumps to a statement that is not supposed to be executed, simply because
27052 it (and the code following) translates to the same thing as the code
27053 that @emph{was} supposed to be executed. This effect is typically seen in
27054 sequences that end in a jump, such as a @cite{goto}, a @cite{return}, or
27055 a @cite{break} in a C @cite{switch} statement.
27058 @emph{The 'roving variable':} The symptom is an unexpected value in a variable.
27059 There are various reasons for this effect:
27065 In a subprogram prologue, a parameter may not yet have been moved to its
27069 A variable may be dead, and its register re-used. This is
27070 probably the most common cause.
27073 As mentioned above, the assignment of a value to a variable may
27077 A variable may be eliminated entirely by value propagation or
27078 other means. In this case, GCC may incorrectly generate debugging
27079 information for the variable
27082 In general, when an unexpected value appears for a local variable or parameter
27083 you should first ascertain if that value was actually computed by
27084 your program, as opposed to being incorrectly reported by the debugger.
27086 array elements in an object designated by an access value
27087 are generally less of a problem, once you have ascertained that the access
27089 Typically, this means checking variables in the preceding code and in the
27090 calling subprogram to verify that the value observed is explainable from other
27091 values (one must apply the procedure recursively to those
27092 other values); or re-running the code and stopping a little earlier
27093 (perhaps before the call) and stepping to better see how the variable obtained
27094 the value in question; or continuing to step @emph{from} the point of the
27095 strange value to see if code motion had simply moved the variable's
27099 In light of such anomalies, a recommended technique is to use @emph{-O0}
27100 early in the software development cycle, when extensive debugging capabilities
27101 are most needed, and then move to @emph{-O1} and later @emph{-O2} as
27102 the debugger becomes less critical.
27103 Whether to use the @emph{-g} switch in the release version is
27104 a release management issue.
27105 Note that if you use @emph{-g} you can then use the @emph{strip} program
27106 on the resulting executable,
27107 which removes both debugging information and global symbols.
27109 @node Inlining of Subprograms,Floating_Point_Operations,Debugging Optimized Code,Performance Considerations
27110 @anchor{gnat_ugn/gnat_and_program_execution id34}@anchor{230}@anchor{gnat_ugn/gnat_and_program_execution inlining-of-subprograms}@anchor{114}
27111 @subsubsection Inlining of Subprograms
27114 A call to a subprogram in the current unit is inlined if all the
27115 following conditions are met:
27121 The optimization level is at least @emph{-O1}.
27124 The called subprogram is suitable for inlining: It must be small enough
27125 and not contain something that @emph{gcc} cannot support in inlined
27128 @geindex pragma Inline
27133 Any one of the following applies: @cite{pragma Inline} is applied to the
27134 subprogram and the @emph{-gnatn} switch is specified; the
27135 subprogram is local to the unit and called once from within it; the
27136 subprogram is small and optimization level @emph{-O2} is specified;
27137 optimization level @emph{-O3} is specified.
27140 Calls to subprograms in @emph{with}ed units are normally not inlined.
27141 To achieve actual inlining (that is, replacement of the call by the code
27142 in the body of the subprogram), the following conditions must all be true:
27148 The optimization level is at least @emph{-O1}.
27151 The called subprogram is suitable for inlining: It must be small enough
27152 and not contain something that @emph{gcc} cannot support in inlined
27156 The call appears in a body (not in a package spec).
27159 There is a @cite{pragma Inline} for the subprogram.
27162 The @emph{-gnatn} switch is used on the command line.
27165 Even if all these conditions are met, it may not be possible for
27166 the compiler to inline the call, due to the length of the body,
27167 or features in the body that make it impossible for the compiler
27168 to do the inlining.
27170 Note that specifying the @emph{-gnatn} switch causes additional
27171 compilation dependencies. Consider the following:
27193 With the default behavior (no @emph{-gnatn} switch specified), the
27194 compilation of the @cite{Main} procedure depends only on its own source,
27195 @code{main.adb}, and the spec of the package in file @code{r.ads}. This
27196 means that editing the body of @cite{R} does not require recompiling
27199 On the other hand, the call @cite{R.Q} is not inlined under these
27200 circumstances. If the @emph{-gnatn} switch is present when @cite{Main}
27201 is compiled, the call will be inlined if the body of @cite{Q} is small
27202 enough, but now @cite{Main} depends on the body of @cite{R} in
27203 @code{r.adb} as well as on the spec. This means that if this body is edited,
27204 the main program must be recompiled. Note that this extra dependency
27205 occurs whether or not the call is in fact inlined by @emph{gcc}.
27207 The use of front end inlining with @emph{-gnatN} generates similar
27208 additional dependencies.
27210 @geindex -fno-inline (gcc)
27212 Note: The @emph{-fno-inline} switch overrides all other conditions and ensures that
27213 no inlining occurs, unless requested with pragma Inline_Always for gcc
27214 back-ends. The extra dependences resulting from @emph{-gnatn} will still be active,
27215 even if this switch is used to suppress the resulting inlining actions.
27217 @geindex -fno-inline-functions (gcc)
27219 Note: The @emph{-fno-inline-functions} switch can be used to prevent
27220 automatic inlining of subprograms if @emph{-O3} is used.
27222 @geindex -fno-inline-small-functions (gcc)
27224 Note: The @emph{-fno-inline-small-functions} switch can be used to prevent
27225 automatic inlining of small subprograms if @emph{-O2} is used.
27227 @geindex -fno-inline-functions-called-once (gcc)
27229 Note: The @emph{-fno-inline-functions-called-once} switch
27230 can be used to prevent inlining of subprograms local to the unit
27231 and called once from within it if @emph{-O1} is used.
27233 Note regarding the use of @emph{-O3}: @emph{-gnatn} is made up of two
27234 sub-switches @emph{-gnatn1} and @emph{-gnatn2} that can be directly
27235 specified in lieu of it, @emph{-gnatn} being translated into one of them
27236 based on the optimization level. With @emph{-O2} or below, @emph{-gnatn}
27237 is equivalent to @emph{-gnatn1} which activates pragma @cite{Inline} with
27238 moderate inlining across modules. With @emph{-O3}, @emph{-gnatn} is
27239 equivalent to @emph{-gnatn2} which activates pragma @cite{Inline} with
27240 full inlining across modules. If you have used pragma @cite{Inline} in
27241 appropriate cases, then it is usually much better to use @emph{-O2}
27242 and @emph{-gnatn} and avoid the use of @emph{-O3} which has the additional
27243 effect of inlining subprograms you did not think should be inlined. We have
27244 found that the use of @emph{-O3} may slow down the compilation and increase
27245 the code size by performing excessive inlining, leading to increased
27246 instruction cache pressure from the increased code size and thus minor
27247 performance improvements. So the bottom line here is that you should not
27248 automatically assume that @emph{-O3} is better than @emph{-O2}, and
27249 indeed you should use @emph{-O3} only if tests show that it actually
27250 improves performance for your program.
27252 @node Floating_Point_Operations,Vectorization of loops,Inlining of Subprograms,Performance Considerations
27253 @anchor{gnat_ugn/gnat_and_program_execution floating-point-operations}@anchor{231}@anchor{gnat_ugn/gnat_and_program_execution id35}@anchor{232}
27254 @subsubsection Floating_Point_Operations
27257 @geindex Floating-Point Operations
27259 On almost all targets, GNAT maps Float and Long_Float to the 32-bit and
27260 64-bit standard IEEE floating-point representations, and operations will
27261 use standard IEEE arithmetic as provided by the processor. On most, but
27262 not all, architectures, the attribute Machine_Overflows is False for these
27263 types, meaning that the semantics of overflow is implementation-defined.
27264 In the case of GNAT, these semantics correspond to the normal IEEE
27265 treatment of infinities and NaN (not a number) values. For example,
27266 1.0 / 0.0 yields plus infinitiy and 0.0 / 0.0 yields a NaN. By
27267 avoiding explicit overflow checks, the performance is greatly improved
27268 on many targets. However, if required, floating-point overflow can be
27269 enabled by the use of the pragma Check_Float_Overflow.
27271 Another consideration that applies specifically to x86 32-bit
27272 architectures is which form of floating-point arithmetic is used.
27273 By default the operations use the old style x86 floating-point,
27274 which implements an 80-bit extended precision form (on these
27275 architectures the type Long_Long_Float corresponds to that form).
27276 In addition, generation of efficient code in this mode means that
27277 the extended precision form will be used for intermediate results.
27278 This may be helpful in improving the final precision of a complex
27279 expression. However it means that the results obtained on the x86
27280 will be different from those on other architectures, and for some
27281 algorithms, the extra intermediate precision can be detrimental.
27283 In addition to this old-style floating-point, all modern x86 chips
27284 implement an alternative floating-point operation model referred
27285 to as SSE2. In this model there is no extended form, and furthermore
27286 execution performance is significantly enhanced. To force GNAT to use
27287 this more modern form, use both of the switches:
27291 -msse2 -mfpmath=sse
27294 A unit compiled with these switches will automatically use the more
27295 efficient SSE2 instruction set for Float and Long_Float operations.
27296 Note that the ABI has the same form for both floating-point models,
27297 so it is permissible to mix units compiled with and without these
27300 @node Vectorization of loops,Other Optimization Switches,Floating_Point_Operations,Performance Considerations
27301 @anchor{gnat_ugn/gnat_and_program_execution id36}@anchor{233}@anchor{gnat_ugn/gnat_and_program_execution vectorization-of-loops}@anchor{234}
27302 @subsubsection Vectorization of loops
27305 @geindex Optimization Switches
27307 You can take advantage of the auto-vectorizer present in the @emph{gcc}
27308 back end to vectorize loops with GNAT. The corresponding command line switch
27309 is @emph{-ftree-vectorize} but, as it is enabled by default at @emph{-O3}
27310 and other aggressive optimizations helpful for vectorization also are enabled
27311 by default at this level, using @emph{-O3} directly is recommended.
27313 You also need to make sure that the target architecture features a supported
27314 SIMD instruction set. For example, for the x86 architecture, you should at
27315 least specify @emph{-msse2} to get significant vectorization (but you don't
27316 need to specify it for x86-64 as it is part of the base 64-bit architecture).
27317 Similarly, for the PowerPC architecture, you should specify @emph{-maltivec}.
27319 The preferred loop form for vectorization is the @cite{for} iteration scheme.
27320 Loops with a @cite{while} iteration scheme can also be vectorized if they are
27321 very simple, but the vectorizer will quickly give up otherwise. With either
27322 iteration scheme, the flow of control must be straight, in particular no
27323 @cite{exit} statement may appear in the loop body. The loop may however
27324 contain a single nested loop, if it can be vectorized when considered alone:
27329 A : array (1..4, 1..4) of Long_Float;
27330 S : array (1..4) of Long_Float;
27334 for I in A'Range(1) loop
27335 for J in A'Range(2) loop
27336 S (I) := S (I) + A (I, J);
27343 The vectorizable operations depend on the targeted SIMD instruction set, but
27344 the adding and some of the multiplying operators are generally supported, as
27345 well as the logical operators for modular types. Note that, in the former
27346 case, enabling overflow checks, for example with @emph{-gnato}, totally
27347 disables vectorization. The other checks are not supposed to have the same
27348 definitive effect, although compiling with @emph{-gnatp} might well reveal
27349 cases where some checks do thwart vectorization.
27351 Type conversions may also prevent vectorization if they involve semantics that
27352 are not directly supported by the code generator or the SIMD instruction set.
27353 A typical example is direct conversion from floating-point to integer types.
27354 The solution in this case is to use the following idiom:
27359 Integer (S'Truncation (F))
27363 if @cite{S} is the subtype of floating-point object @cite{F}.
27365 In most cases, the vectorizable loops are loops that iterate over arrays.
27366 All kinds of array types are supported, i.e. constrained array types with
27372 type Array_Type is array (1 .. 4) of Long_Float;
27376 constrained array types with dynamic bounds:
27381 type Array_Type is array (1 .. Q.N) of Long_Float;
27383 type Array_Type is array (Q.K .. 4) of Long_Float;
27385 type Array_Type is array (Q.K .. Q.N) of Long_Float;
27389 or unconstrained array types:
27394 type Array_Type is array (Positive range <>) of Long_Float;
27398 The quality of the generated code decreases when the dynamic aspect of the
27399 array type increases, the worst code being generated for unconstrained array
27400 types. This is so because, the less information the compiler has about the
27401 bounds of the array, the more fallback code it needs to generate in order to
27402 fix things up at run time.
27404 It is possible to specify that a given loop should be subject to vectorization
27405 preferably to other optimizations by means of pragma @cite{Loop_Optimize}:
27410 pragma Loop_Optimize (Vector);
27414 placed immediately within the loop will convey the appropriate hint to the
27415 compiler for this loop.
27417 It is also possible to help the compiler generate better vectorized code
27418 for a given loop by asserting that there are no loop-carried dependencies
27419 in the loop. Consider for example the procedure:
27424 type Arr is array (1 .. 4) of Long_Float;
27426 procedure Add (X, Y : not null access Arr; R : not null access Arr) is
27428 for I in Arr'Range loop
27429 R(I) := X(I) + Y(I);
27435 By default, the compiler cannot unconditionally vectorize the loop because
27436 assigning to a component of the array designated by R in one iteration could
27437 change the value read from the components of the array designated by X or Y
27438 in a later iteration. As a result, the compiler will generate two versions
27439 of the loop in the object code, one vectorized and the other not vectorized,
27440 as well as a test to select the appropriate version at run time. This can
27441 be overcome by another hint:
27446 pragma Loop_Optimize (Ivdep);
27450 placed immediately within the loop will tell the compiler that it can safely
27451 omit the non-vectorized version of the loop as well as the run-time test.
27453 @node Other Optimization Switches,Optimization and Strict Aliasing,Vectorization of loops,Performance Considerations
27454 @anchor{gnat_ugn/gnat_and_program_execution id37}@anchor{235}@anchor{gnat_ugn/gnat_and_program_execution other-optimization-switches}@anchor{236}
27455 @subsubsection Other Optimization Switches
27458 @geindex Optimization Switches
27460 Since @cite{GNAT} uses the @emph{gcc} back end, all the specialized
27461 @emph{gcc} optimization switches are potentially usable. These switches
27462 have not been extensively tested with GNAT but can generally be expected
27463 to work. Examples of switches in this category are @emph{-funroll-loops}
27464 and the various target-specific @emph{-m} options (in particular, it has
27465 been observed that @emph{-march=xxx} can significantly improve performance
27466 on appropriate machines). For full details of these switches, see
27467 the @cite{Submodel Options} section in the @cite{Hardware Models and Configurations}
27468 chapter of @cite{Using the GNU Compiler Collection (GCC)}.
27470 @node Optimization and Strict Aliasing,Aliased Variables and Optimization,Other Optimization Switches,Performance Considerations
27471 @anchor{gnat_ugn/gnat_and_program_execution optimization-and-strict-aliasing}@anchor{f8}@anchor{gnat_ugn/gnat_and_program_execution id38}@anchor{237}
27472 @subsubsection Optimization and Strict Aliasing
27477 @geindex Strict Aliasing
27479 @geindex No_Strict_Aliasing
27481 The strong typing capabilities of Ada allow an optimizer to generate
27482 efficient code in situations where other languages would be forced to
27483 make worst case assumptions preventing such optimizations. Consider
27484 the following example:
27490 type Int1 is new Integer;
27491 type Int2 is new Integer;
27492 type Int1A is access Int1;
27493 type Int2A is access Int2;
27500 for J in Data'Range loop
27501 if Data (J) = Int1V.all then
27502 Int2V.all := Int2V.all + 1;
27510 In this example, since the variable @cite{Int1V} can only access objects
27511 of type @cite{Int1}, and @cite{Int2V} can only access objects of type
27512 @cite{Int2}, there is no possibility that the assignment to
27513 @cite{Int2V.all} affects the value of @cite{Int1V.all}. This means that
27514 the compiler optimizer can "know" that the value @cite{Int1V.all} is constant
27515 for all iterations of the loop and avoid the extra memory reference
27516 required to dereference it each time through the loop.
27518 This kind of optimization, called strict aliasing analysis, is
27519 triggered by specifying an optimization level of @emph{-O2} or
27520 higher or @emph{-Os} and allows @cite{GNAT} to generate more efficient code
27521 when access values are involved.
27523 However, although this optimization is always correct in terms of
27524 the formal semantics of the Ada Reference Manual, difficulties can
27525 arise if features like @cite{Unchecked_Conversion} are used to break
27526 the typing system. Consider the following complete program example:
27532 type int1 is new integer;
27533 type int2 is new integer;
27534 type a1 is access int1;
27535 type a2 is access int2;
27540 function to_a2 (Input : a1) return a2;
27543 with Unchecked_Conversion;
27545 function to_a2 (Input : a1) return a2 is
27547 new Unchecked_Conversion (a1, a2);
27549 return to_a2u (Input);
27555 with Text_IO; use Text_IO;
27557 v1 : a1 := new int1;
27558 v2 : a2 := to_a2 (v1);
27562 put_line (int1'image (v1.all));
27567 This program prints out 0 in @emph{-O0} or @emph{-O1}
27568 mode, but it prints out 1 in @emph{-O2} mode. That's
27569 because in strict aliasing mode, the compiler can and
27570 does assume that the assignment to @cite{v2.all} could not
27571 affect the value of @cite{v1.all}, since different types
27574 This behavior is not a case of non-conformance with the standard, since
27575 the Ada RM specifies that an unchecked conversion where the resulting
27576 bit pattern is not a correct value of the target type can result in an
27577 abnormal value and attempting to reference an abnormal value makes the
27578 execution of a program erroneous. That's the case here since the result
27579 does not point to an object of type @cite{int2}. This means that the
27580 effect is entirely unpredictable.
27582 However, although that explanation may satisfy a language
27583 lawyer, in practice an applications programmer expects an
27584 unchecked conversion involving pointers to create true
27585 aliases and the behavior of printing 1 seems plain wrong.
27586 In this case, the strict aliasing optimization is unwelcome.
27588 Indeed the compiler recognizes this possibility, and the
27589 unchecked conversion generates a warning:
27594 p2.adb:5:07: warning: possible aliasing problem with type "a2"
27595 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
27596 p2.adb:5:07: warning: or use "pragma No_Strict_Aliasing (a2);"
27600 Unfortunately the problem is recognized when compiling the body of
27601 package @cite{p2}, but the actual "bad" code is generated while
27602 compiling the body of @cite{m} and this latter compilation does not see
27603 the suspicious @cite{Unchecked_Conversion}.
27605 As implied by the warning message, there are approaches you can use to
27606 avoid the unwanted strict aliasing optimization in a case like this.
27608 One possibility is to simply avoid the use of @emph{-O2}, but
27609 that is a bit drastic, since it throws away a number of useful
27610 optimizations that do not involve strict aliasing assumptions.
27612 A less drastic approach is to compile the program using the
27613 option @emph{-fno-strict-aliasing}. Actually it is only the
27614 unit containing the dereferencing of the suspicious pointer
27615 that needs to be compiled. So in this case, if we compile
27616 unit @cite{m} with this switch, then we get the expected
27617 value of zero printed. Analyzing which units might need
27618 the switch can be painful, so a more reasonable approach
27619 is to compile the entire program with options @emph{-O2}
27620 and @emph{-fno-strict-aliasing}. If the performance is
27621 satisfactory with this combination of options, then the
27622 advantage is that the entire issue of possible "wrong"
27623 optimization due to strict aliasing is avoided.
27625 To avoid the use of compiler switches, the configuration
27626 pragma @cite{No_Strict_Aliasing} with no parameters may be
27627 used to specify that for all access types, the strict
27628 aliasing optimization should be suppressed.
27630 However, these approaches are still overkill, in that they causes
27631 all manipulations of all access values to be deoptimized. A more
27632 refined approach is to concentrate attention on the specific
27633 access type identified as problematic.
27635 First, if a careful analysis of uses of the pointer shows
27636 that there are no possible problematic references, then
27637 the warning can be suppressed by bracketing the
27638 instantiation of @cite{Unchecked_Conversion} to turn
27644 pragma Warnings (Off);
27646 new Unchecked_Conversion (a1, a2);
27647 pragma Warnings (On);
27651 Of course that approach is not appropriate for this particular
27652 example, since indeed there is a problematic reference. In this
27653 case we can take one of two other approaches.
27655 The first possibility is to move the instantiation of unchecked
27656 conversion to the unit in which the type is declared. In
27657 this example, we would move the instantiation of
27658 @cite{Unchecked_Conversion} from the body of package
27659 @cite{p2} to the spec of package @cite{p1}. Now the
27660 warning disappears. That's because any use of the
27661 access type knows there is a suspicious unchecked
27662 conversion, and the strict aliasing optimization
27663 is automatically suppressed for the type.
27665 If it is not practical to move the unchecked conversion to the same unit
27666 in which the destination access type is declared (perhaps because the
27667 source type is not visible in that unit), you may use pragma
27668 @cite{No_Strict_Aliasing} for the type. This pragma must occur in the
27669 same declarative sequence as the declaration of the access type:
27674 type a2 is access int2;
27675 pragma No_Strict_Aliasing (a2);
27679 Here again, the compiler now knows that the strict aliasing optimization
27680 should be suppressed for any reference to type @cite{a2} and the
27681 expected behavior is obtained.
27683 Finally, note that although the compiler can generate warnings for
27684 simple cases of unchecked conversions, there are tricker and more
27685 indirect ways of creating type incorrect aliases which the compiler
27686 cannot detect. Examples are the use of address overlays and unchecked
27687 conversions involving composite types containing access types as
27688 components. In such cases, no warnings are generated, but there can
27689 still be aliasing problems. One safe coding practice is to forbid the
27690 use of address clauses for type overlaying, and to allow unchecked
27691 conversion only for primitive types. This is not really a significant
27692 restriction since any possible desired effect can be achieved by
27693 unchecked conversion of access values.
27695 The aliasing analysis done in strict aliasing mode can certainly
27696 have significant benefits. We have seen cases of large scale
27697 application code where the time is increased by up to 5% by turning
27698 this optimization off. If you have code that includes significant
27699 usage of unchecked conversion, you might want to just stick with
27700 @emph{-O1} and avoid the entire issue. If you get adequate
27701 performance at this level of optimization level, that's probably
27702 the safest approach. If tests show that you really need higher
27703 levels of optimization, then you can experiment with @emph{-O2}
27704 and @emph{-O2 -fno-strict-aliasing} to see how much effect this
27705 has on size and speed of the code. If you really need to use
27706 @emph{-O2} with strict aliasing in effect, then you should
27707 review any uses of unchecked conversion of access types,
27708 particularly if you are getting the warnings described above.
27710 @node Aliased Variables and Optimization,Atomic Variables and Optimization,Optimization and Strict Aliasing,Performance Considerations
27711 @anchor{gnat_ugn/gnat_and_program_execution aliased-variables-and-optimization}@anchor{238}@anchor{gnat_ugn/gnat_and_program_execution id39}@anchor{239}
27712 @subsubsection Aliased Variables and Optimization
27717 There are scenarios in which programs may
27718 use low level techniques to modify variables
27719 that otherwise might be considered to be unassigned. For example,
27720 a variable can be passed to a procedure by reference, which takes
27721 the address of the parameter and uses the address to modify the
27722 variable's value, even though it is passed as an IN parameter.
27723 Consider the following example:
27729 Max_Length : constant Natural := 16;
27730 type Char_Ptr is access all Character;
27732 procedure Get_String(Buffer: Char_Ptr; Size : Integer);
27733 pragma Import (C, Get_String, "get_string");
27735 Name : aliased String (1 .. Max_Length) := (others => ' ');
27738 function Addr (S : String) return Char_Ptr is
27739 function To_Char_Ptr is
27740 new Ada.Unchecked_Conversion (System.Address, Char_Ptr);
27742 return To_Char_Ptr (S (S'First)'Address);
27746 Temp := Addr (Name);
27747 Get_String (Temp, Max_Length);
27752 where Get_String is a C function that uses the address in Temp to
27753 modify the variable @cite{Name}. This code is dubious, and arguably
27754 erroneous, and the compiler would be entitled to assume that
27755 @cite{Name} is never modified, and generate code accordingly.
27757 However, in practice, this would cause some existing code that
27758 seems to work with no optimization to start failing at high
27759 levels of optimzization.
27761 What the compiler does for such cases is to assume that marking
27762 a variable as aliased indicates that some "funny business" may
27763 be going on. The optimizer recognizes the aliased keyword and
27764 inhibits optimizations that assume the value cannot be assigned.
27765 This means that the above example will in fact "work" reliably,
27766 that is, it will produce the expected results.
27768 @node Atomic Variables and Optimization,Passive Task Optimization,Aliased Variables and Optimization,Performance Considerations
27769 @anchor{gnat_ugn/gnat_and_program_execution atomic-variables-and-optimization}@anchor{23a}@anchor{gnat_ugn/gnat_and_program_execution id40}@anchor{23b}
27770 @subsubsection Atomic Variables and Optimization
27775 There are two considerations with regard to performance when
27776 atomic variables are used.
27778 First, the RM only guarantees that access to atomic variables
27779 be atomic, it has nothing to say about how this is achieved,
27780 though there is a strong implication that this should not be
27781 achieved by explicit locking code. Indeed GNAT will never
27782 generate any locking code for atomic variable access (it will
27783 simply reject any attempt to make a variable or type atomic
27784 if the atomic access cannot be achieved without such locking code).
27786 That being said, it is important to understand that you cannot
27787 assume that the entire variable will always be accessed. Consider
27794 A,B,C,D : Character;
27797 for R'Alignment use 4;
27800 pragma Atomic (RV);
27807 You cannot assume that the reference to @cite{RV.B}
27808 will read the entire 32-bit
27809 variable with a single load instruction. It is perfectly legitimate if
27810 the hardware allows it to do a byte read of just the B field. This read
27811 is still atomic, which is all the RM requires. GNAT can and does take
27812 advantage of this, depending on the architecture and optimization level.
27813 Any assumption to the contrary is non-portable and risky. Even if you
27814 examine the assembly language and see a full 32-bit load, this might
27815 change in a future version of the compiler.
27817 If your application requires that all accesses to @cite{RV} in this
27818 example be full 32-bit loads, you need to make a copy for the access
27825 RV_Copy : constant R := RV;
27832 Now the reference to RV must read the whole variable.
27833 Actually one can imagine some compiler which figures
27834 out that the whole copy is not required (because only
27835 the B field is actually accessed), but GNAT
27836 certainly won't do that, and we don't know of any
27837 compiler that would not handle this right, and the
27838 above code will in practice work portably across
27839 all architectures (that permit the Atomic declaration).
27841 The second issue with atomic variables has to do with
27842 the possible requirement of generating synchronization
27843 code. For more details on this, consult the sections on
27844 the pragmas Enable/Disable_Atomic_Synchronization in the
27845 GNAT Reference Manual. If performance is critical, and
27846 such synchronization code is not required, it may be
27847 useful to disable it.
27849 @node Passive Task Optimization,,Atomic Variables and Optimization,Performance Considerations
27850 @anchor{gnat_ugn/gnat_and_program_execution id41}@anchor{23c}@anchor{gnat_ugn/gnat_and_program_execution passive-task-optimization}@anchor{23d}
27851 @subsubsection Passive Task Optimization
27854 @geindex Passive Task
27856 A passive task is one which is sufficiently simple that
27857 in theory a compiler could recognize it an implement it
27858 efficiently without creating a new thread. The original design
27859 of Ada 83 had in mind this kind of passive task optimization, but
27860 only a few Ada 83 compilers attempted it. The problem was that
27861 it was difficult to determine the exact conditions under which
27862 the optimization was possible. The result is a very fragile
27863 optimization where a very minor change in the program can
27864 suddenly silently make a task non-optimizable.
27866 With the revisiting of this issue in Ada 95, there was general
27867 agreement that this approach was fundamentally flawed, and the
27868 notion of protected types was introduced. When using protected
27869 types, the restrictions are well defined, and you KNOW that the
27870 operations will be optimized, and furthermore this optimized
27871 performance is fully portable.
27873 Although it would theoretically be possible for GNAT to attempt to
27874 do this optimization, but it really doesn't make sense in the
27875 context of Ada 95, and none of the Ada 95 compilers implement
27876 this optimization as far as we know. In particular GNAT never
27877 attempts to perform this optimization.
27879 In any new Ada 95 code that is written, you should always
27880 use protected types in place of tasks that might be able to
27881 be optimized in this manner.
27882 Of course this does not help if you have legacy Ada 83 code
27883 that depends on this optimization, but it is unusual to encounter
27884 a case where the performance gains from this optimization
27887 Your program should work correctly without this optimization. If
27888 you have performance problems, then the most practical
27889 approach is to figure out exactly where these performance problems
27890 arise, and update those particular tasks to be protected types. Note
27891 that typically clients of the tasks who call entries, will not have
27892 to be modified, only the task definition itself.
27894 @node Text_IO Suggestions,Reducing Size of Executables with Unused Subprogram/Data Elimination,Performance Considerations,Improving Performance
27895 @anchor{gnat_ugn/gnat_and_program_execution text-io-suggestions}@anchor{23e}@anchor{gnat_ugn/gnat_and_program_execution id42}@anchor{23f}
27896 @subsection @cite{Text_IO} Suggestions
27899 @geindex Text_IO and performance
27901 The @cite{Ada.Text_IO} package has fairly high overheads due in part to
27902 the requirement of maintaining page and line counts. If performance
27903 is critical, a recommendation is to use @cite{Stream_IO} instead of
27904 @cite{Text_IO} for volume output, since this package has less overhead.
27906 If @cite{Text_IO} must be used, note that by default output to the standard
27907 output and standard error files is unbuffered (this provides better
27908 behavior when output statements are used for debugging, or if the
27909 progress of a program is observed by tracking the output, e.g. by
27910 using the Unix @emph{tail -f} command to watch redirected output.
27912 If you are generating large volumes of output with @cite{Text_IO} and
27913 performance is an important factor, use a designated file instead
27914 of the standard output file, or change the standard output file to
27915 be buffered using @cite{Interfaces.C_Streams.setvbuf}.
27917 @node Reducing Size of Executables with Unused Subprogram/Data Elimination,,Text_IO Suggestions,Improving Performance
27918 @anchor{gnat_ugn/gnat_and_program_execution id43}@anchor{240}@anchor{gnat_ugn/gnat_and_program_execution reducing-size-of-executables-with-unused-subprogram-data-elimination}@anchor{241}
27919 @subsection Reducing Size of Executables with Unused Subprogram/Data Elimination
27922 @geindex Uunused subprogram/data elimination
27924 This section describes how you can eliminate unused subprograms and data from
27925 your executable just by setting options at compilation time.
27928 * About unused subprogram/data elimination::
27929 * Compilation options::
27930 * Example of unused subprogram/data elimination::
27934 @node About unused subprogram/data elimination,Compilation options,,Reducing Size of Executables with Unused Subprogram/Data Elimination
27935 @anchor{gnat_ugn/gnat_and_program_execution id44}@anchor{242}@anchor{gnat_ugn/gnat_and_program_execution about-unused-subprogram-data-elimination}@anchor{243}
27936 @subsubsection About unused subprogram/data elimination
27939 By default, an executable contains all code and data of its composing objects
27940 (directly linked or coming from statically linked libraries), even data or code
27941 never used by this executable.
27943 This feature will allow you to eliminate such unused code from your
27944 executable, making it smaller (in disk and in memory).
27946 This functionality is available on all Linux platforms except for the IA-64
27947 architecture and on all cross platforms using the ELF binary file format.
27948 In both cases GNU binutils version 2.16 or later are required to enable it.
27950 @node Compilation options,Example of unused subprogram/data elimination,About unused subprogram/data elimination,Reducing Size of Executables with Unused Subprogram/Data Elimination
27951 @anchor{gnat_ugn/gnat_and_program_execution id45}@anchor{244}@anchor{gnat_ugn/gnat_and_program_execution compilation-options}@anchor{245}
27952 @subsubsection Compilation options
27955 The operation of eliminating the unused code and data from the final executable
27956 is directly performed by the linker.
27958 @geindex -ffunction-sections (gcc)
27960 @geindex -fdata-sections (gcc)
27962 In order to do this, it has to work with objects compiled with the
27964 @emph{-ffunction-sections} @emph{-fdata-sections}.
27966 These options are usable with C and Ada files.
27967 They will place respectively each
27968 function or data in a separate section in the resulting object file.
27970 Once the objects and static libraries are created with these options, the
27971 linker can perform the dead code elimination. You can do this by setting
27972 the @emph{-Wl,--gc-sections} option to gcc command or in the
27973 @emph{-largs} section of @emph{gnatmake}. This will perform a
27974 garbage collection of code and data never referenced.
27976 If the linker performs a partial link (@emph{-r} linker option), then you
27977 will need to provide the entry point using the @emph{-e} / @emph{--entry}
27980 Note that objects compiled without the @emph{-ffunction-sections} and
27981 @emph{-fdata-sections} options can still be linked with the executable.
27982 However, no dead code elimination will be performed on those objects (they will
27985 The GNAT static library is now compiled with -ffunction-sections and
27986 -fdata-sections on some platforms. This allows you to eliminate the unused code
27987 and data of the GNAT library from your executable.
27989 @node Example of unused subprogram/data elimination,,Compilation options,Reducing Size of Executables with Unused Subprogram/Data Elimination
27990 @anchor{gnat_ugn/gnat_and_program_execution id46}@anchor{246}@anchor{gnat_ugn/gnat_and_program_execution example-of-unused-subprogram-data-elimination}@anchor{247}
27991 @subsubsection Example of unused subprogram/data elimination
27994 Here is a simple example:
28007 Used_Data : Integer;
28008 Unused_Data : Integer;
28010 procedure Used (Data : Integer);
28011 procedure Unused (Data : Integer);
28014 package body Aux is
28015 procedure Used (Data : Integer) is
28020 procedure Unused (Data : Integer) is
28022 Unused_Data := Data;
28028 @cite{Unused} and @cite{Unused_Data} are never referenced in this code
28029 excerpt, and hence they may be safely removed from the final executable.
28036 $ nm test | grep used
28037 020015f0 T aux__unused
28038 02005d88 B aux__unused_data
28039 020015cc T aux__used
28040 02005d84 B aux__used_data
28042 $ gnatmake test -cargs -fdata-sections -ffunction-sections \\
28043 -largs -Wl,--gc-sections
28045 $ nm test | grep used
28046 02005350 T aux__used
28047 0201ffe0 B aux__used_data
28051 It can be observed that the procedure @cite{Unused} and the object
28052 @cite{Unused_Data} are removed by the linker when using the
28053 appropriate options.
28055 @geindex Overflow checks
28057 @geindex Checks (overflow)
28060 @node Overflow Check Handling in GNAT,Performing Dimensionality Analysis in GNAT,Improving Performance,GNAT and Program Execution
28061 @anchor{gnat_ugn/gnat_and_program_execution id54}@anchor{1f3}@anchor{gnat_ugn/gnat_and_program_execution overflow-check-handling-in-gnat}@anchor{29}
28062 @section Overflow Check Handling in GNAT
28065 This section explains how to control the handling of overflow checks.
28069 * Overflow Checking Modes in GNAT::
28070 * Specifying the Desired Mode::
28071 * Default Settings::
28072 * Implementation Notes::
28076 @node Background,Overflow Checking Modes in GNAT,,Overflow Check Handling in GNAT
28077 @anchor{gnat_ugn/gnat_and_program_execution id55}@anchor{248}@anchor{gnat_ugn/gnat_and_program_execution background}@anchor{249}
28078 @subsection Background
28081 Overflow checks are checks that the compiler may make to ensure
28082 that intermediate results are not out of range. For example:
28093 If @cite{A} has the value @cite{Integer'Last}, then the addition may cause
28094 overflow since the result is out of range of the type @cite{Integer}.
28095 In this case @cite{Constraint_Error} will be raised if checks are
28098 A trickier situation arises in examples like the following:
28109 where @cite{A} is @cite{Integer'Last} and @cite{C} is @cite{-1}.
28110 Now the final result of the expression on the right hand side is
28111 @cite{Integer'Last} which is in range, but the question arises whether the
28112 intermediate addition of @cite{(A + 1)} raises an overflow error.
28114 The (perhaps surprising) answer is that the Ada language
28115 definition does not answer this question. Instead it leaves
28116 it up to the implementation to do one of two things if overflow
28117 checks are enabled.
28123 raise an exception (@cite{Constraint_Error}), or
28126 yield the correct mathematical result which is then used in
28127 subsequent operations.
28130 If the compiler chooses the first approach, then the assignment of this
28131 example will indeed raise @cite{Constraint_Error} if overflow checking is
28132 enabled, or result in erroneous execution if overflow checks are suppressed.
28134 But if the compiler
28135 chooses the second approach, then it can perform both additions yielding
28136 the correct mathematical result, which is in range, so no exception
28137 will be raised, and the right result is obtained, regardless of whether
28138 overflow checks are suppressed.
28140 Note that in the first example an
28141 exception will be raised in either case, since if the compiler
28142 gives the correct mathematical result for the addition, it will
28143 be out of range of the target type of the assignment, and thus
28144 fails the range check.
28146 This lack of specified behavior in the handling of overflow for
28147 intermediate results is a source of non-portability, and can thus
28148 be problematic when programs are ported. Most typically this arises
28149 in a situation where the original compiler did not raise an exception,
28150 and then the application is moved to a compiler where the check is
28151 performed on the intermediate result and an unexpected exception is
28154 Furthermore, when using Ada 2012's preconditions and other
28155 assertion forms, another issue arises. Consider:
28160 procedure P (A, B : Integer) with
28161 Pre => A + B <= Integer'Last;
28165 One often wants to regard arithmetic in a context like this from
28166 a mathematical point of view. So for example, if the two actual parameters
28167 for a call to @cite{P} are both @cite{Integer'Last}, then
28168 the precondition should be regarded as False. If we are executing
28169 in a mode with run-time checks enabled for preconditions, then we would
28170 like this precondition to fail, rather than raising an exception
28171 because of the intermediate overflow.
28173 However, the language definition leaves the specification of
28174 whether the above condition fails (raising @cite{Assert_Error}) or
28175 causes an intermediate overflow (raising @cite{Constraint_Error})
28176 up to the implementation.
28178 The situation is worse in a case such as the following:
28183 procedure Q (A, B, C : Integer) with
28184 Pre => A + B + C <= Integer'Last;
28193 Q (A => Integer'Last, B => 1, C => -1);
28197 From a mathematical point of view the precondition
28198 is True, but at run time we may (but are not guaranteed to) get an
28199 exception raised because of the intermediate overflow (and we really
28200 would prefer this precondition to be considered True at run time).
28202 @node Overflow Checking Modes in GNAT,Specifying the Desired Mode,Background,Overflow Check Handling in GNAT
28203 @anchor{gnat_ugn/gnat_and_program_execution id56}@anchor{24a}@anchor{gnat_ugn/gnat_and_program_execution overflow-checking-modes-in-gnat}@anchor{24b}
28204 @subsection Overflow Checking Modes in GNAT
28207 To deal with the portability issue, and with the problem of
28208 mathematical versus run-time interpretation of the expressions in
28209 assertions, GNAT provides comprehensive control over the handling
28210 of intermediate overflow. GNAT can operate in three modes, and
28211 furthemore, permits separate selection of operating modes for
28212 the expressions within assertions (here the term 'assertions'
28213 is used in the technical sense, which includes preconditions and so forth)
28214 and for expressions appearing outside assertions.
28216 The three modes are:
28222 @emph{Use base type for intermediate operations} (@cite{STRICT})
28224 In this mode, all intermediate results for predefined arithmetic
28225 operators are computed using the base type, and the result must
28226 be in range of the base type. If this is not the
28227 case then either an exception is raised (if overflow checks are
28228 enabled) or the execution is erroneous (if overflow checks are suppressed).
28229 This is the normal default mode.
28232 @emph{Most intermediate overflows avoided} (@cite{MINIMIZED})
28234 In this mode, the compiler attempts to avoid intermediate overflows by
28235 using a larger integer type, typically @cite{Long_Long_Integer},
28236 as the type in which arithmetic is
28237 performed for predefined arithmetic operators. This may be slightly more
28239 run time (compared to suppressing intermediate overflow checks), though
28240 the cost is negligible on modern 64-bit machines. For the examples given
28241 earlier, no intermediate overflows would have resulted in exceptions,
28242 since the intermediate results are all in the range of
28243 @cite{Long_Long_Integer} (typically 64-bits on nearly all implementations
28244 of GNAT). In addition, if checks are enabled, this reduces the number of
28245 checks that must be made, so this choice may actually result in an
28246 improvement in space and time behavior.
28248 However, there are cases where @cite{Long_Long_Integer} is not large
28249 enough, consider the following example:
28254 procedure R (A, B, C, D : Integer) with
28255 Pre => (A**2 * B**2) / (C**2 * D**2) <= 10;
28259 where @cite{A} = @cite{B} = @cite{C} = @cite{D} = @cite{Integer'Last}.
28260 Now the intermediate results are
28261 out of the range of @cite{Long_Long_Integer} even though the final result
28262 is in range and the precondition is True (from a mathematical point
28263 of view). In such a case, operating in this mode, an overflow occurs
28264 for the intermediate computation (which is why this mode
28265 says @emph{most} intermediate overflows are avoided). In this case,
28266 an exception is raised if overflow checks are enabled, and the
28267 execution is erroneous if overflow checks are suppressed.
28270 @emph{All intermediate overflows avoided} (@cite{ELIMINATED})
28272 In this mode, the compiler avoids all intermediate overflows
28273 by using arbitrary precision arithmetic as required. In this
28274 mode, the above example with @cite{A**2 * B**2} would
28275 not cause intermediate overflow, because the intermediate result
28276 would be evaluated using sufficient precision, and the result
28277 of evaluating the precondition would be True.
28279 This mode has the advantage of avoiding any intermediate
28280 overflows, but at the expense of significant run-time overhead,
28281 including the use of a library (included automatically in this
28282 mode) for multiple-precision arithmetic.
28284 This mode provides cleaner semantics for assertions, since now
28285 the run-time behavior emulates true arithmetic behavior for the
28286 predefined arithmetic operators, meaning that there is never a
28287 conflict between the mathematical view of the assertion, and its
28290 Note that in this mode, the behavior is unaffected by whether or
28291 not overflow checks are suppressed, since overflow does not occur.
28292 It is possible for gigantic intermediate expressions to raise
28293 @cite{Storage_Error} as a result of attempting to compute the
28294 results of such expressions (e.g. @cite{Integer'Last ** Integer'Last})
28295 but overflow is impossible.
28298 Note that these modes apply only to the evaluation of predefined
28299 arithmetic, membership, and comparison operators for signed integer
28302 For fixed-point arithmetic, checks can be suppressed. But if checks
28304 then fixed-point values are always checked for overflow against the
28305 base type for intermediate expressions (that is such checks always
28306 operate in the equivalent of @cite{STRICT} mode).
28308 For floating-point, on nearly all architectures, @cite{Machine_Overflows}
28309 is False, and IEEE infinities are generated, so overflow exceptions
28310 are never raised. If you want to avoid infinities, and check that
28311 final results of expressions are in range, then you can declare a
28312 constrained floating-point type, and range checks will be carried
28313 out in the normal manner (with infinite values always failing all
28316 @node Specifying the Desired Mode,Default Settings,Overflow Checking Modes in GNAT,Overflow Check Handling in GNAT
28317 @anchor{gnat_ugn/gnat_and_program_execution specifying-the-desired-mode}@anchor{fd}@anchor{gnat_ugn/gnat_and_program_execution id57}@anchor{24c}
28318 @subsection Specifying the Desired Mode
28321 @geindex pragma Overflow_Mode
28323 The desired mode of for handling intermediate overflow can be specified using
28324 either the @cite{Overflow_Mode} pragma or an equivalent compiler switch.
28325 The pragma has the form
28330 pragma Overflow_Mode ([General =>] MODE [, [Assertions =>] MODE]);
28334 where @cite{MODE} is one of
28340 @cite{STRICT}: intermediate overflows checked (using base type)
28343 @cite{MINIMIZED}: minimize intermediate overflows
28346 @cite{ELIMINATED}: eliminate intermediate overflows
28349 The case is ignored, so @cite{MINIMIZED}, @cite{Minimized} and
28350 @cite{minimized} all have the same effect.
28352 If only the @cite{General} parameter is present, then the given @cite{MODE}
28354 to expressions both within and outside assertions. If both arguments
28355 are present, then @cite{General} applies to expressions outside assertions,
28356 and @cite{Assertions} applies to expressions within assertions. For example:
28361 pragma Overflow_Mode
28362 (General => Minimized, Assertions => Eliminated);
28366 specifies that general expressions outside assertions be evaluated
28367 in 'minimize intermediate overflows' mode, and expressions within
28368 assertions be evaluated in 'eliminate intermediate overflows' mode.
28369 This is often a reasonable choice, avoiding excessive overhead
28370 outside assertions, but assuring a high degree of portability
28371 when importing code from another compiler, while incurring
28372 the extra overhead for assertion expressions to ensure that
28373 the behavior at run time matches the expected mathematical
28376 The @cite{Overflow_Mode} pragma has the same scoping and placement
28377 rules as pragma @cite{Suppress}, so it can occur either as a
28378 configuration pragma, specifying a default for the whole
28379 program, or in a declarative scope, where it applies to the
28380 remaining declarations and statements in that scope.
28382 Note that pragma @cite{Overflow_Mode} does not affect whether
28383 overflow checks are enabled or suppressed. It only controls the
28384 method used to compute intermediate values. To control whether
28385 overflow checking is enabled or suppressed, use pragma @cite{Suppress}
28386 or @cite{Unsuppress} in the usual manner
28388 @geindex -gnato? (gcc)
28390 @geindex -gnato?? (gcc)
28392 Additionally, a compiler switch @emph{-gnato?} or @emph{-gnato??}
28393 can be used to control the checking mode default (which can be subsequently
28394 overridden using pragmas).
28396 Here @code{?} is one of the digits @code{1} through @code{3}:
28401 @multitable {xxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
28408 use base type for intermediate operations (@cite{STRICT})
28416 minimize intermediate overflows (@cite{MINIMIZED})
28424 eliminate intermediate overflows (@cite{ELIMINATED})
28430 As with the pragma, if only one digit appears then it applies to all
28431 cases; if two digits are given, then the first applies outside
28432 assertions, and the second within assertions. Thus the equivalent
28433 of the example pragma above would be
28436 If no digits follow the @emph{-gnato}, then it is equivalent to
28438 causing all intermediate operations to be computed using the base
28439 type (@cite{STRICT} mode).
28441 In addition to setting the mode used for computation of intermediate
28442 results, the @cite{-gnato} switch also enables overflow checking (which
28443 is suppressed by default). It thus combines the effect of using
28444 a pragma @cite{Overflow_Mode} and pragma @cite{Unsuppress}.
28446 @node Default Settings,Implementation Notes,Specifying the Desired Mode,Overflow Check Handling in GNAT
28447 @anchor{gnat_ugn/gnat_and_program_execution id58}@anchor{24d}@anchor{gnat_ugn/gnat_and_program_execution default-settings}@anchor{24e}
28448 @subsection Default Settings
28451 The default mode for overflow checks is
28460 which causes all computations both inside and outside assertions to use
28461 the base type. In addition overflow checks are suppressed.
28463 This retains compatibility with previous versions of
28464 GNAT which suppressed overflow checks by default and always
28465 used the base type for computation of intermediate results.
28467 The switch @emph{-gnato} (with no digits following) is equivalent to
28468 .. index:: -gnato (gcc)
28477 which causes overflow checking of all intermediate overflows
28478 both inside and outside assertions against the base type.
28479 This provides compatibility
28480 with this switch as implemented in previous versions of GNAT.
28482 The pragma @cite{Suppress (Overflow_Check)} disables overflow
28483 checking, but it has no effect on the method used for computing
28484 intermediate results.
28486 The pragma @cite{Unsuppress (Overflow_Check)} enables overflow
28487 checking, but it has no effect on the method used for computing
28488 intermediate results.
28490 @node Implementation Notes,,Default Settings,Overflow Check Handling in GNAT
28491 @anchor{gnat_ugn/gnat_and_program_execution implementation-notes}@anchor{24f}@anchor{gnat_ugn/gnat_and_program_execution id59}@anchor{250}
28492 @subsection Implementation Notes
28495 In practice on typical 64-bit machines, the @cite{MINIMIZED} mode is
28496 reasonably efficient, and can be generally used. It also helps
28497 to ensure compatibility with code imported from some other
28500 Setting all intermediate overflows checking (@cite{CHECKED} mode)
28501 makes sense if you want to
28502 make sure that your code is compatible with any other possible
28503 Ada implementation. This may be useful in ensuring portability
28504 for code that is to be exported to some other compiler than GNAT.
28506 The Ada standard allows the reassociation of expressions at
28507 the same precedence level if no parentheses are present. For
28508 example, @cite{A+B+C} parses as though it were @cite{(A+B)+C}, but
28509 the compiler can reintepret this as @cite{A+(B+C)}, possibly
28510 introducing or eliminating an overflow exception. The GNAT
28511 compiler never takes advantage of this freedom, and the
28512 expression @cite{A+B+C} will be evaluated as @cite{(A+B)+C}.
28513 If you need the other order, you can write the parentheses
28514 explicitly @cite{A+(B+C)} and GNAT will respect this order.
28516 The use of @cite{ELIMINATED} mode will cause the compiler to
28517 automatically include an appropriate arbitrary precision
28518 integer arithmetic package. The compiler will make calls
28519 to this package, though only in cases where it cannot be
28520 sure that @cite{Long_Long_Integer} is sufficient to guard against
28521 intermediate overflows. This package does not use dynamic
28522 alllocation, but it does use the secondary stack, so an
28523 appropriate secondary stack package must be present (this
28524 is always true for standard full Ada, but may require
28525 specific steps for restricted run times such as ZFP).
28527 Although @cite{ELIMINATED} mode causes expressions to use arbitrary
28528 precision arithmetic, avoiding overflow, the final result
28529 must be in an appropriate range. This is true even if the
28530 final result is of type @cite{[Long_[Long_]]Integer'Base}, which
28531 still has the same bounds as its associated constrained
28534 Currently, the @cite{ELIMINATED} mode is only available on target
28535 platforms for which @cite{Long_Long_Integer} is 64-bits (nearly all GNAT
28538 @node Performing Dimensionality Analysis in GNAT,Stack Related Facilities,Overflow Check Handling in GNAT,GNAT and Program Execution
28539 @anchor{gnat_ugn/gnat_and_program_execution performing-dimensionality-analysis-in-gnat}@anchor{2a}@anchor{gnat_ugn/gnat_and_program_execution id60}@anchor{1f4}
28540 @section Performing Dimensionality Analysis in GNAT
28543 @geindex Dimensionality analysis
28545 The GNAT compiler supports dimensionality checking. The user can
28546 specify physical units for objects, and the compiler will verify that uses
28547 of these objects are compatible with their dimensions, in a fashion that is
28548 familiar to engineering practice. The dimensions of algebraic expressions
28549 (including powers with static exponents) are computed from their constituents.
28551 @geindex Dimension_System aspect
28553 @geindex Dimension aspect
28555 This feature depends on Ada 2012 aspect specifications, and is available from
28556 version 7.0.1 of GNAT onwards.
28557 The GNAT-specific aspect @cite{Dimension_System}
28558 allows you to define a system of units; the aspect @cite{Dimension}
28559 then allows the user to declare dimensioned quantities within a given system.
28560 (These aspects are described in the @emph{Implementation Defined Aspects}
28561 chapter of the @emph{GNAT Reference Manual}).
28563 The major advantage of this model is that it does not require the declaration of
28564 multiple operators for all possible combinations of types: it is only necessary
28565 to use the proper subtypes in object declarations.
28567 @geindex System.Dim.Mks package (GNAT library)
28569 @geindex MKS_Type type
28571 The simplest way to impose dimensionality checking on a computation is to make
28572 use of the package @cite{System.Dim.Mks},
28573 which is part of the GNAT library. This
28574 package defines a floating-point type @cite{MKS_Type},
28575 for which a sequence of
28576 dimension names are specified, together with their conventional abbreviations.
28577 The following should be read together with the full specification of the
28578 package, in file @code{s-dimmks.ads}.
28582 @geindex s-dimmks.ads file
28585 type Mks_Type is new Long_Long_Float
28587 Dimension_System => (
28588 (Unit_Name => Meter, Unit_Symbol => 'm', Dim_Symbol => 'L'),
28589 (Unit_Name => Kilogram, Unit_Symbol => "kg", Dim_Symbol => 'M'),
28590 (Unit_Name => Second, Unit_Symbol => 's', Dim_Symbol => 'T'),
28591 (Unit_Name => Ampere, Unit_Symbol => 'A', Dim_Symbol => 'I'),
28592 (Unit_Name => Kelvin, Unit_Symbol => 'K', Dim_Symbol => "Theta"),
28593 (Unit_Name => Mole, Unit_Symbol => "mol", Dim_Symbol => 'N'),
28594 (Unit_Name => Candela, Unit_Symbol => "cd", Dim_Symbol => 'J'));
28598 The package then defines a series of subtypes that correspond to these
28599 conventional units. For example:
28604 subtype Length is Mks_Type
28606 Dimension => (Symbol => 'm', Meter => 1, others => 0);
28610 and similarly for @cite{Mass}, @cite{Time}, @cite{Electric_Current},
28611 @cite{Thermodynamic_Temperature}, @cite{Amount_Of_Substance}, and
28612 @cite{Luminous_Intensity} (the standard set of units of the SI system).
28614 The package also defines conventional names for values of each unit, for
28619 @c code-block":: ada
28621 @c m : constant Length := 1.0;
28622 @c kg : constant Mass := 1.0;
28623 @c s : constant Time := 1.0;
28624 @c A : constant Electric_Current := 1.0;
28627 as well as useful multiples of these units:
28632 cm : constant Length := 1.0E-02;
28633 g : constant Mass := 1.0E-03;
28634 min : constant Time := 60.0;
28635 day : constant Time := 60.0 * 24.0 * min;
28640 Using this package, you can then define a derived unit by
28641 providing the aspect that
28642 specifies its dimensions within the MKS system, as well as the string to
28643 be used for output of a value of that unit:
28648 subtype Acceleration is Mks_Type
28649 with Dimension => ("m/sec^2",
28656 Here is a complete example of use:
28661 with System.Dim.MKS; use System.Dim.Mks;
28662 with System.Dim.Mks_IO; use System.Dim.Mks_IO;
28663 with Text_IO; use Text_IO;
28664 procedure Free_Fall is
28665 subtype Acceleration is Mks_Type
28666 with Dimension => ("m/sec^2", 1, 0, -2, others => 0);
28667 G : constant acceleration := 9.81 * m / (s ** 2);
28668 T : Time := 10.0*s;
28672 Put ("Gravitational constant: ");
28673 Put (G, Aft => 2, Exp => 0); Put_Line ("");
28674 Distance := 0.5 * G * T ** 2;
28675 Put ("distance travelled in 10 seconds of free fall ");
28676 Put (Distance, Aft => 2, Exp => 0);
28682 Execution of this program yields:
28687 Gravitational constant: 9.81 m/sec^2
28688 distance travelled in 10 seconds of free fall 490.50 m
28692 However, incorrect assignments such as:
28698 Distance := 5.0 * kg:
28702 are rejected with the following diagnoses:
28708 >>> dimensions mismatch in assignment
28709 >>> left-hand side has dimension [L]
28710 >>> right-hand side is dimensionless
28712 Distance := 5.0 * kg:
28713 >>> dimensions mismatch in assignment
28714 >>> left-hand side has dimension [L]
28715 >>> right-hand side has dimension [M]
28719 The dimensions of an expression are properly displayed, even if there is
28720 no explicit subtype for it. If we add to the program:
28725 Put ("Final velocity: ");
28726 Put (G * T, Aft =>2, Exp =>0);
28731 then the output includes:
28736 Final velocity: 98.10 m.s**(-1)
28740 @node Stack Related Facilities,Memory Management Issues,Performing Dimensionality Analysis in GNAT,GNAT and Program Execution
28741 @anchor{gnat_ugn/gnat_and_program_execution id61}@anchor{1f5}@anchor{gnat_ugn/gnat_and_program_execution stack-related-facilities}@anchor{2b}
28742 @section Stack Related Facilities
28745 This section describes some useful tools associated with stack
28746 checking and analysis. In
28747 particular, it deals with dynamic and static stack usage measurements.
28750 * Stack Overflow Checking::
28751 * Static Stack Usage Analysis::
28752 * Dynamic Stack Usage Analysis::
28756 @node Stack Overflow Checking,Static Stack Usage Analysis,,Stack Related Facilities
28757 @anchor{gnat_ugn/gnat_and_program_execution id62}@anchor{251}@anchor{gnat_ugn/gnat_and_program_execution stack-overflow-checking}@anchor{f9}
28758 @subsection Stack Overflow Checking
28761 @geindex Stack Overflow Checking
28763 @geindex -fstack-check (gcc)
28765 For most operating systems, @emph{gcc} does not perform stack overflow
28766 checking by default. This means that if the main environment task or
28767 some other task exceeds the available stack space, then unpredictable
28768 behavior will occur. Most native systems offer some level of protection by
28769 adding a guard page at the end of each task stack. This mechanism is usually
28770 not enough for dealing properly with stack overflow situations because
28771 a large local variable could "jump" above the guard page.
28772 Furthermore, when the
28773 guard page is hit, there may not be any space left on the stack for executing
28774 the exception propagation code. Enabling stack checking avoids
28777 To activate stack checking, compile all units with the gcc option
28778 @cite{-fstack-check}. For example:
28783 $ gcc -c -fstack-check package1.adb
28787 Units compiled with this option will generate extra instructions to check
28788 that any use of the stack (for procedure calls or for declaring local
28789 variables in declare blocks) does not exceed the available stack space.
28790 If the space is exceeded, then a @cite{Storage_Error} exception is raised.
28792 For declared tasks, the stack size is controlled by the size
28793 given in an applicable @cite{Storage_Size} pragma or by the value specified
28794 at bind time with @code{-d} (@ref{123,,Switches for gnatbind}) or is set to
28795 the default size as defined in the GNAT runtime otherwise.
28797 @geindex GNAT_STACK_LIMIT
28799 For the environment task, the stack size depends on
28800 system defaults and is unknown to the compiler. Stack checking
28801 may still work correctly if a fixed
28802 size stack is allocated, but this cannot be guaranteed.
28803 To ensure that a clean exception is signalled for stack
28804 overflow, set the environment variable
28805 @geindex GNAT_STACK_LIMIT
28806 @geindex environment variable; GNAT_STACK_LIMIT
28807 @code{GNAT_STACK_LIMIT} to indicate the maximum
28808 stack area that can be used, as in:
28813 $ SET GNAT_STACK_LIMIT 1600
28817 The limit is given in kilobytes, so the above declaration would
28818 set the stack limit of the environment task to 1.6 megabytes.
28819 Note that the only purpose of this usage is to limit the amount
28820 of stack used by the environment task. If it is necessary to
28821 increase the amount of stack for the environment task, then this
28822 is an operating systems issue, and must be addressed with the
28823 appropriate operating systems commands.
28825 @node Static Stack Usage Analysis,Dynamic Stack Usage Analysis,Stack Overflow Checking,Stack Related Facilities
28826 @anchor{gnat_ugn/gnat_and_program_execution static-stack-usage-analysis}@anchor{fa}@anchor{gnat_ugn/gnat_and_program_execution id63}@anchor{252}
28827 @subsection Static Stack Usage Analysis
28830 @geindex Static Stack Usage Analysis
28832 @geindex -fstack-usage
28834 A unit compiled with @code{-fstack-usage} will generate an extra file
28836 the maximum amount of stack used, on a per-function basis.
28837 The file has the same
28838 basename as the target object file with a @code{.su} extension.
28839 Each line of this file is made up of three fields:
28845 The name of the function.
28851 One or more qualifiers: @cite{static}, @cite{dynamic}, @cite{bounded}.
28854 The second field corresponds to the size of the known part of the function
28857 The qualifier @cite{static} means that the function frame size
28859 It usually means that all local variables have a static size.
28860 In this case, the second field is a reliable measure of the function stack
28863 The qualifier @cite{dynamic} means that the function frame size is not static.
28864 It happens mainly when some local variables have a dynamic size. When this
28865 qualifier appears alone, the second field is not a reliable measure
28866 of the function stack analysis. When it is qualified with @cite{bounded}, it
28867 means that the second field is a reliable maximum of the function stack
28870 A unit compiled with @code{-Wstack-usage} will issue a warning for each
28871 subprogram whose stack usage might be larger than the specified amount of
28872 bytes. The wording is in keeping with the qualifier documented above.
28874 @node Dynamic Stack Usage Analysis,,Static Stack Usage Analysis,Stack Related Facilities
28875 @anchor{gnat_ugn/gnat_and_program_execution id64}@anchor{253}@anchor{gnat_ugn/gnat_and_program_execution dynamic-stack-usage-analysis}@anchor{125}
28876 @subsection Dynamic Stack Usage Analysis
28879 It is possible to measure the maximum amount of stack used by a task, by
28880 adding a switch to @emph{gnatbind}, as:
28885 $ gnatbind -u0 file
28889 With this option, at each task termination, its stack usage is output on
28891 It is not always convenient to output the stack usage when the program
28892 is still running. Hence, it is possible to delay this output until program
28893 termination. for a given number of tasks specified as the argument of the
28894 @code{-u} option. For instance:
28899 $ gnatbind -u100 file
28903 will buffer the stack usage information of the first 100 tasks to terminate and
28904 output this info at program termination. Results are displayed in four
28910 Index | Task Name | Stack Size | Stack Usage
28920 @emph{Index} is a number associated with each task.
28923 @emph{Task Name} is the name of the task analyzed.
28926 @emph{Stack Size} is the maximum size for the stack.
28929 @emph{Stack Usage} is the measure done by the stack analyzer.
28930 In order to prevent overflow, the stack
28931 is not entirely analyzed, and it's not possible to know exactly how
28932 much has actually been used.
28935 The environment task stack, e.g., the stack that contains the main unit, is
28936 only processed when the environment variable GNAT_STACK_LIMIT is set.
28938 The package @cite{GNAT.Task_Stack_Usage} provides facilities to get
28939 stack usage reports at run-time. See its body for the details.
28941 @node Memory Management Issues,,Stack Related Facilities,GNAT and Program Execution
28942 @anchor{gnat_ugn/gnat_and_program_execution id65}@anchor{1f6}@anchor{gnat_ugn/gnat_and_program_execution memory-management-issues}@anchor{2c}
28943 @section Memory Management Issues
28946 This section describes some useful memory pools provided in the GNAT library
28947 and in particular the GNAT Debug Pool facility, which can be used to detect
28948 incorrect uses of access values (including 'dangling references').
28952 * Some Useful Memory Pools::
28953 * The GNAT Debug Pool Facility::
28957 @node Some Useful Memory Pools,The GNAT Debug Pool Facility,,Memory Management Issues
28958 @anchor{gnat_ugn/gnat_and_program_execution id66}@anchor{254}@anchor{gnat_ugn/gnat_and_program_execution some-useful-memory-pools}@anchor{255}
28959 @subsection Some Useful Memory Pools
28962 @geindex Memory Pool
28967 The @cite{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
28968 storage pool. Allocations use the standard system call @cite{malloc} while
28969 deallocations use the standard system call @cite{free}. No reclamation is
28970 performed when the pool goes out of scope. For performance reasons, the
28971 standard default Ada allocators/deallocators do not use any explicit storage
28972 pools but if they did, they could use this storage pool without any change in
28973 behavior. That is why this storage pool is used when the user
28974 manages to make the default implicit allocator explicit as in this example:
28979 type T1 is access Something;
28980 -- no Storage pool is defined for T2
28982 type T2 is access Something_Else;
28983 for T2'Storage_Pool use T1'Storage_Pool;
28984 -- the above is equivalent to
28985 for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
28989 The @cite{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
28990 pool. The allocation strategy is similar to @cite{Pool_Local}'s
28991 except that the all
28992 storage allocated with this pool is reclaimed when the pool object goes out of
28993 scope. This pool provides a explicit mechanism similar to the implicit one
28994 provided by several Ada 83 compilers for allocations performed through a local
28995 access type and whose purpose was to reclaim memory when exiting the
28996 scope of a given local access. As an example, the following program does not
28997 leak memory even though it does not perform explicit deallocation:
29002 with System.Pool_Local;
29003 procedure Pooloc1 is
29004 procedure Internal is
29005 type A is access Integer;
29006 X : System.Pool_Local.Unbounded_Reclaim_Pool;
29007 for A'Storage_Pool use X;
29010 for I in 1 .. 50 loop
29015 for I in 1 .. 100 loop
29022 The @cite{System.Pool_Size} package implements the Stack_Bounded_Pool used when
29023 @cite{Storage_Size} is specified for an access type.
29024 The whole storage for the pool is
29025 allocated at once, usually on the stack at the point where the access type is
29026 elaborated. It is automatically reclaimed when exiting the scope where the
29027 access type is defined. This package is not intended to be used directly by the
29028 user and it is implicitly used for each such declaration:
29033 type T1 is access Something;
29034 for T1'Storage_Size use 10_000;
29038 @node The GNAT Debug Pool Facility,,Some Useful Memory Pools,Memory Management Issues
29039 @anchor{gnat_ugn/gnat_and_program_execution id67}@anchor{256}@anchor{gnat_ugn/gnat_and_program_execution the-gnat-debug-pool-facility}@anchor{257}
29040 @subsection The GNAT Debug Pool Facility
29043 @geindex Debug Pool
29047 @geindex memory corruption
29049 The use of unchecked deallocation and unchecked conversion can easily
29050 lead to incorrect memory references. The problems generated by such
29051 references are usually difficult to tackle because the symptoms can be
29052 very remote from the origin of the problem. In such cases, it is
29053 very helpful to detect the problem as early as possible. This is the
29054 purpose of the Storage Pool provided by @cite{GNAT.Debug_Pools}.
29056 In order to use the GNAT specific debugging pool, the user must
29057 associate a debug pool object with each of the access types that may be
29058 related to suspected memory problems. See Ada Reference Manual 13.11.
29063 type Ptr is access Some_Type;
29064 Pool : GNAT.Debug_Pools.Debug_Pool;
29065 for Ptr'Storage_Pool use Pool;
29069 @cite{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
29070 pool: the @cite{Checked_Pool}. Such pools, like standard Ada storage pools,
29071 allow the user to redefine allocation and deallocation strategies. They
29072 also provide a checkpoint for each dereference, through the use of
29073 the primitive operation @cite{Dereference} which is implicitly called at
29074 each dereference of an access value.
29076 Once an access type has been associated with a debug pool, operations on
29077 values of the type may raise four distinct exceptions,
29078 which correspond to four potential kinds of memory corruption:
29084 @cite{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
29087 @cite{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
29090 @cite{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
29093 @cite{GNAT.Debug_Pools.Freeing_Deallocated_Storage}
29096 For types associated with a Debug_Pool, dynamic allocation is performed using
29097 the standard GNAT allocation routine. References to all allocated chunks of
29098 memory are kept in an internal dictionary. Several deallocation strategies are
29099 provided, whereupon the user can choose to release the memory to the system,
29100 keep it allocated for further invalid access checks, or fill it with an easily
29101 recognizable pattern for debug sessions. The memory pattern is the old IBM
29102 hexadecimal convention: @cite{16#DEADBEEF#}.
29104 See the documentation in the file g-debpoo.ads for more information on the
29105 various strategies.
29107 Upon each dereference, a check is made that the access value denotes a
29108 properly allocated memory location. Here is a complete example of use of
29109 @cite{Debug_Pools}, that includes typical instances of memory corruption:
29114 with Gnat.Io; use Gnat.Io;
29115 with Unchecked_Deallocation;
29116 with Unchecked_Conversion;
29117 with GNAT.Debug_Pools;
29118 with System.Storage_Elements;
29119 with Ada.Exceptions; use Ada.Exceptions;
29120 procedure Debug_Pool_Test is
29122 type T is access Integer;
29123 type U is access all T;
29125 P : GNAT.Debug_Pools.Debug_Pool;
29126 for T'Storage_Pool use P;
29128 procedure Free is new Unchecked_Deallocation (Integer, T);
29129 function UC is new Unchecked_Conversion (U, T);
29132 procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
29142 Put_Line (Integer'Image(B.all));
29144 when E : others => Put_Line ("raised: " & Exception_Name (E));
29149 when E : others => Put_Line ("raised: " & Exception_Name (E));
29153 Put_Line (Integer'Image(B.all));
29155 when E : others => Put_Line ("raised: " & Exception_Name (E));
29160 when E : others => Put_Line ("raised: " & Exception_Name (E));
29163 end Debug_Pool_Test;
29167 The debug pool mechanism provides the following precise diagnostics on the
29168 execution of this erroneous program:
29174 Total allocated bytes : 0
29175 Total deallocated bytes : 0
29176 Current Water Mark: 0
29180 Total allocated bytes : 8
29181 Total deallocated bytes : 0
29182 Current Water Mark: 8
29185 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
29186 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
29187 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
29188 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
29190 Total allocated bytes : 8
29191 Total deallocated bytes : 4
29192 Current Water Mark: 4
29198 @c -- Non-breaking space in running text
29199 @c -- E.g. Ada |nbsp| 95
29201 @node Platform-Specific Information,Example of Binder Output File,GNAT and Program Execution,Top
29202 @anchor{gnat_ugn/platform_specific_information platform-specific-information}@anchor{f}@anchor{gnat_ugn/platform_specific_information doc}@anchor{258}@anchor{gnat_ugn/platform_specific_information id1}@anchor{259}
29203 @chapter Platform-Specific Information
29206 This appendix contains information relating to the implementation
29207 of run-time libraries on various platforms and also covers
29208 topics related to the GNAT implementation on Windows and Mac OS.
29211 * Run-Time Libraries::
29212 * Specifying a Run-Time Library::
29213 * Microsoft Windows Topics::
29218 @node Run-Time Libraries,Specifying a Run-Time Library,,Platform-Specific Information
29219 @anchor{gnat_ugn/platform_specific_information id2}@anchor{25a}@anchor{gnat_ugn/platform_specific_information run-time-libraries}@anchor{2d}
29220 @section Run-Time Libraries
29223 @geindex Tasking and threads libraries
29225 @geindex Threads libraries and tasking
29227 @geindex Run-time libraries (platform-specific information)
29229 The GNAT run-time implementation may vary with respect to both the
29230 underlying threads library and the exception handling scheme.
29231 For threads support, one or more of the following are supplied:
29237 @strong{native threads library}, a binding to the thread package from
29238 the underlying operating system
29241 @strong{pthreads library} (Sparc Solaris only), a binding to the Solaris
29242 POSIX thread package
29245 For exception handling, either or both of two models are supplied:
29249 @geindex Zero-Cost Exceptions
29251 @geindex ZCX (Zero-Cost Exceptions)
29258 @strong{Zero-Cost Exceptions} ("ZCX"),
29259 which uses binder-generated tables that
29260 are interrogated at run time to locate a handler.
29262 @geindex setjmp/longjmp Exception Model
29264 @geindex SJLJ (setjmp/longjmp Exception Model)
29267 @strong{setjmp / longjmp} ('SJLJ'),
29268 which uses dynamically-set data to establish
29269 the set of handlers
29272 Most programs should experience a substantial speed improvement by
29273 being compiled with a ZCX run-time.
29274 This is especially true for
29275 tasking applications or applications with many exception handlers.@}
29277 This section summarizes which combinations of threads and exception support
29278 are supplied on various GNAT platforms.
29279 It then shows how to select a particular library either
29280 permanently or temporarily,
29281 explains the properties of (and tradeoffs among) the various threads
29282 libraries, and provides some additional
29283 information about several specific platforms.
29286 * Summary of Run-Time Configurations::
29290 @node Summary of Run-Time Configurations,,,Run-Time Libraries
29291 @anchor{gnat_ugn/platform_specific_information summary-of-run-time-configurations}@anchor{25b}@anchor{gnat_ugn/platform_specific_information id3}@anchor{25c}
29292 @subsection Summary of Run-Time Configurations
29296 @multitable {xxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxx}
29443 native LynxOS threads
29491 native Win32 threads
29503 native Win32 threads
29541 @node Specifying a Run-Time Library,Microsoft Windows Topics,Run-Time Libraries,Platform-Specific Information
29542 @anchor{gnat_ugn/platform_specific_information specifying-a-run-time-library}@anchor{25d}@anchor{gnat_ugn/platform_specific_information id4}@anchor{25e}
29543 @section Specifying a Run-Time Library
29546 The @code{adainclude} subdirectory containing the sources of the GNAT
29547 run-time library, and the @code{adalib} subdirectory containing the
29548 @code{ALI} files and the static and/or shared GNAT library, are located
29549 in the gcc target-dependent area:
29554 target=$prefix/lib/gcc/gcc-*dumpmachine*/gcc-*dumpversion*/
29558 As indicated above, on some platforms several run-time libraries are supplied.
29559 These libraries are installed in the target dependent area and
29560 contain a complete source and binary subdirectory. The detailed description
29561 below explains the differences between the different libraries in terms of
29562 their thread support.
29564 The default run-time library (when GNAT is installed) is @emph{rts-native}.
29565 This default run time is selected by the means of soft links.
29566 For example on x86-linux:
29572 -- +--- adainclude----------+
29574 -- +--- adalib-----------+ |
29576 -- +--- rts-native | |
29578 -- | +--- adainclude <---+
29580 -- | +--- adalib <----+
29589 If the @emph{rts-sjlj} library is to be selected on a permanent basis,
29590 these soft links can be modified with the following commands:
29596 $ rm -f adainclude adalib
29597 $ ln -s rts-sjlj/adainclude adainclude
29598 $ ln -s rts-sjlj/adalib adalib
29602 Alternatively, you can specify @code{rts-sjlj/adainclude} in the file
29603 @code{$target/ada_source_path} and @code{rts-sjlj/adalib} in
29604 @code{$target/ada_object_path}.
29606 @geindex --RTS option
29608 Selecting another run-time library temporarily can be
29609 achieved by using the @emph{--RTS} switch, e.g., @emph{--RTS=sjlj}
29610 @anchor{gnat_ugn/platform_specific_information choosing-the-scheduling-policy}@anchor{25f}
29611 @geindex SCHED_FIFO scheduling policy
29613 @geindex SCHED_RR scheduling policy
29615 @geindex SCHED_OTHER scheduling policy
29618 * Choosing the Scheduling Policy::
29619 * Solaris-Specific Considerations::
29620 * Solaris Threads Issues::
29621 * AIX-Specific Considerations::
29625 @node Choosing the Scheduling Policy,Solaris-Specific Considerations,,Specifying a Run-Time Library
29626 @anchor{gnat_ugn/platform_specific_information id5}@anchor{260}
29627 @subsection Choosing the Scheduling Policy
29630 When using a POSIX threads implementation, you have a choice of several
29631 scheduling policies: @cite{SCHED_FIFO}, @cite{SCHED_RR} and @cite{SCHED_OTHER}.
29633 Typically, the default is @cite{SCHED_OTHER}, while using @cite{SCHED_FIFO}
29634 or @cite{SCHED_RR} requires special (e.g., root) privileges.
29636 @geindex pragma Time_Slice
29638 @geindex -T0 option
29640 @geindex pragma Task_Dispatching_Policy
29642 By default, GNAT uses the @cite{SCHED_OTHER} policy. To specify
29644 you can use one of the following:
29650 @cite{pragma Time_Slice (0.0)}
29653 the corresponding binder option @emph{-T0}
29656 @cite{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
29659 To specify @cite{SCHED_RR},
29660 you should use @cite{pragma Time_Slice} with a
29661 value greater than 0.0, or else use the corresponding @emph{-T}
29664 @geindex Solaris Sparc threads libraries
29666 @node Solaris-Specific Considerations,Solaris Threads Issues,Choosing the Scheduling Policy,Specifying a Run-Time Library
29667 @anchor{gnat_ugn/platform_specific_information id6}@anchor{261}@anchor{gnat_ugn/platform_specific_information solaris-specific-considerations}@anchor{262}
29668 @subsection Solaris-Specific Considerations
29671 This section addresses some topics related to the various threads libraries
29674 @geindex rts-pthread threads library
29676 @node Solaris Threads Issues,AIX-Specific Considerations,Solaris-Specific Considerations,Specifying a Run-Time Library
29677 @anchor{gnat_ugn/platform_specific_information id7}@anchor{263}@anchor{gnat_ugn/platform_specific_information solaris-threads-issues}@anchor{264}
29678 @subsection Solaris Threads Issues
29681 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
29682 library based on POSIX threads --- @emph{rts-pthread}.
29684 @geindex PTHREAD_PRIO_INHERIT policy (under rts-pthread)
29686 @geindex PTHREAD_PRIO_PROTECT policy (under rts-pthread)
29688 @geindex pragma Locking_Policy (under rts-pthread)
29690 @geindex Inheritance_Locking (under rts-pthread)
29692 @geindex Ceiling_Locking (under rts-pthread)
29694 This run-time library has the advantage of being mostly shared across all
29695 POSIX-compliant thread implementations, and it also provides under
29696 Solaris 8 the @cite{PTHREAD_PRIO_INHERIT}
29697 and @cite{PTHREAD_PRIO_PROTECT}
29698 semantics that can be selected using the predefined pragma
29699 @cite{Locking_Policy}
29701 @cite{Inheritance_Locking} and @cite{Ceiling_Locking} as the policy.
29703 As explained above, the native run-time library is based on the Solaris thread
29704 library (@cite{libthread}) and is the default library.
29706 @geindex GNAT_PROCESSOR environment variable (on Sparc Solaris)
29708 When the Solaris threads library is used (this is the default), programs
29709 compiled with GNAT can automatically take advantage of
29710 and can thus execute on multiple processors.
29711 The user can alternatively specify a processor on which the program should run
29712 to emulate a single-processor system. The multiprocessor / uniprocessor choice
29714 setting the environment variable
29715 @geindex GNAT_PROCESSOR
29716 @geindex environment variable; GNAT_PROCESSOR
29717 @code{GNAT_PROCESSOR}
29718 to one of the following:
29723 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
29726 @code{GNAT_PROCESSOR} Value
29738 Use the default configuration (run the program on all
29739 available processors) - this is the same as having @cite{GNAT_PROCESSOR}
29748 Let the run-time implementation choose one processor and run the
29749 program on that processor
29753 @emph{0 .. Last_Proc}
29757 Run the program on the specified processor.
29758 @cite{Last_Proc} is equal to @cite{_SC_NPROCESSORS_CONF - 1}
29759 (where @cite{_SC_NPROCESSORS_CONF} is a system variable).
29765 @node AIX-Specific Considerations,,Solaris Threads Issues,Specifying a Run-Time Library
29766 @anchor{gnat_ugn/platform_specific_information aix-specific-considerations}@anchor{265}@anchor{gnat_ugn/platform_specific_information id8}@anchor{266}
29767 @subsection AIX-Specific Considerations
29770 @geindex AIX resolver library
29772 On AIX, the resolver library initializes some internal structure on
29773 the first call to @cite{get*by*} functions, which are used to implement
29774 @cite{GNAT.Sockets.Get_Host_By_Name} and
29775 @cite{GNAT.Sockets.Get_Host_By_Address}.
29776 If such initialization occurs within an Ada task, and the stack size for
29777 the task is the default size, a stack overflow may occur.
29779 To avoid this overflow, the user should either ensure that the first call
29780 to @cite{GNAT.Sockets.Get_Host_By_Name} or
29781 @cite{GNAT.Sockets.Get_Host_By_Addrss}
29782 occurs in the environment task, or use @cite{pragma Storage_Size} to
29783 specify a sufficiently large size for the stack of the task that contains
29786 @geindex Windows NT
29788 @geindex Windows 95
29790 @geindex Windows 98
29792 @node Microsoft Windows Topics,Mac OS Topics,Specifying a Run-Time Library,Platform-Specific Information
29793 @anchor{gnat_ugn/platform_specific_information microsoft-windows-topics}@anchor{2e}@anchor{gnat_ugn/platform_specific_information id9}@anchor{267}
29794 @section Microsoft Windows Topics
29797 This section describes topics that are specific to the Microsoft Windows
29805 * Using GNAT on Windows::
29806 * Using a network installation of GNAT::
29807 * CONSOLE and WINDOWS subsystems::
29808 * Temporary Files::
29809 * Mixed-Language Programming on Windows::
29813 @node Using GNAT on Windows,Using a network installation of GNAT,,Microsoft Windows Topics
29814 @anchor{gnat_ugn/platform_specific_information using-gnat-on-windows}@anchor{268}@anchor{gnat_ugn/platform_specific_information id10}@anchor{269}
29815 @subsection Using GNAT on Windows
29818 One of the strengths of the GNAT technology is that its tool set
29819 (@emph{gcc}, @emph{gnatbind}, @emph{gnatlink}, @emph{gnatmake}, the
29820 @cite{gdb} debugger, etc.) is used in the same way regardless of the
29823 On Windows this tool set is complemented by a number of Microsoft-specific
29824 tools that have been provided to facilitate interoperability with Windows
29825 when this is required. With these tools:
29831 You can build applications using the @cite{CONSOLE} or @cite{WINDOWS}
29835 You can use any Dynamically Linked Library (DLL) in your Ada code (both
29836 relocatable and non-relocatable DLLs are supported).
29839 You can build Ada DLLs for use in other applications. These applications
29840 can be written in a language other than Ada (e.g., C, C++, etc). Again both
29841 relocatable and non-relocatable Ada DLLs are supported.
29844 You can include Windows resources in your Ada application.
29847 You can use or create COM/DCOM objects.
29850 Immediately below are listed all known general GNAT-for-Windows restrictions.
29851 Other restrictions about specific features like Windows Resources and DLLs
29852 are listed in separate sections below.
29858 It is not possible to use @cite{GetLastError} and @cite{SetLastError}
29859 when tasking, protected records, or exceptions are used. In these
29860 cases, in order to implement Ada semantics, the GNAT run-time system
29861 calls certain Win32 routines that set the last error variable to 0 upon
29862 success. It should be possible to use @cite{GetLastError} and
29863 @cite{SetLastError} when tasking, protected record, and exception
29864 features are not used, but it is not guaranteed to work.
29867 It is not possible to link against Microsoft C++ libraries except for
29868 import libraries. Interfacing must be done by the mean of DLLs.
29871 It is possible to link against Microsoft C libraries. Yet the preferred
29872 solution is to use C/C++ compiler that comes with GNAT, since it
29873 doesn't require having two different development environments and makes the
29874 inter-language debugging experience smoother.
29877 When the compilation environment is located on FAT32 drives, users may
29878 experience recompilations of the source files that have not changed if
29879 Daylight Saving Time (DST) state has changed since the last time files
29880 were compiled. NTFS drives do not have this problem.
29883 No components of the GNAT toolset use any entries in the Windows
29884 registry. The only entries that can be created are file associations and
29885 PATH settings, provided the user has chosen to create them at installation
29886 time, as well as some minimal book-keeping information needed to correctly
29887 uninstall or integrate different GNAT products.
29890 @node Using a network installation of GNAT,CONSOLE and WINDOWS subsystems,Using GNAT on Windows,Microsoft Windows Topics
29891 @anchor{gnat_ugn/platform_specific_information id11}@anchor{26a}@anchor{gnat_ugn/platform_specific_information using-a-network-installation-of-gnat}@anchor{26b}
29892 @subsection Using a network installation of GNAT
29895 Make sure the system on which GNAT is installed is accessible from the
29896 current machine, i.e., the install location is shared over the network.
29897 Shared resources are accessed on Windows by means of UNC paths, which
29898 have the format @cite{\\server\sharename\path}
29900 In order to use such a network installation, simply add the UNC path of the
29901 @code{bin} directory of your GNAT installation in front of your PATH. For
29902 example, if GNAT is installed in @code{\GNAT} directory of a share location
29903 called @code{c-drive} on a machine @code{LOKI}, the following command will
29909 $ path \\loki\c-drive\gnat\bin;%path%`
29913 Be aware that every compilation using the network installation results in the
29914 transfer of large amounts of data across the network and will likely cause
29915 serious performance penalty.
29917 @node CONSOLE and WINDOWS subsystems,Temporary Files,Using a network installation of GNAT,Microsoft Windows Topics
29918 @anchor{gnat_ugn/platform_specific_information id12}@anchor{26c}@anchor{gnat_ugn/platform_specific_information console-and-windows-subsystems}@anchor{26d}
29919 @subsection CONSOLE and WINDOWS subsystems
29922 @geindex CONSOLE Subsystem
29924 @geindex WINDOWS Subsystem
29928 There are two main subsystems under Windows. The @cite{CONSOLE} subsystem
29929 (which is the default subsystem) will always create a console when
29930 launching the application. This is not something desirable when the
29931 application has a Windows GUI. To get rid of this console the
29932 application must be using the @cite{WINDOWS} subsystem. To do so
29933 the @emph{-mwindows} linker option must be specified.
29938 $ gnatmake winprog -largs -mwindows
29942 @node Temporary Files,Mixed-Language Programming on Windows,CONSOLE and WINDOWS subsystems,Microsoft Windows Topics
29943 @anchor{gnat_ugn/platform_specific_information id13}@anchor{26e}@anchor{gnat_ugn/platform_specific_information temporary-files}@anchor{26f}
29944 @subsection Temporary Files
29947 @geindex Temporary files
29949 It is possible to control where temporary files gets created by setting
29952 @geindex environment variable; TMP
29953 @code{TMP} environment variable. The file will be created:
29959 Under the directory pointed to by the
29961 @geindex environment variable; TMP
29962 @code{TMP} environment variable if
29963 this directory exists.
29966 Under @code{c:\temp}, if the
29968 @geindex environment variable; TMP
29969 @code{TMP} environment variable is not
29970 set (or not pointing to a directory) and if this directory exists.
29973 Under the current working directory otherwise.
29976 This allows you to determine exactly where the temporary
29977 file will be created. This is particularly useful in networked
29978 environments where you may not have write access to some
29981 @node Mixed-Language Programming on Windows,,Temporary Files,Microsoft Windows Topics
29982 @anchor{gnat_ugn/platform_specific_information mixed-language-programming-on-windows}@anchor{270}@anchor{gnat_ugn/platform_specific_information id14}@anchor{271}
29983 @subsection Mixed-Language Programming on Windows
29986 Developing pure Ada applications on Windows is no different than on
29987 other GNAT-supported platforms. However, when developing or porting an
29988 application that contains a mix of Ada and C/C++, the choice of your
29989 Windows C/C++ development environment conditions your overall
29990 interoperability strategy.
29992 If you use @emph{gcc} or Microsoft C to compile the non-Ada part of
29993 your application, there are no Windows-specific restrictions that
29994 affect the overall interoperability with your Ada code. If you do want
29995 to use the Microsoft tools for your C++ code, you have two choices:
30001 Encapsulate your C++ code in a DLL to be linked with your Ada
30002 application. In this case, use the Microsoft or whatever environment to
30003 build the DLL and use GNAT to build your executable
30004 (@ref{272,,Using DLLs with GNAT}).
30007 Or you can encapsulate your Ada code in a DLL to be linked with the
30008 other part of your application. In this case, use GNAT to build the DLL
30009 (@ref{273,,Building DLLs with GNAT Project files}) and use the Microsoft
30010 or whatever environment to build your executable.
30013 In addition to the description about C main in
30014 @ref{46,,Mixed Language Programming} section, if the C main uses a
30015 stand-alone library it is required on x86-windows to
30016 setup the SEH context. For this the C main must looks like this:
30022 extern void adainit (void);
30023 extern void adafinal (void);
30024 extern void __gnat_initialize(void*);
30025 extern void call_to_ada (void);
30027 int main (int argc, char *argv[])
30031 /* Initialize the SEH context */
30032 __gnat_initialize (&SEH);
30036 /* Then call Ada services in the stand-alone library */
30045 Note that this is not needed on x86_64-windows where the Windows
30046 native SEH support is used.
30049 * Windows Calling Conventions::
30050 * Introduction to Dynamic Link Libraries (DLLs): Introduction to Dynamic Link Libraries DLLs.
30051 * Using DLLs with GNAT::
30052 * Building DLLs with GNAT Project files::
30053 * Building DLLs with GNAT::
30054 * Building DLLs with gnatdll::
30055 * Ada DLLs and Finalization::
30056 * Creating a Spec for Ada DLLs::
30057 * GNAT and Windows Resources::
30058 * Debugging a DLL::
30059 * Setting Stack Size from gnatlink::
30060 * Setting Heap Size from gnatlink::
30064 @node Windows Calling Conventions,Introduction to Dynamic Link Libraries DLLs,,Mixed-Language Programming on Windows
30065 @anchor{gnat_ugn/platform_specific_information windows-calling-conventions}@anchor{274}@anchor{gnat_ugn/platform_specific_information id15}@anchor{275}
30066 @subsubsection Windows Calling Conventions
30073 This section pertain only to Win32. On Win64 there is a single native
30074 calling convention. All convention specifiers are ignored on this
30077 When a subprogram @cite{F} (caller) calls a subprogram @cite{G}
30078 (callee), there are several ways to push @cite{G}'s parameters on the
30079 stack and there are several possible scenarios to clean up the stack
30080 upon @cite{G}'s return. A calling convention is an agreed upon software
30081 protocol whereby the responsibilities between the caller (@cite{F}) and
30082 the callee (@cite{G}) are clearly defined. Several calling conventions
30083 are available for Windows:
30089 @cite{C} (Microsoft defined)
30092 @cite{Stdcall} (Microsoft defined)
30095 @cite{Win32} (GNAT specific)
30098 @cite{DLL} (GNAT specific)
30102 * C Calling Convention::
30103 * Stdcall Calling Convention::
30104 * Win32 Calling Convention::
30105 * DLL Calling Convention::
30109 @node C Calling Convention,Stdcall Calling Convention,,Windows Calling Conventions
30110 @anchor{gnat_ugn/platform_specific_information c-calling-convention}@anchor{276}@anchor{gnat_ugn/platform_specific_information id16}@anchor{277}
30111 @subsubsection @cite{C} Calling Convention
30114 This is the default calling convention used when interfacing to C/C++
30115 routines compiled with either @emph{gcc} or Microsoft Visual C++.
30117 In the @cite{C} calling convention subprogram parameters are pushed on the
30118 stack by the caller from right to left. The caller itself is in charge of
30119 cleaning up the stack after the call. In addition, the name of a routine
30120 with @cite{C} calling convention is mangled by adding a leading underscore.
30122 The name to use on the Ada side when importing (or exporting) a routine
30123 with @cite{C} calling convention is the name of the routine. For
30124 instance the C function:
30129 int get_val (long);
30133 should be imported from Ada as follows:
30138 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30139 pragma Import (C, Get_Val, External_Name => "get_val");
30143 Note that in this particular case the @cite{External_Name} parameter could
30144 have been omitted since, when missing, this parameter is taken to be the
30145 name of the Ada entity in lower case. When the @cite{Link_Name} parameter
30146 is missing, as in the above example, this parameter is set to be the
30147 @cite{External_Name} with a leading underscore.
30149 When importing a variable defined in C, you should always use the @cite{C}
30150 calling convention unless the object containing the variable is part of a
30151 DLL (in which case you should use the @cite{Stdcall} calling
30152 convention, @ref{278,,Stdcall Calling Convention}).
30154 @node Stdcall Calling Convention,Win32 Calling Convention,C Calling Convention,Windows Calling Conventions
30155 @anchor{gnat_ugn/platform_specific_information stdcall-calling-convention}@anchor{278}@anchor{gnat_ugn/platform_specific_information id17}@anchor{279}
30156 @subsubsection @cite{Stdcall} Calling Convention
30159 This convention, which was the calling convention used for Pascal
30160 programs, is used by Microsoft for all the routines in the Win32 API for
30161 efficiency reasons. It must be used to import any routine for which this
30162 convention was specified.
30164 In the @cite{Stdcall} calling convention subprogram parameters are pushed
30165 on the stack by the caller from right to left. The callee (and not the
30166 caller) is in charge of cleaning the stack on routine exit. In addition,
30167 the name of a routine with @cite{Stdcall} calling convention is mangled by
30168 adding a leading underscore (as for the @cite{C} calling convention) and a
30169 trailing @code{@@@emph{nn}}, where @cite{nn} is the overall size (in
30170 bytes) of the parameters passed to the routine.
30172 The name to use on the Ada side when importing a C routine with a
30173 @cite{Stdcall} calling convention is the name of the C routine. The leading
30174 underscore and trailing @code{@@@emph{nn}} are added automatically by
30175 the compiler. For instance the Win32 function:
30180 APIENTRY int get_val (long);
30184 should be imported from Ada as follows:
30189 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30190 pragma Import (Stdcall, Get_Val);
30191 -- On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
30195 As for the @cite{C} calling convention, when the @cite{External_Name}
30196 parameter is missing, it is taken to be the name of the Ada entity in lower
30197 case. If instead of writing the above import pragma you write:
30202 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30203 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
30207 then the imported routine is @cite{_retrieve_val@@4}. However, if instead
30208 of specifying the @cite{External_Name} parameter you specify the
30209 @cite{Link_Name} as in the following example:
30214 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30215 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
30219 then the imported routine is @cite{retrieve_val}, that is, there is no
30220 decoration at all. No leading underscore and no Stdcall suffix
30221 @code{@@@emph{nn}}.
30223 This is especially important as in some special cases a DLL's entry
30224 point name lacks a trailing @code{@@@emph{nn}} while the exported
30225 name generated for a call has it.
30227 It is also possible to import variables defined in a DLL by using an
30228 import pragma for a variable. As an example, if a DLL contains a
30229 variable defined as:
30238 then, to access this variable from Ada you should write:
30243 My_Var : Interfaces.C.int;
30244 pragma Import (Stdcall, My_Var);
30248 Note that to ease building cross-platform bindings this convention
30249 will be handled as a @cite{C} calling convention on non-Windows platforms.
30251 @node Win32 Calling Convention,DLL Calling Convention,Stdcall Calling Convention,Windows Calling Conventions
30252 @anchor{gnat_ugn/platform_specific_information id18}@anchor{27a}@anchor{gnat_ugn/platform_specific_information win32-calling-convention}@anchor{27b}
30253 @subsubsection @cite{Win32} Calling Convention
30256 This convention, which is GNAT-specific is fully equivalent to the
30257 @cite{Stdcall} calling convention described above.
30259 @node DLL Calling Convention,,Win32 Calling Convention,Windows Calling Conventions
30260 @anchor{gnat_ugn/platform_specific_information id19}@anchor{27c}@anchor{gnat_ugn/platform_specific_information dll-calling-convention}@anchor{27d}
30261 @subsubsection @cite{DLL} Calling Convention
30264 This convention, which is GNAT-specific is fully equivalent to the
30265 @cite{Stdcall} calling convention described above.
30267 @node Introduction to Dynamic Link Libraries DLLs,Using DLLs with GNAT,Windows Calling Conventions,Mixed-Language Programming on Windows
30268 @anchor{gnat_ugn/platform_specific_information id20}@anchor{27e}@anchor{gnat_ugn/platform_specific_information introduction-to-dynamic-link-libraries-dlls}@anchor{27f}
30269 @subsubsection Introduction to Dynamic Link Libraries (DLLs)
30274 A Dynamically Linked Library (DLL) is a library that can be shared by
30275 several applications running under Windows. A DLL can contain any number of
30276 routines and variables.
30278 One advantage of DLLs is that you can change and enhance them without
30279 forcing all the applications that depend on them to be relinked or
30280 recompiled. However, you should be aware than all calls to DLL routines are
30281 slower since, as you will understand below, such calls are indirect.
30283 To illustrate the remainder of this section, suppose that an application
30284 wants to use the services of a DLL @code{API.dll}. To use the services
30285 provided by @code{API.dll} you must statically link against the DLL or
30286 an import library which contains a jump table with an entry for each
30287 routine and variable exported by the DLL. In the Microsoft world this
30288 import library is called @code{API.lib}. When using GNAT this import
30289 library is called either @code{libAPI.dll.a}, @code{libapi.dll.a},
30290 @code{libAPI.a} or @code{libapi.a} (names are case insensitive).
30292 After you have linked your application with the DLL or the import library
30293 and you run your application, here is what happens:
30299 Your application is loaded into memory.
30302 The DLL @code{API.dll} is mapped into the address space of your
30303 application. This means that:
30309 The DLL will use the stack of the calling thread.
30312 The DLL will use the virtual address space of the calling process.
30315 The DLL will allocate memory from the virtual address space of the calling
30319 Handles (pointers) can be safely exchanged between routines in the DLL
30320 routines and routines in the application using the DLL.
30324 The entries in the jump table (from the import library @code{libAPI.dll.a}
30325 or @code{API.lib} or automatically created when linking against a DLL)
30326 which is part of your application are initialized with the addresses
30327 of the routines and variables in @code{API.dll}.
30330 If present in @code{API.dll}, routines @cite{DllMain} or
30331 @cite{DllMainCRTStartup} are invoked. These routines typically contain
30332 the initialization code needed for the well-being of the routines and
30333 variables exported by the DLL.
30336 There is an additional point which is worth mentioning. In the Windows
30337 world there are two kind of DLLs: relocatable and non-relocatable
30338 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
30339 in the target application address space. If the addresses of two
30340 non-relocatable DLLs overlap and these happen to be used by the same
30341 application, a conflict will occur and the application will run
30342 incorrectly. Hence, when possible, it is always preferable to use and
30343 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
30344 supported by GNAT. Note that the @emph{-s} linker option (see GNU Linker
30345 User's Guide) removes the debugging symbols from the DLL but the DLL can
30346 still be relocated.
30348 As a side note, an interesting difference between Microsoft DLLs and
30349 Unix shared libraries, is the fact that on most Unix systems all public
30350 routines are exported by default in a Unix shared library, while under
30351 Windows it is possible (but not required) to list exported routines in
30352 a definition file (see @ref{280,,The Definition File}).
30354 @node Using DLLs with GNAT,Building DLLs with GNAT Project files,Introduction to Dynamic Link Libraries DLLs,Mixed-Language Programming on Windows
30355 @anchor{gnat_ugn/platform_specific_information id21}@anchor{281}@anchor{gnat_ugn/platform_specific_information using-dlls-with-gnat}@anchor{272}
30356 @subsubsection Using DLLs with GNAT
30359 To use the services of a DLL, say @code{API.dll}, in your Ada application
30366 The Ada spec for the routines and/or variables you want to access in
30367 @code{API.dll}. If not available this Ada spec must be built from the C/C++
30368 header files provided with the DLL.
30371 The import library (@code{libAPI.dll.a} or @code{API.lib}). As previously
30372 mentioned an import library is a statically linked library containing the
30373 import table which will be filled at load time to point to the actual
30374 @code{API.dll} routines. Sometimes you don't have an import library for the
30375 DLL you want to use. The following sections will explain how to build
30376 one. Note that this is optional.
30379 The actual DLL, @code{API.dll}.
30382 Once you have all the above, to compile an Ada application that uses the
30383 services of @code{API.dll} and whose main subprogram is @cite{My_Ada_App},
30384 you simply issue the command
30389 $ gnatmake my_ada_app -largs -lAPI
30393 The argument @emph{-largs -lAPI} at the end of the @emph{gnatmake} command
30394 tells the GNAT linker to look for an import library. The linker will
30395 look for a library name in this specific order:
30401 @code{libAPI.dll.a}
30419 The first three are the GNU style import libraries. The third is the
30420 Microsoft style import libraries. The last two are the actual DLL names.
30422 Note that if the Ada package spec for @code{API.dll} contains the
30428 pragma Linker_Options ("-lAPI");
30432 you do not have to add @emph{-largs -lAPI} at the end of the
30433 @emph{gnatmake} command.
30435 If any one of the items above is missing you will have to create it
30436 yourself. The following sections explain how to do so using as an
30437 example a fictitious DLL called @code{API.dll}.
30440 * Creating an Ada Spec for the DLL Services::
30441 * Creating an Import Library::
30445 @node Creating an Ada Spec for the DLL Services,Creating an Import Library,,Using DLLs with GNAT
30446 @anchor{gnat_ugn/platform_specific_information creating-an-ada-spec-for-the-dll-services}@anchor{282}@anchor{gnat_ugn/platform_specific_information id22}@anchor{283}
30447 @subsubsection Creating an Ada Spec for the DLL Services
30450 A DLL typically comes with a C/C++ header file which provides the
30451 definitions of the routines and variables exported by the DLL. The Ada
30452 equivalent of this header file is a package spec that contains definitions
30453 for the imported entities. If the DLL you intend to use does not come with
30454 an Ada spec you have to generate one such spec yourself. For example if
30455 the header file of @code{API.dll} is a file @code{api.h} containing the
30456 following two definitions:
30466 then the equivalent Ada spec could be:
30471 with Interfaces.C.Strings;
30476 function Get (Str : C.Strings.Chars_Ptr) return C.int;
30479 pragma Import (C, Get);
30480 pragma Import (DLL, Some_Var);
30485 @node Creating an Import Library,,Creating an Ada Spec for the DLL Services,Using DLLs with GNAT
30486 @anchor{gnat_ugn/platform_specific_information id23}@anchor{284}@anchor{gnat_ugn/platform_specific_information creating-an-import-library}@anchor{285}
30487 @subsubsection Creating an Import Library
30490 @geindex Import library
30492 If a Microsoft-style import library @code{API.lib} or a GNAT-style
30493 import library @code{libAPI.dll.a} or @code{libAPI.a} is available
30494 with @code{API.dll} you can skip this section. You can also skip this
30495 section if @code{API.dll} or @code{libAPI.dll} is built with GNU tools
30496 as in this case it is possible to link directly against the
30497 DLL. Otherwise read on.
30499 @geindex Definition file
30500 @anchor{gnat_ugn/platform_specific_information the-definition-file}@anchor{280}
30501 @subsubheading The Definition File
30504 As previously mentioned, and unlike Unix systems, the list of symbols
30505 that are exported from a DLL must be provided explicitly in Windows.
30506 The main goal of a definition file is precisely that: list the symbols
30507 exported by a DLL. A definition file (usually a file with a @cite{.def}
30508 suffix) has the following structure:
30514 [DESCRIPTION `string`]
30525 @item @emph{LIBRARY `name`}
30527 This section, which is optional, gives the name of the DLL.
30529 @item @emph{DESCRIPTION `string`}
30531 This section, which is optional, gives a description string that will be
30532 embedded in the import library.
30534 @item @emph{EXPORTS}
30536 This section gives the list of exported symbols (procedures, functions or
30537 variables). For instance in the case of @code{API.dll} the @cite{EXPORTS}
30538 section of @code{API.def} looks like:
30547 Note that you must specify the correct suffix (@code{@@@emph{nn}})
30548 (see @ref{274,,Windows Calling Conventions}) for a Stdcall
30549 calling convention function in the exported symbols list.
30551 There can actually be other sections in a definition file, but these
30552 sections are not relevant to the discussion at hand.
30554 @subsubheading GNAT-Style Import Library
30556 @anchor{gnat_ugn/platform_specific_information gnat-style-import-library}@anchor{286}
30557 To create a static import library from @code{API.dll} with the GNAT tools
30558 you should proceed as follows:
30564 Create the definition file @code{API.def}
30565 (see @ref{280,,The Definition File}).
30566 For that use the @cite{dll2def} tool as follows:
30569 $ dll2def API.dll > API.def
30572 @cite{dll2def} is a very simple tool: it takes as input a DLL and prints
30573 to standard output the list of entry points in the DLL. Note that if
30574 some routines in the DLL have the @cite{Stdcall} convention
30575 (@ref{274,,Windows Calling Conventions}) with stripped @code{@@@emph{nn}}
30576 suffix then you'll have to edit @code{api.def} to add it, and specify
30577 @emph{-k} to @emph{gnatdll} when creating the import library.
30579 Here are some hints to find the right @code{@@@emph{nn}} suffix.
30585 If you have the Microsoft import library (.lib), it is possible to get
30586 the right symbols by using Microsoft @cite{dumpbin} tool (see the
30587 corresponding Microsoft documentation for further details).
30590 $ dumpbin /exports api.lib
30594 If you have a message about a missing symbol at link time the compiler
30595 tells you what symbol is expected. You just have to go back to the
30596 definition file and add the right suffix.
30600 Build the import library @cite{libAPI.dll.a}, using @cite{gnatdll}
30601 (see @ref{287,,Using gnatdll}) as follows:
30604 $ gnatdll -e API.def -d API.dll
30607 @cite{gnatdll} takes as input a definition file @code{API.def} and the
30608 name of the DLL containing the services listed in the definition file
30609 @code{API.dll}. The name of the static import library generated is
30610 computed from the name of the definition file as follows: if the
30611 definition file name is @cite{xyz`}.def`, the import library name will
30612 be @cite{lib`@w{`}xyz`}.a`. Note that in the previous example option
30613 @emph{-e} could have been removed because the name of the definition
30614 file (before the '@cite{.def}' suffix) is the same as the name of the
30615 DLL (@ref{287,,Using gnatdll} for more information about @cite{gnatdll}).
30618 @subsubheading Microsoft-Style Import Library
30621 With GNAT you can either use a GNAT-style or Microsoft-style import
30622 library. A Microsoft import library is needed only if you plan to make an
30623 Ada DLL available to applications developed with Microsoft
30624 tools (@ref{270,,Mixed-Language Programming on Windows}).
30626 To create a Microsoft-style import library for @code{API.dll} you
30627 should proceed as follows:
30633 Create the definition file @code{API.def} from the DLL. For this use either
30634 the @cite{dll2def} tool as described above or the Microsoft @cite{dumpbin}
30635 tool (see the corresponding Microsoft documentation for further details).
30638 Build the actual import library using Microsoft's @cite{lib} utility:
30641 $ lib -machine:IX86 -def:API.def -out:API.lib
30644 If you use the above command the definition file @code{API.def} must
30645 contain a line giving the name of the DLL:
30651 See the Microsoft documentation for further details about the usage of
30655 @node Building DLLs with GNAT Project files,Building DLLs with GNAT,Using DLLs with GNAT,Mixed-Language Programming on Windows
30656 @anchor{gnat_ugn/platform_specific_information id24}@anchor{288}@anchor{gnat_ugn/platform_specific_information building-dlls-with-gnat-project-files}@anchor{273}
30657 @subsubsection Building DLLs with GNAT Project files
30663 There is nothing specific to Windows in the build process.
30664 @ref{8a,,Library Projects}.
30666 Due to a system limitation, it is not possible under Windows to create threads
30667 when inside the @cite{DllMain} routine which is used for auto-initialization
30668 of shared libraries, so it is not possible to have library level tasks in SALs.
30670 @node Building DLLs with GNAT,Building DLLs with gnatdll,Building DLLs with GNAT Project files,Mixed-Language Programming on Windows
30671 @anchor{gnat_ugn/platform_specific_information building-dlls-with-gnat}@anchor{289}@anchor{gnat_ugn/platform_specific_information id25}@anchor{28a}
30672 @subsubsection Building DLLs with GNAT
30678 This section explain how to build DLLs using the GNAT built-in DLL
30679 support. With the following procedure it is straight forward to build
30680 and use DLLs with GNAT.
30686 Building object files.
30687 The first step is to build all objects files that are to be included
30688 into the DLL. This is done by using the standard @emph{gnatmake} tool.
30692 To build the DLL you must use @emph{gcc}'s @emph{-shared} and
30693 @emph{-shared-libgcc} options. It is quite simple to use this method:
30696 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o ...
30699 It is important to note that in this case all symbols found in the
30700 object files are automatically exported. It is possible to restrict
30701 the set of symbols to export by passing to @emph{gcc} a definition
30702 file (see @ref{280,,The Definition File}).
30706 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o ...
30709 If you use a definition file you must export the elaboration procedures
30710 for every package that required one. Elaboration procedures are named
30711 using the package name followed by "_E".
30714 Preparing DLL to be used.
30715 For the DLL to be used by client programs the bodies must be hidden
30716 from it and the .ali set with read-only attribute. This is very important
30717 otherwise GNAT will recompile all packages and will not actually use
30718 the code in the DLL. For example:
30722 $ copy *.ads *.ali api.dll apilib
30723 $ attrib +R apilib\\*.ali
30727 At this point it is possible to use the DLL by directly linking
30728 against it. Note that you must use the GNAT shared runtime when using
30729 GNAT shared libraries. This is achieved by using @emph{-shared} binder's
30735 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
30739 @node Building DLLs with gnatdll,Ada DLLs and Finalization,Building DLLs with GNAT,Mixed-Language Programming on Windows
30740 @anchor{gnat_ugn/platform_specific_information building-dlls-with-gnatdll}@anchor{28b}@anchor{gnat_ugn/platform_specific_information id26}@anchor{28c}
30741 @subsubsection Building DLLs with gnatdll
30747 Note that it is preferred to use GNAT Project files
30748 (@ref{273,,Building DLLs with GNAT Project files}) or the built-in GNAT
30749 DLL support (@ref{289,,Building DLLs with GNAT}) or to build DLLs.
30751 This section explains how to build DLLs containing Ada code using
30752 @cite{gnatdll}. These DLLs will be referred to as Ada DLLs in the
30753 remainder of this section.
30755 The steps required to build an Ada DLL that is to be used by Ada as well as
30756 non-Ada applications are as follows:
30762 You need to mark each Ada @emph{entity} exported by the DLL with a @cite{C} or
30763 @cite{Stdcall} calling convention to avoid any Ada name mangling for the
30764 entities exported by the DLL
30765 (see @ref{28d,,Exporting Ada Entities}). You can
30766 skip this step if you plan to use the Ada DLL only from Ada applications.
30769 Your Ada code must export an initialization routine which calls the routine
30770 @cite{adainit} generated by @emph{gnatbind} to perform the elaboration of
30771 the Ada code in the DLL (@ref{28e,,Ada DLLs and Elaboration}). The initialization
30772 routine exported by the Ada DLL must be invoked by the clients of the DLL
30773 to initialize the DLL.
30776 When useful, the DLL should also export a finalization routine which calls
30777 routine @cite{adafinal} generated by @emph{gnatbind} to perform the
30778 finalization of the Ada code in the DLL (@ref{28f,,Ada DLLs and Finalization}).
30779 The finalization routine exported by the Ada DLL must be invoked by the
30780 clients of the DLL when the DLL services are no further needed.
30783 You must provide a spec for the services exported by the Ada DLL in each
30784 of the programming languages to which you plan to make the DLL available.
30787 You must provide a definition file listing the exported entities
30788 (@ref{280,,The Definition File}).
30791 Finally you must use @cite{gnatdll} to produce the DLL and the import
30792 library (@ref{287,,Using gnatdll}).
30795 Note that a relocatable DLL stripped using the @cite{strip}
30796 binutils tool will not be relocatable anymore. To build a DLL without
30797 debug information pass @cite{-largs -s} to @cite{gnatdll}. This
30798 restriction does not apply to a DLL built using a Library Project.
30799 See @ref{8a,,Library Projects}.
30801 @c Limitations_When_Using_Ada_DLLs_from Ada:
30804 * Limitations When Using Ada DLLs from Ada::
30805 * Exporting Ada Entities::
30806 * Ada DLLs and Elaboration::
30810 @node Limitations When Using Ada DLLs from Ada,Exporting Ada Entities,,Building DLLs with gnatdll
30811 @anchor{gnat_ugn/platform_specific_information limitations-when-using-ada-dlls-from-ada}@anchor{290}
30812 @subsubsection Limitations When Using Ada DLLs from Ada
30815 When using Ada DLLs from Ada applications there is a limitation users
30816 should be aware of. Because on Windows the GNAT run time is not in a DLL of
30817 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
30818 each Ada DLL includes the services of the GNAT run time that are necessary
30819 to the Ada code inside the DLL. As a result, when an Ada program uses an
30820 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
30821 one in the main program.
30823 It is therefore not possible to exchange GNAT run-time objects between the
30824 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
30825 handles (e.g., @cite{Text_IO.File_Type}), tasks types, protected objects
30828 It is completely safe to exchange plain elementary, array or record types,
30829 Windows object handles, etc.
30831 @node Exporting Ada Entities,Ada DLLs and Elaboration,Limitations When Using Ada DLLs from Ada,Building DLLs with gnatdll
30832 @anchor{gnat_ugn/platform_specific_information exporting-ada-entities}@anchor{28d}@anchor{gnat_ugn/platform_specific_information id27}@anchor{291}
30833 @subsubsection Exporting Ada Entities
30836 @geindex Export table
30838 Building a DLL is a way to encapsulate a set of services usable from any
30839 application. As a result, the Ada entities exported by a DLL should be
30840 exported with the @cite{C} or @cite{Stdcall} calling conventions to avoid
30841 any Ada name mangling. As an example here is an Ada package
30842 @cite{API}, spec and body, exporting two procedures, a function, and a
30848 with Interfaces.C; use Interfaces;
30850 Count : C.int := 0;
30851 function Factorial (Val : C.int) return C.int;
30853 procedure Initialize_API;
30854 procedure Finalize_API;
30855 -- Initialization & Finalization routines. More in the next section.
30857 pragma Export (C, Initialize_API);
30858 pragma Export (C, Finalize_API);
30859 pragma Export (C, Count);
30860 pragma Export (C, Factorial);
30865 package body API is
30866 function Factorial (Val : C.int) return C.int is
30869 Count := Count + 1;
30870 for K in 1 .. Val loop
30876 procedure Initialize_API is
30878 pragma Import (C, Adainit);
30881 end Initialize_API;
30883 procedure Finalize_API is
30884 procedure Adafinal;
30885 pragma Import (C, Adafinal);
30893 If the Ada DLL you are building will only be used by Ada applications
30894 you do not have to export Ada entities with a @cite{C} or @cite{Stdcall}
30895 convention. As an example, the previous package could be written as
30902 Count : Integer := 0;
30903 function Factorial (Val : Integer) return Integer;
30905 procedure Initialize_API;
30906 procedure Finalize_API;
30907 -- Initialization and Finalization routines.
30912 package body API is
30913 function Factorial (Val : Integer) return Integer is
30914 Fact : Integer := 1;
30916 Count := Count + 1;
30917 for K in 1 .. Val loop
30924 -- The remainder of this package body is unchanged.
30929 Note that if you do not export the Ada entities with a @cite{C} or
30930 @cite{Stdcall} convention you will have to provide the mangled Ada names
30931 in the definition file of the Ada DLL
30932 (@ref{292,,Creating the Definition File}).
30934 @node Ada DLLs and Elaboration,,Exporting Ada Entities,Building DLLs with gnatdll
30935 @anchor{gnat_ugn/platform_specific_information ada-dlls-and-elaboration}@anchor{28e}@anchor{gnat_ugn/platform_specific_information id28}@anchor{293}
30936 @subsubsection Ada DLLs and Elaboration
30939 @geindex DLLs and elaboration
30941 The DLL that you are building contains your Ada code as well as all the
30942 routines in the Ada library that are needed by it. The first thing a
30943 user of your DLL must do is elaborate the Ada code
30944 (@ref{11,,Elaboration Order Handling in GNAT}).
30946 To achieve this you must export an initialization routine
30947 (@cite{Initialize_API} in the previous example), which must be invoked
30948 before using any of the DLL services. This elaboration routine must call
30949 the Ada elaboration routine @cite{adainit} generated by the GNAT binder
30950 (@ref{ba,,Binding with Non-Ada Main Programs}). See the body of
30951 @cite{Initialize_Api} for an example. Note that the GNAT binder is
30952 automatically invoked during the DLL build process by the @cite{gnatdll}
30953 tool (@ref{287,,Using gnatdll}).
30955 When a DLL is loaded, Windows systematically invokes a routine called
30956 @cite{DllMain}. It would therefore be possible to call @cite{adainit}
30957 directly from @cite{DllMain} without having to provide an explicit
30958 initialization routine. Unfortunately, it is not possible to call
30959 @cite{adainit} from the @cite{DllMain} if your program has library level
30960 tasks because access to the @cite{DllMain} entry point is serialized by
30961 the system (that is, only a single thread can execute 'through' it at a
30962 time), which means that the GNAT run time will deadlock waiting for the
30963 newly created task to complete its initialization.
30965 @node Ada DLLs and Finalization,Creating a Spec for Ada DLLs,Building DLLs with gnatdll,Mixed-Language Programming on Windows
30966 @anchor{gnat_ugn/platform_specific_information id29}@anchor{294}@anchor{gnat_ugn/platform_specific_information ada-dlls-and-finalization}@anchor{28f}
30967 @subsubsection Ada DLLs and Finalization
30970 @geindex DLLs and finalization
30972 When the services of an Ada DLL are no longer needed, the client code should
30973 invoke the DLL finalization routine, if available. The DLL finalization
30974 routine is in charge of releasing all resources acquired by the DLL. In the
30975 case of the Ada code contained in the DLL, this is achieved by calling
30976 routine @cite{adafinal} generated by the GNAT binder
30977 (@ref{ba,,Binding with Non-Ada Main Programs}).
30978 See the body of @cite{Finalize_Api} for an
30979 example. As already pointed out the GNAT binder is automatically invoked
30980 during the DLL build process by the @cite{gnatdll} tool
30981 (@ref{287,,Using gnatdll}).
30983 @node Creating a Spec for Ada DLLs,GNAT and Windows Resources,Ada DLLs and Finalization,Mixed-Language Programming on Windows
30984 @anchor{gnat_ugn/platform_specific_information id30}@anchor{295}@anchor{gnat_ugn/platform_specific_information creating-a-spec-for-ada-dlls}@anchor{296}
30985 @subsubsection Creating a Spec for Ada DLLs
30988 To use the services exported by the Ada DLL from another programming
30989 language (e.g., C), you have to translate the specs of the exported Ada
30990 entities in that language. For instance in the case of @cite{API.dll},
30991 the corresponding C header file could look like:
30996 extern int *_imp__count;
30997 #define count (*_imp__count)
30998 int factorial (int);
31002 It is important to understand that when building an Ada DLL to be used by
31003 other Ada applications, you need two different specs for the packages
31004 contained in the DLL: one for building the DLL and the other for using
31005 the DLL. This is because the @cite{DLL} calling convention is needed to
31006 use a variable defined in a DLL, but when building the DLL, the variable
31007 must have either the @cite{Ada} or @cite{C} calling convention. As an
31008 example consider a DLL comprising the following package @cite{API}:
31014 Count : Integer := 0;
31016 -- Remainder of the package omitted.
31021 After producing a DLL containing package @cite{API}, the spec that
31022 must be used to import @cite{API.Count} from Ada code outside of the
31030 pragma Import (DLL, Count);
31036 * Creating the Definition File::
31041 @node Creating the Definition File,Using gnatdll,,Creating a Spec for Ada DLLs
31042 @anchor{gnat_ugn/platform_specific_information creating-the-definition-file}@anchor{292}@anchor{gnat_ugn/platform_specific_information id31}@anchor{297}
31043 @subsubsection Creating the Definition File
31046 The definition file is the last file needed to build the DLL. It lists
31047 the exported symbols. As an example, the definition file for a DLL
31048 containing only package @cite{API} (where all the entities are exported
31049 with a @cite{C} calling convention) is:
31062 If the @cite{C} calling convention is missing from package @cite{API},
31063 then the definition file contains the mangled Ada names of the above
31064 entities, which in this case are:
31073 api__initialize_api
31077 @node Using gnatdll,,Creating the Definition File,Creating a Spec for Ada DLLs
31078 @anchor{gnat_ugn/platform_specific_information using-gnatdll}@anchor{287}@anchor{gnat_ugn/platform_specific_information id32}@anchor{298}
31079 @subsubsection Using @cite{gnatdll}
31084 @cite{gnatdll} is a tool to automate the DLL build process once all the Ada
31085 and non-Ada sources that make up your DLL have been compiled.
31086 @cite{gnatdll} is actually in charge of two distinct tasks: build the
31087 static import library for the DLL and the actual DLL. The form of the
31088 @cite{gnatdll} command is
31093 $ gnatdll [`switches`] `list-of-files` [-largs `opts`]
31097 where @cite{list-of-files} is a list of ALI and object files. The object
31098 file list must be the exact list of objects corresponding to the non-Ada
31099 sources whose services are to be included in the DLL. The ALI file list
31100 must be the exact list of ALI files for the corresponding Ada sources
31101 whose services are to be included in the DLL. If @cite{list-of-files} is
31102 missing, only the static import library is generated.
31104 You may specify any of the following switches to @cite{gnatdll}:
31108 @geindex -a (gnatdll)
31114 @item @code{-a[@emph{address}]}
31116 Build a non-relocatable DLL at @cite{address}. If @cite{address} is not
31117 specified the default address @cite{0x11000000} will be used. By default,
31118 when this switch is missing, @cite{gnatdll} builds relocatable DLL. We
31119 advise the reader to build relocatable DLL.
31121 @geindex -b (gnatdll)
31123 @item @code{-b @emph{address}}
31125 Set the relocatable DLL base address. By default the address is
31128 @geindex -bargs (gnatdll)
31130 @item @code{-bargs @emph{opts}}
31132 Binder options. Pass @cite{opts} to the binder.
31134 @geindex -d (gnatdll)
31136 @item @code{-d @emph{dllfile}}
31138 @cite{dllfile} is the name of the DLL. This switch must be present for
31139 @cite{gnatdll} to do anything. The name of the generated import library is
31140 obtained algorithmically from @cite{dllfile} as shown in the following
31141 example: if @cite{dllfile} is @cite{xyz.dll}, the import library name is
31142 @cite{libxyz.dll.a}. The name of the definition file to use (if not specified
31143 by option @emph{-e}) is obtained algorithmically from @cite{dllfile}
31144 as shown in the following example:
31145 if @cite{dllfile} is @cite{xyz.dll}, the definition
31146 file used is @cite{xyz.def}.
31148 @geindex -e (gnatdll)
31150 @item @code{-e @emph{deffile}}
31152 @cite{deffile} is the name of the definition file.
31154 @geindex -g (gnatdll)
31158 Generate debugging information. This information is stored in the object
31159 file and copied from there to the final DLL file by the linker,
31160 where it can be read by the debugger. You must use the
31161 @emph{-g} switch if you plan on using the debugger or the symbolic
31164 @geindex -h (gnatdll)
31168 Help mode. Displays @cite{gnatdll} switch usage information.
31170 @geindex -I (gnatdll)
31172 @item @code{-I@emph{dir}}
31174 Direct @cite{gnatdll} to search the @cite{dir} directory for source and
31175 object files needed to build the DLL.
31176 (@ref{8e,,Search Paths and the Run-Time Library (RTL)}).
31178 @geindex -k (gnatdll)
31182 Removes the @code{@@@emph{nn}} suffix from the import library's exported
31183 names, but keeps them for the link names. You must specify this
31184 option if you want to use a @cite{Stdcall} function in a DLL for which
31185 the @code{@@@emph{nn}} suffix has been removed. This is the case for most
31186 of the Windows NT DLL for example. This option has no effect when
31187 @emph{-n} option is specified.
31189 @geindex -l (gnatdll)
31191 @item @code{-l @emph{file}}
31193 The list of ALI and object files used to build the DLL are listed in
31194 @cite{file}, instead of being given in the command line. Each line in
31195 @cite{file} contains the name of an ALI or object file.
31197 @geindex -n (gnatdll)
31201 No Import. Do not create the import library.
31203 @geindex -q (gnatdll)
31207 Quiet mode. Do not display unnecessary messages.
31209 @geindex -v (gnatdll)
31213 Verbose mode. Display extra information.
31215 @geindex -largs (gnatdll)
31217 @item @code{-largs @emph{opts}}
31219 Linker options. Pass @cite{opts} to the linker.
31222 @subsubheading @cite{gnatdll} Example
31225 As an example the command to build a relocatable DLL from @code{api.adb}
31226 once @code{api.adb} has been compiled and @code{api.def} created is
31231 $ gnatdll -d api.dll api.ali
31235 The above command creates two files: @code{libapi.dll.a} (the import
31236 library) and @code{api.dll} (the actual DLL). If you want to create
31237 only the DLL, just type:
31242 $ gnatdll -d api.dll -n api.ali
31246 Alternatively if you want to create just the import library, type:
31251 $ gnatdll -d api.dll
31255 @subsubheading @cite{gnatdll} behind the Scenes
31258 This section details the steps involved in creating a DLL. @cite{gnatdll}
31259 does these steps for you. Unless you are interested in understanding what
31260 goes on behind the scenes, you should skip this section.
31262 We use the previous example of a DLL containing the Ada package @cite{API},
31263 to illustrate the steps necessary to build a DLL. The starting point is a
31264 set of objects that will make up the DLL and the corresponding ALI
31265 files. In the case of this example this means that @code{api.o} and
31266 @code{api.ali} are available. To build a relocatable DLL, @cite{gnatdll} does
31273 @cite{gnatdll} builds the base file (@code{api.base}). A base file gives
31274 the information necessary to generate relocation information for the
31279 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
31282 In addition to the base file, the @emph{gnatlink} command generates an
31283 output file @code{api.jnk} which can be discarded. The @emph{-mdll} switch
31284 asks @emph{gnatlink} to generate the routines @cite{DllMain} and
31285 @cite{DllMainCRTStartup} that are called by the Windows loader when the DLL
31286 is loaded into memory.
31289 @cite{gnatdll} uses @cite{dlltool} (see @ref{299,,Using dlltool}) to build the
31290 export table (@code{api.exp}). The export table contains the relocation
31291 information in a form which can be used during the final link to ensure
31292 that the Windows loader is able to place the DLL anywhere in memory.
31295 $ dlltool --dllname api.dll --def api.def --base-file api.base \\
31296 --output-exp api.exp
31300 @cite{gnatdll} builds the base file using the new export table. Note that
31301 @emph{gnatbind} must be called once again since the binder generated file
31302 has been deleted during the previous call to @emph{gnatlink}.
31306 $ gnatlink api -o api.jnk api.exp -mdll
31307 -Wl,--base-file,api.base
31311 @cite{gnatdll} builds the new export table using the new base file and
31312 generates the DLL import library @code{libAPI.dll.a}.
31315 $ dlltool --dllname api.dll --def api.def --base-file api.base \\
31316 --output-exp api.exp --output-lib libAPI.a
31320 Finally @cite{gnatdll} builds the relocatable DLL using the final export
31325 $ gnatlink api api.exp -o api.dll -mdll
31328 @anchor{gnat_ugn/platform_specific_information using-dlltool}@anchor{299}
31329 @subsubheading Using @cite{dlltool}
31332 @cite{dlltool} is the low-level tool used by @cite{gnatdll} to build
31333 DLLs and static import libraries. This section summarizes the most
31334 common @cite{dlltool} switches. The form of the @cite{dlltool} command
31340 $ dlltool [`switches`]
31344 @cite{dlltool} switches include:
31346 @geindex --base-file (dlltool)
31351 @item @code{--base-file @emph{basefile}}
31353 Read the base file @cite{basefile} generated by the linker. This switch
31354 is used to create a relocatable DLL.
31357 @geindex --def (dlltool)
31362 @item @code{--def @emph{deffile}}
31364 Read the definition file.
31367 @geindex --dllname (dlltool)
31372 @item @code{--dllname @emph{name}}
31374 Gives the name of the DLL. This switch is used to embed the name of the
31375 DLL in the static import library generated by @cite{dlltool} with switch
31376 @emph{--output-lib}.
31379 @geindex -k (dlltool)
31386 Kill @code{@@@emph{nn}} from exported names
31387 (@ref{274,,Windows Calling Conventions}
31388 for a discussion about @cite{Stdcall}-style symbols.
31391 @geindex --help (dlltool)
31396 @item @code{--help}
31398 Prints the @cite{dlltool} switches with a concise description.
31401 @geindex --output-exp (dlltool)
31406 @item @code{--output-exp @emph{exportfile}}
31408 Generate an export file @cite{exportfile}. The export file contains the
31409 export table (list of symbols in the DLL) and is used to create the DLL.
31412 @geindex --output-lib (dlltool)
31417 @item @code{--output-lib @emph{libfile}}
31419 Generate a static import library @cite{libfile}.
31422 @geindex -v (dlltool)
31432 @geindex --as (dlltool)
31437 @item @code{--as @emph{assembler-name}}
31439 Use @cite{assembler-name} as the assembler. The default is @cite{as}.
31442 @node GNAT and Windows Resources,Debugging a DLL,Creating a Spec for Ada DLLs,Mixed-Language Programming on Windows
31443 @anchor{gnat_ugn/platform_specific_information gnat-and-windows-resources}@anchor{29a}@anchor{gnat_ugn/platform_specific_information id33}@anchor{29b}
31444 @subsubsection GNAT and Windows Resources
31450 Resources are an easy way to add Windows specific objects to your
31451 application. The objects that can be added as resources include:
31481 version information
31484 For example, a version information resource can be defined as follow and
31485 embedded into an executable or DLL:
31487 A version information resource can be used to embed information into an
31488 executable or a DLL. These information can be viewed using the file properties
31489 from the Windows Explorer. Here is an example of a version information
31496 FILEVERSION 1,0,0,0
31497 PRODUCTVERSION 1,0,0,0
31499 BLOCK "StringFileInfo"
31503 VALUE "CompanyName", "My Company Name"
31504 VALUE "FileDescription", "My application"
31505 VALUE "FileVersion", "1.0"
31506 VALUE "InternalName", "my_app"
31507 VALUE "LegalCopyright", "My Name"
31508 VALUE "OriginalFilename", "my_app.exe"
31509 VALUE "ProductName", "My App"
31510 VALUE "ProductVersion", "1.0"
31514 BLOCK "VarFileInfo"
31516 VALUE "Translation", 0x809, 1252
31522 The value @cite{0809} (langID) is for the U.K English language and
31523 @cite{04E4} (charsetID), which is equal to @cite{1252} decimal, for
31526 This section explains how to build, compile and use resources. Note that this
31527 section does not cover all resource objects, for a complete description see
31528 the corresponding Microsoft documentation.
31531 * Building Resources::
31532 * Compiling Resources::
31533 * Using Resources::
31537 @node Building Resources,Compiling Resources,,GNAT and Windows Resources
31538 @anchor{gnat_ugn/platform_specific_information building-resources}@anchor{29c}@anchor{gnat_ugn/platform_specific_information id34}@anchor{29d}
31539 @subsubsection Building Resources
31545 A resource file is an ASCII file. By convention resource files have an
31546 @code{.rc} extension.
31547 The easiest way to build a resource file is to use Microsoft tools
31548 such as @cite{imagedit.exe} to build bitmaps, icons and cursors and
31549 @cite{dlgedit.exe} to build dialogs.
31550 It is always possible to build an @code{.rc} file yourself by writing a
31553 It is not our objective to explain how to write a resource file. A
31554 complete description of the resource script language can be found in the
31555 Microsoft documentation.
31557 @node Compiling Resources,Using Resources,Building Resources,GNAT and Windows Resources
31558 @anchor{gnat_ugn/platform_specific_information compiling-resources}@anchor{29e}@anchor{gnat_ugn/platform_specific_information id35}@anchor{29f}
31559 @subsubsection Compiling Resources
31569 This section describes how to build a GNAT-compatible (COFF) object file
31570 containing the resources. This is done using the Resource Compiler
31571 @cite{windres} as follows:
31576 $ windres -i myres.rc -o myres.o
31580 By default @cite{windres} will run @emph{gcc} to preprocess the @code{.rc}
31581 file. You can specify an alternate preprocessor (usually named
31582 @code{cpp.exe}) using the @cite{windres} @emph{--preprocessor}
31583 parameter. A list of all possible options may be obtained by entering
31584 the command @cite{windres} @emph{--help}.
31586 It is also possible to use the Microsoft resource compiler @cite{rc.exe}
31587 to produce a @code{.res} file (binary resource file). See the
31588 corresponding Microsoft documentation for further details. In this case
31589 you need to use @cite{windres} to translate the @code{.res} file to a
31590 GNAT-compatible object file as follows:
31595 $ windres -i myres.res -o myres.o
31599 @node Using Resources,,Compiling Resources,GNAT and Windows Resources
31600 @anchor{gnat_ugn/platform_specific_information id36}@anchor{2a0}@anchor{gnat_ugn/platform_specific_information using-resources}@anchor{2a1}
31601 @subsubsection Using Resources
31607 To include the resource file in your program just add the
31608 GNAT-compatible object file for the resource(s) to the linker
31609 arguments. With @emph{gnatmake} this is done by using the @emph{-largs}
31615 $ gnatmake myprog -largs myres.o
31619 @node Debugging a DLL,Setting Stack Size from gnatlink,GNAT and Windows Resources,Mixed-Language Programming on Windows
31620 @anchor{gnat_ugn/platform_specific_information id37}@anchor{2a2}@anchor{gnat_ugn/platform_specific_information debugging-a-dll}@anchor{2a3}
31621 @subsubsection Debugging a DLL
31624 @geindex DLL debugging
31626 Debugging a DLL is similar to debugging a standard program. But
31627 we have to deal with two different executable parts: the DLL and the
31628 program that uses it. We have the following four possibilities:
31634 The program and the DLL are built with @cite{GCC/GNAT}.
31637 The program is built with foreign tools and the DLL is built with
31641 The program is built with @cite{GCC/GNAT} and the DLL is built with
31645 In this section we address only cases one and two above.
31646 There is no point in trying to debug
31647 a DLL with @cite{GNU/GDB}, if there is no GDB-compatible debugging
31648 information in it. To do so you must use a debugger compatible with the
31649 tools suite used to build the DLL.
31652 * Program and DLL Both Built with GCC/GNAT::
31653 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
31657 @node Program and DLL Both Built with GCC/GNAT,Program Built with Foreign Tools and DLL Built with GCC/GNAT,,Debugging a DLL
31658 @anchor{gnat_ugn/platform_specific_information program-and-dll-both-built-with-gcc-gnat}@anchor{2a4}@anchor{gnat_ugn/platform_specific_information id38}@anchor{2a5}
31659 @subsubsection Program and DLL Both Built with GCC/GNAT
31662 This is the simplest case. Both the DLL and the program have @cite{GDB}
31663 compatible debugging information. It is then possible to break anywhere in
31664 the process. Let's suppose here that the main procedure is named
31665 @cite{ada_main} and that in the DLL there is an entry point named
31668 The DLL (@ref{27f,,Introduction to Dynamic Link Libraries (DLLs)}) and
31669 program must have been built with the debugging information (see GNAT -g
31670 switch). Here are the step-by-step instructions for debugging it:
31676 Launch @cite{GDB} on the main program.
31683 Start the program and stop at the beginning of the main procedure
31689 This step is required to be able to set a breakpoint inside the DLL. As long
31690 as the program is not run, the DLL is not loaded. This has the
31691 consequence that the DLL debugging information is also not loaded, so it is not
31692 possible to set a breakpoint in the DLL.
31695 Set a breakpoint inside the DLL
31698 (gdb) break ada_dll
31703 At this stage a breakpoint is set inside the DLL. From there on
31704 you can use the standard approach to debug the whole program
31705 (@ref{26,,Running and Debugging Ada Programs}).
31707 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT,,Program and DLL Both Built with GCC/GNAT,Debugging a DLL
31708 @anchor{gnat_ugn/platform_specific_information program-built-with-foreign-tools-and-dll-built-with-gcc-gnat}@anchor{2a6}@anchor{gnat_ugn/platform_specific_information id39}@anchor{2a7}
31709 @subsubsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
31712 In this case things are slightly more complex because it is not possible to
31713 start the main program and then break at the beginning to load the DLL and the
31714 associated DLL debugging information. It is not possible to break at the
31715 beginning of the program because there is no @cite{GDB} debugging information,
31716 and therefore there is no direct way of getting initial control. This
31717 section addresses this issue by describing some methods that can be used
31718 to break somewhere in the DLL to debug it.
31720 First suppose that the main procedure is named @cite{main} (this is for
31721 example some C code built with Microsoft Visual C) and that there is a
31722 DLL named @cite{test.dll} containing an Ada entry point named
31725 The DLL (see @ref{27f,,Introduction to Dynamic Link Libraries (DLLs)}) must have
31726 been built with debugging information (see GNAT @cite{-g} option).
31728 @subsubheading Debugging the DLL Directly
31735 Find out the executable starting address
31738 $ objdump --file-header main.exe
31741 The starting address is reported on the last line. For example:
31744 main.exe: file format pei-i386
31745 architecture: i386, flags 0x0000010a:
31746 EXEC_P, HAS_DEBUG, D_PAGED
31747 start address 0x00401010
31751 Launch the debugger on the executable.
31758 Set a breakpoint at the starting address, and launch the program.
31761 $ (gdb) break *0x00401010
31765 The program will stop at the given address.
31768 Set a breakpoint on a DLL subroutine.
31771 (gdb) break ada_dll.adb:45
31774 Or if you want to break using a symbol on the DLL, you need first to
31775 select the Ada language (language used by the DLL).
31778 (gdb) set language ada
31779 (gdb) break ada_dll
31783 Continue the program.
31789 This will run the program until it reaches the breakpoint that has been
31790 set. From that point you can use the standard way to debug a program
31791 as described in (@ref{26,,Running and Debugging Ada Programs}).
31794 It is also possible to debug the DLL by attaching to a running process.
31796 @subsubheading Attaching to a Running Process
31799 @geindex DLL debugging
31800 @geindex attach to process
31802 With @cite{GDB} it is always possible to debug a running process by
31803 attaching to it. It is possible to debug a DLL this way. The limitation
31804 of this approach is that the DLL must run long enough to perform the
31805 attach operation. It may be useful for instance to insert a time wasting
31806 loop in the code of the DLL to meet this criterion.
31812 Launch the main program @code{main.exe}.
31819 Use the Windows @emph{Task Manager} to find the process ID. Let's say
31820 that the process PID for @code{main.exe} is 208.
31830 Attach to the running process to be debugged.
31837 Load the process debugging information.
31840 (gdb) symbol-file main.exe
31844 Break somewhere in the DLL.
31847 (gdb) break ada_dll
31851 Continue process execution.
31858 This last step will resume the process execution, and stop at
31859 the breakpoint we have set. From there you can use the standard
31860 approach to debug a program as described in
31861 @ref{26,,Running and Debugging Ada Programs}.
31863 @node Setting Stack Size from gnatlink,Setting Heap Size from gnatlink,Debugging a DLL,Mixed-Language Programming on Windows
31864 @anchor{gnat_ugn/platform_specific_information setting-stack-size-from-gnatlink}@anchor{13a}@anchor{gnat_ugn/platform_specific_information id40}@anchor{2a8}
31865 @subsubsection Setting Stack Size from @emph{gnatlink}
31868 It is possible to specify the program stack size at link time. On modern
31869 versions of Windows, starting with XP, this is mostly useful to set the size of
31870 the main stack (environment task). The other task stacks are set with pragma
31871 Storage_Size or with the @emph{gnatbind -d} command.
31873 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
31874 reserve size of individual tasks, the link-time stack size applies to all
31875 tasks, and pragma Storage_Size has no effect.
31876 In particular, Stack Overflow checks are made against this
31877 link-time specified size.
31879 This setting can be done with @emph{gnatlink} using either of the following:
31885 @emph{-Xlinker} linker option
31888 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
31891 This sets the stack reserve size to 0x10000 bytes and the stack commit
31892 size to 0x1000 bytes.
31895 @emph{-Wl} linker option
31898 $ gnatlink hello -Wl,--stack=0x1000000
31901 This sets the stack reserve size to 0x1000000 bytes. Note that with
31902 @emph{-Wl} option it is not possible to set the stack commit size
31903 because the coma is a separator for this option.
31906 @node Setting Heap Size from gnatlink,,Setting Stack Size from gnatlink,Mixed-Language Programming on Windows
31907 @anchor{gnat_ugn/platform_specific_information setting-heap-size-from-gnatlink}@anchor{13b}@anchor{gnat_ugn/platform_specific_information id41}@anchor{2a9}
31908 @subsubsection Setting Heap Size from @emph{gnatlink}
31911 Under Windows systems, it is possible to specify the program heap size from
31912 @emph{gnatlink} using either of the following:
31918 @emph{-Xlinker} linker option
31921 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
31924 This sets the heap reserve size to 0x10000 bytes and the heap commit
31925 size to 0x1000 bytes.
31928 @emph{-Wl} linker option
31931 $ gnatlink hello -Wl,--heap=0x1000000
31934 This sets the heap reserve size to 0x1000000 bytes. Note that with
31935 @emph{-Wl} option it is not possible to set the heap commit size
31936 because the coma is a separator for this option.
31939 @node Mac OS Topics,,Microsoft Windows Topics,Platform-Specific Information
31940 @anchor{gnat_ugn/platform_specific_information mac-os-topics}@anchor{2f}@anchor{gnat_ugn/platform_specific_information id42}@anchor{2aa}
31941 @section Mac OS Topics
31946 This section describes topics that are specific to Apple's OS X
31950 * Codesigning the Debugger::
31954 @node Codesigning the Debugger,,,Mac OS Topics
31955 @anchor{gnat_ugn/platform_specific_information codesigning-the-debugger}@anchor{2ab}
31956 @subsection Codesigning the Debugger
31959 The Darwin Kernel requires the debugger to have special permissions
31960 before it is allowed to control other processes. These permissions
31961 are granted by codesigning the GDB executable. Without these
31962 permissions, the debugger will report error messages such as:
31965 Starting program: /x/y/foo
31966 Unable to find Mach task port for process-id 28885: (os/kern) failure (0x5).
31967 (please check gdb is codesigned - see taskgated(8))
31970 Codesigning requires a certificate. The following procedure explains
31977 Start the Keychain Access application (in
31978 /Applications/Utilities/Keychain Access.app)
31981 Select the Keychain Access -> Certificate Assistant ->
31982 Create a Certificate... menu
31991 Choose a name for the new certificate (this procedure will use
31992 "gdb-cert" as an example)
31995 Set "Identity Type" to "Self Signed Root"
31998 Set "Certificate Type" to "Code Signing"
32001 Activate the "Let me override defaults" option
32005 Click several times on "Continue" until the "Specify a Location
32006 For The Certificate" screen appears, then set "Keychain" to "System"
32009 Click on "Continue" until the certificate is created
32012 Finally, in the view, double-click on the new certificate,
32013 and set "When using this certificate" to "Always Trust"
32016 Exit the Keychain Access application and restart the computer
32017 (this is unfortunately required)
32020 Once a certificate has been created, the debugger can be codesigned
32021 as follow. In a Terminal, run the following command:
32026 $ codesign -f -s "gdb-cert" <gnat_install_prefix>/bin/gdb
32030 where "gdb-cert" should be replaced by the actual certificate
32031 name chosen above, and <gnat_install_prefix> should be replaced by
32032 the location where you installed GNAT. Also, be sure that users are
32033 in the Unix group @code{_developer}.
32035 @node Example of Binder Output File,Elaboration Order Handling in GNAT,Platform-Specific Information,Top
32036 @anchor{gnat_ugn/example_of_binder_output example-of-binder-output-file}@anchor{10}@anchor{gnat_ugn/example_of_binder_output doc}@anchor{2ac}@anchor{gnat_ugn/example_of_binder_output id1}@anchor{2ad}
32037 @chapter Example of Binder Output File
32040 @geindex Binder output (example)
32042 This Appendix displays the source code for the output file
32043 generated by @emph{gnatbind} for a simple 'Hello World' program.
32044 Comments have been added for clarification purposes.
32047 -- The package is called Ada_Main unless this name is actually used
32048 -- as a unit name in the partition, in which case some other unique
32053 package ada_main is
32054 pragma Warnings (Off);
32056 -- The main program saves the parameters (argument count,
32057 -- argument values, environment pointer) in global variables
32058 -- for later access by other units including
32059 -- Ada.Command_Line.
32061 gnat_argc : Integer;
32062 gnat_argv : System.Address;
32063 gnat_envp : System.Address;
32065 -- The actual variables are stored in a library routine. This
32066 -- is useful for some shared library situations, where there
32067 -- are problems if variables are not in the library.
32069 pragma Import (C, gnat_argc);
32070 pragma Import (C, gnat_argv);
32071 pragma Import (C, gnat_envp);
32073 -- The exit status is similarly an external location
32075 gnat_exit_status : Integer;
32076 pragma Import (C, gnat_exit_status);
32078 GNAT_Version : constant String :=
32079 "GNAT Version: Pro 7.4.0w (20141119-49)" & ASCII.NUL;
32080 pragma Export (C, GNAT_Version, "__gnat_version");
32082 Ada_Main_Program_Name : constant String := "_ada_hello" & ASCII.NUL;
32083 pragma Export (C, Ada_Main_Program_Name, "__gnat_ada_main_program_name");
32085 -- This is the generated adainit routine that performs
32086 -- initialization at the start of execution. In the case
32087 -- where Ada is the main program, this main program makes
32088 -- a call to adainit at program startup.
32091 pragma Export (C, adainit, "adainit");
32093 -- This is the generated adafinal routine that performs
32094 -- finalization at the end of execution. In the case where
32095 -- Ada is the main program, this main program makes a call
32096 -- to adafinal at program termination.
32098 procedure adafinal;
32099 pragma Export (C, adafinal, "adafinal");
32101 -- This routine is called at the start of execution. It is
32102 -- a dummy routine that is used by the debugger to breakpoint
32103 -- at the start of execution.
32105 -- This is the actual generated main program (it would be
32106 -- suppressed if the no main program switch were used). As
32107 -- required by standard system conventions, this program has
32108 -- the external name main.
32112 argv : System.Address;
32113 envp : System.Address)
32115 pragma Export (C, main, "main");
32117 -- The following set of constants give the version
32118 -- identification values for every unit in the bound
32119 -- partition. This identification is computed from all
32120 -- dependent semantic units, and corresponds to the
32121 -- string that would be returned by use of the
32122 -- Body_Version or Version attributes.
32124 -- The following Export pragmas export the version numbers
32125 -- with symbolic names ending in B (for body) or S
32126 -- (for spec) so that they can be located in a link. The
32127 -- information provided here is sufficient to track down
32128 -- the exact versions of units used in a given build.
32130 type Version_32 is mod 2 ** 32;
32131 u00001 : constant Version_32 := 16#8ad6e54a#;
32132 pragma Export (C, u00001, "helloB");
32133 u00002 : constant Version_32 := 16#fbff4c67#;
32134 pragma Export (C, u00002, "system__standard_libraryB");
32135 u00003 : constant Version_32 := 16#1ec6fd90#;
32136 pragma Export (C, u00003, "system__standard_libraryS");
32137 u00004 : constant Version_32 := 16#3ffc8e18#;
32138 pragma Export (C, u00004, "adaS");
32139 u00005 : constant Version_32 := 16#28f088c2#;
32140 pragma Export (C, u00005, "ada__text_ioB");
32141 u00006 : constant Version_32 := 16#f372c8ac#;
32142 pragma Export (C, u00006, "ada__text_ioS");
32143 u00007 : constant Version_32 := 16#2c143749#;
32144 pragma Export (C, u00007, "ada__exceptionsB");
32145 u00008 : constant Version_32 := 16#f4f0cce8#;
32146 pragma Export (C, u00008, "ada__exceptionsS");
32147 u00009 : constant Version_32 := 16#a46739c0#;
32148 pragma Export (C, u00009, "ada__exceptions__last_chance_handlerB");
32149 u00010 : constant Version_32 := 16#3aac8c92#;
32150 pragma Export (C, u00010, "ada__exceptions__last_chance_handlerS");
32151 u00011 : constant Version_32 := 16#1d274481#;
32152 pragma Export (C, u00011, "systemS");
32153 u00012 : constant Version_32 := 16#a207fefe#;
32154 pragma Export (C, u00012, "system__soft_linksB");
32155 u00013 : constant Version_32 := 16#467d9556#;
32156 pragma Export (C, u00013, "system__soft_linksS");
32157 u00014 : constant Version_32 := 16#b01dad17#;
32158 pragma Export (C, u00014, "system__parametersB");
32159 u00015 : constant Version_32 := 16#630d49fe#;
32160 pragma Export (C, u00015, "system__parametersS");
32161 u00016 : constant Version_32 := 16#b19b6653#;
32162 pragma Export (C, u00016, "system__secondary_stackB");
32163 u00017 : constant Version_32 := 16#b6468be8#;
32164 pragma Export (C, u00017, "system__secondary_stackS");
32165 u00018 : constant Version_32 := 16#39a03df9#;
32166 pragma Export (C, u00018, "system__storage_elementsB");
32167 u00019 : constant Version_32 := 16#30e40e85#;
32168 pragma Export (C, u00019, "system__storage_elementsS");
32169 u00020 : constant Version_32 := 16#41837d1e#;
32170 pragma Export (C, u00020, "system__stack_checkingB");
32171 u00021 : constant Version_32 := 16#93982f69#;
32172 pragma Export (C, u00021, "system__stack_checkingS");
32173 u00022 : constant Version_32 := 16#393398c1#;
32174 pragma Export (C, u00022, "system__exception_tableB");
32175 u00023 : constant Version_32 := 16#b33e2294#;
32176 pragma Export (C, u00023, "system__exception_tableS");
32177 u00024 : constant Version_32 := 16#ce4af020#;
32178 pragma Export (C, u00024, "system__exceptionsB");
32179 u00025 : constant Version_32 := 16#75442977#;
32180 pragma Export (C, u00025, "system__exceptionsS");
32181 u00026 : constant Version_32 := 16#37d758f1#;
32182 pragma Export (C, u00026, "system__exceptions__machineS");
32183 u00027 : constant Version_32 := 16#b895431d#;
32184 pragma Export (C, u00027, "system__exceptions_debugB");
32185 u00028 : constant Version_32 := 16#aec55d3f#;
32186 pragma Export (C, u00028, "system__exceptions_debugS");
32187 u00029 : constant Version_32 := 16#570325c8#;
32188 pragma Export (C, u00029, "system__img_intB");
32189 u00030 : constant Version_32 := 16#1ffca443#;
32190 pragma Export (C, u00030, "system__img_intS");
32191 u00031 : constant Version_32 := 16#b98c3e16#;
32192 pragma Export (C, u00031, "system__tracebackB");
32193 u00032 : constant Version_32 := 16#831a9d5a#;
32194 pragma Export (C, u00032, "system__tracebackS");
32195 u00033 : constant Version_32 := 16#9ed49525#;
32196 pragma Export (C, u00033, "system__traceback_entriesB");
32197 u00034 : constant Version_32 := 16#1d7cb2f1#;
32198 pragma Export (C, u00034, "system__traceback_entriesS");
32199 u00035 : constant Version_32 := 16#8c33a517#;
32200 pragma Export (C, u00035, "system__wch_conB");
32201 u00036 : constant Version_32 := 16#065a6653#;
32202 pragma Export (C, u00036, "system__wch_conS");
32203 u00037 : constant Version_32 := 16#9721e840#;
32204 pragma Export (C, u00037, "system__wch_stwB");
32205 u00038 : constant Version_32 := 16#2b4b4a52#;
32206 pragma Export (C, u00038, "system__wch_stwS");
32207 u00039 : constant Version_32 := 16#92b797cb#;
32208 pragma Export (C, u00039, "system__wch_cnvB");
32209 u00040 : constant Version_32 := 16#09eddca0#;
32210 pragma Export (C, u00040, "system__wch_cnvS");
32211 u00041 : constant Version_32 := 16#6033a23f#;
32212 pragma Export (C, u00041, "interfacesS");
32213 u00042 : constant Version_32 := 16#ece6fdb6#;
32214 pragma Export (C, u00042, "system__wch_jisB");
32215 u00043 : constant Version_32 := 16#899dc581#;
32216 pragma Export (C, u00043, "system__wch_jisS");
32217 u00044 : constant Version_32 := 16#10558b11#;
32218 pragma Export (C, u00044, "ada__streamsB");
32219 u00045 : constant Version_32 := 16#2e6701ab#;
32220 pragma Export (C, u00045, "ada__streamsS");
32221 u00046 : constant Version_32 := 16#db5c917c#;
32222 pragma Export (C, u00046, "ada__io_exceptionsS");
32223 u00047 : constant Version_32 := 16#12c8cd7d#;
32224 pragma Export (C, u00047, "ada__tagsB");
32225 u00048 : constant Version_32 := 16#ce72c228#;
32226 pragma Export (C, u00048, "ada__tagsS");
32227 u00049 : constant Version_32 := 16#c3335bfd#;
32228 pragma Export (C, u00049, "system__htableB");
32229 u00050 : constant Version_32 := 16#99e5f76b#;
32230 pragma Export (C, u00050, "system__htableS");
32231 u00051 : constant Version_32 := 16#089f5cd0#;
32232 pragma Export (C, u00051, "system__string_hashB");
32233 u00052 : constant Version_32 := 16#3bbb9c15#;
32234 pragma Export (C, u00052, "system__string_hashS");
32235 u00053 : constant Version_32 := 16#807fe041#;
32236 pragma Export (C, u00053, "system__unsigned_typesS");
32237 u00054 : constant Version_32 := 16#d27be59e#;
32238 pragma Export (C, u00054, "system__val_lluB");
32239 u00055 : constant Version_32 := 16#fa8db733#;
32240 pragma Export (C, u00055, "system__val_lluS");
32241 u00056 : constant Version_32 := 16#27b600b2#;
32242 pragma Export (C, u00056, "system__val_utilB");
32243 u00057 : constant Version_32 := 16#b187f27f#;
32244 pragma Export (C, u00057, "system__val_utilS");
32245 u00058 : constant Version_32 := 16#d1060688#;
32246 pragma Export (C, u00058, "system__case_utilB");
32247 u00059 : constant Version_32 := 16#392e2d56#;
32248 pragma Export (C, u00059, "system__case_utilS");
32249 u00060 : constant Version_32 := 16#84a27f0d#;
32250 pragma Export (C, u00060, "interfaces__c_streamsB");
32251 u00061 : constant Version_32 := 16#8bb5f2c0#;
32252 pragma Export (C, u00061, "interfaces__c_streamsS");
32253 u00062 : constant Version_32 := 16#6db6928f#;
32254 pragma Export (C, u00062, "system__crtlS");
32255 u00063 : constant Version_32 := 16#4e6a342b#;
32256 pragma Export (C, u00063, "system__file_ioB");
32257 u00064 : constant Version_32 := 16#ba56a5e4#;
32258 pragma Export (C, u00064, "system__file_ioS");
32259 u00065 : constant Version_32 := 16#b7ab275c#;
32260 pragma Export (C, u00065, "ada__finalizationB");
32261 u00066 : constant Version_32 := 16#19f764ca#;
32262 pragma Export (C, u00066, "ada__finalizationS");
32263 u00067 : constant Version_32 := 16#95817ed8#;
32264 pragma Export (C, u00067, "system__finalization_rootB");
32265 u00068 : constant Version_32 := 16#52d53711#;
32266 pragma Export (C, u00068, "system__finalization_rootS");
32267 u00069 : constant Version_32 := 16#769e25e6#;
32268 pragma Export (C, u00069, "interfaces__cB");
32269 u00070 : constant Version_32 := 16#4a38bedb#;
32270 pragma Export (C, u00070, "interfaces__cS");
32271 u00071 : constant Version_32 := 16#07e6ee66#;
32272 pragma Export (C, u00071, "system__os_libB");
32273 u00072 : constant Version_32 := 16#d7b69782#;
32274 pragma Export (C, u00072, "system__os_libS");
32275 u00073 : constant Version_32 := 16#1a817b8e#;
32276 pragma Export (C, u00073, "system__stringsB");
32277 u00074 : constant Version_32 := 16#639855e7#;
32278 pragma Export (C, u00074, "system__stringsS");
32279 u00075 : constant Version_32 := 16#e0b8de29#;
32280 pragma Export (C, u00075, "system__file_control_blockS");
32281 u00076 : constant Version_32 := 16#b5b2aca1#;
32282 pragma Export (C, u00076, "system__finalization_mastersB");
32283 u00077 : constant Version_32 := 16#69316dc1#;
32284 pragma Export (C, u00077, "system__finalization_mastersS");
32285 u00078 : constant Version_32 := 16#57a37a42#;
32286 pragma Export (C, u00078, "system__address_imageB");
32287 u00079 : constant Version_32 := 16#bccbd9bb#;
32288 pragma Export (C, u00079, "system__address_imageS");
32289 u00080 : constant Version_32 := 16#7268f812#;
32290 pragma Export (C, u00080, "system__img_boolB");
32291 u00081 : constant Version_32 := 16#e8fe356a#;
32292 pragma Export (C, u00081, "system__img_boolS");
32293 u00082 : constant Version_32 := 16#d7aac20c#;
32294 pragma Export (C, u00082, "system__ioB");
32295 u00083 : constant Version_32 := 16#8365b3ce#;
32296 pragma Export (C, u00083, "system__ioS");
32297 u00084 : constant Version_32 := 16#6d4d969a#;
32298 pragma Export (C, u00084, "system__storage_poolsB");
32299 u00085 : constant Version_32 := 16#e87cc305#;
32300 pragma Export (C, u00085, "system__storage_poolsS");
32301 u00086 : constant Version_32 := 16#e34550ca#;
32302 pragma Export (C, u00086, "system__pool_globalB");
32303 u00087 : constant Version_32 := 16#c88d2d16#;
32304 pragma Export (C, u00087, "system__pool_globalS");
32305 u00088 : constant Version_32 := 16#9d39c675#;
32306 pragma Export (C, u00088, "system__memoryB");
32307 u00089 : constant Version_32 := 16#445a22b5#;
32308 pragma Export (C, u00089, "system__memoryS");
32309 u00090 : constant Version_32 := 16#6a859064#;
32310 pragma Export (C, u00090, "system__storage_pools__subpoolsB");
32311 u00091 : constant Version_32 := 16#e3b008dc#;
32312 pragma Export (C, u00091, "system__storage_pools__subpoolsS");
32313 u00092 : constant Version_32 := 16#63f11652#;
32314 pragma Export (C, u00092, "system__storage_pools__subpools__finalizationB");
32315 u00093 : constant Version_32 := 16#fe2f4b3a#;
32316 pragma Export (C, u00093, "system__storage_pools__subpools__finalizationS");
32318 -- BEGIN ELABORATION ORDER
32322 -- system.case_util%s
32323 -- system.case_util%b
32325 -- system.img_bool%s
32326 -- system.img_bool%b
32327 -- system.img_int%s
32328 -- system.img_int%b
32331 -- system.parameters%s
32332 -- system.parameters%b
32334 -- interfaces.c_streams%s
32335 -- interfaces.c_streams%b
32336 -- system.standard_library%s
32337 -- system.exceptions_debug%s
32338 -- system.exceptions_debug%b
32339 -- system.storage_elements%s
32340 -- system.storage_elements%b
32341 -- system.stack_checking%s
32342 -- system.stack_checking%b
32343 -- system.string_hash%s
32344 -- system.string_hash%b
32346 -- system.strings%s
32347 -- system.strings%b
32349 -- system.traceback_entries%s
32350 -- system.traceback_entries%b
32351 -- ada.exceptions%s
32352 -- system.soft_links%s
32353 -- system.unsigned_types%s
32354 -- system.val_llu%s
32355 -- system.val_util%s
32356 -- system.val_util%b
32357 -- system.val_llu%b
32358 -- system.wch_con%s
32359 -- system.wch_con%b
32360 -- system.wch_cnv%s
32361 -- system.wch_jis%s
32362 -- system.wch_jis%b
32363 -- system.wch_cnv%b
32364 -- system.wch_stw%s
32365 -- system.wch_stw%b
32366 -- ada.exceptions.last_chance_handler%s
32367 -- ada.exceptions.last_chance_handler%b
32368 -- system.address_image%s
32369 -- system.exception_table%s
32370 -- system.exception_table%b
32371 -- ada.io_exceptions%s
32376 -- system.exceptions%s
32377 -- system.exceptions%b
32378 -- system.exceptions.machine%s
32379 -- system.finalization_root%s
32380 -- system.finalization_root%b
32381 -- ada.finalization%s
32382 -- ada.finalization%b
32383 -- system.storage_pools%s
32384 -- system.storage_pools%b
32385 -- system.finalization_masters%s
32386 -- system.storage_pools.subpools%s
32387 -- system.storage_pools.subpools.finalization%s
32388 -- system.storage_pools.subpools.finalization%b
32391 -- system.standard_library%b
32392 -- system.pool_global%s
32393 -- system.pool_global%b
32394 -- system.file_control_block%s
32395 -- system.file_io%s
32396 -- system.secondary_stack%s
32397 -- system.file_io%b
32398 -- system.storage_pools.subpools%b
32399 -- system.finalization_masters%b
32402 -- system.soft_links%b
32404 -- system.secondary_stack%b
32405 -- system.address_image%b
32406 -- system.traceback%s
32407 -- ada.exceptions%b
32408 -- system.traceback%b
32412 -- END ELABORATION ORDER
32419 -- The following source file name pragmas allow the generated file
32420 -- names to be unique for different main programs. They are needed
32421 -- since the package name will always be Ada_Main.
32423 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
32424 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
32426 pragma Suppress (Overflow_Check);
32427 with Ada.Exceptions;
32429 -- Generated package body for Ada_Main starts here
32431 package body ada_main is
32432 pragma Warnings (Off);
32434 -- These values are reference counter associated to units which have
32435 -- been elaborated. It is also used to avoid elaborating the
32436 -- same unit twice.
32438 E72 : Short_Integer; pragma Import (Ada, E72, "system__os_lib_E");
32439 E13 : Short_Integer; pragma Import (Ada, E13, "system__soft_links_E");
32440 E23 : Short_Integer; pragma Import (Ada, E23, "system__exception_table_E");
32441 E46 : Short_Integer; pragma Import (Ada, E46, "ada__io_exceptions_E");
32442 E48 : Short_Integer; pragma Import (Ada, E48, "ada__tags_E");
32443 E45 : Short_Integer; pragma Import (Ada, E45, "ada__streams_E");
32444 E70 : Short_Integer; pragma Import (Ada, E70, "interfaces__c_E");
32445 E25 : Short_Integer; pragma Import (Ada, E25, "system__exceptions_E");
32446 E68 : Short_Integer; pragma Import (Ada, E68, "system__finalization_root_E");
32447 E66 : Short_Integer; pragma Import (Ada, E66, "ada__finalization_E");
32448 E85 : Short_Integer; pragma Import (Ada, E85, "system__storage_pools_E");
32449 E77 : Short_Integer; pragma Import (Ada, E77, "system__finalization_masters_E");
32450 E91 : Short_Integer; pragma Import (Ada, E91, "system__storage_pools__subpools_E");
32451 E87 : Short_Integer; pragma Import (Ada, E87, "system__pool_global_E");
32452 E75 : Short_Integer; pragma Import (Ada, E75, "system__file_control_block_E");
32453 E64 : Short_Integer; pragma Import (Ada, E64, "system__file_io_E");
32454 E17 : Short_Integer; pragma Import (Ada, E17, "system__secondary_stack_E");
32455 E06 : Short_Integer; pragma Import (Ada, E06, "ada__text_io_E");
32457 Local_Priority_Specific_Dispatching : constant String := "";
32458 Local_Interrupt_States : constant String := "";
32460 Is_Elaborated : Boolean := False;
32462 procedure finalize_library is
32467 pragma Import (Ada, F1, "ada__text_io__finalize_spec");
32475 pragma Import (Ada, F2, "system__file_io__finalize_body");
32482 pragma Import (Ada, F3, "system__file_control_block__finalize_spec");
32490 pragma Import (Ada, F4, "system__pool_global__finalize_spec");
32496 pragma Import (Ada, F5, "system__storage_pools__subpools__finalize_spec");
32502 pragma Import (Ada, F6, "system__finalization_masters__finalize_spec");
32507 procedure Reraise_Library_Exception_If_Any;
32508 pragma Import (Ada, Reraise_Library_Exception_If_Any, "__gnat_reraise_library_exception_if_any");
32510 Reraise_Library_Exception_If_Any;
32512 end finalize_library;
32518 procedure adainit is
32520 Main_Priority : Integer;
32521 pragma Import (C, Main_Priority, "__gl_main_priority");
32522 Time_Slice_Value : Integer;
32523 pragma Import (C, Time_Slice_Value, "__gl_time_slice_val");
32524 WC_Encoding : Character;
32525 pragma Import (C, WC_Encoding, "__gl_wc_encoding");
32526 Locking_Policy : Character;
32527 pragma Import (C, Locking_Policy, "__gl_locking_policy");
32528 Queuing_Policy : Character;
32529 pragma Import (C, Queuing_Policy, "__gl_queuing_policy");
32530 Task_Dispatching_Policy : Character;
32531 pragma Import (C, Task_Dispatching_Policy, "__gl_task_dispatching_policy");
32532 Priority_Specific_Dispatching : System.Address;
32533 pragma Import (C, Priority_Specific_Dispatching, "__gl_priority_specific_dispatching");
32534 Num_Specific_Dispatching : Integer;
32535 pragma Import (C, Num_Specific_Dispatching, "__gl_num_specific_dispatching");
32536 Main_CPU : Integer;
32537 pragma Import (C, Main_CPU, "__gl_main_cpu");
32538 Interrupt_States : System.Address;
32539 pragma Import (C, Interrupt_States, "__gl_interrupt_states");
32540 Num_Interrupt_States : Integer;
32541 pragma Import (C, Num_Interrupt_States, "__gl_num_interrupt_states");
32542 Unreserve_All_Interrupts : Integer;
32543 pragma Import (C, Unreserve_All_Interrupts, "__gl_unreserve_all_interrupts");
32544 Detect_Blocking : Integer;
32545 pragma Import (C, Detect_Blocking, "__gl_detect_blocking");
32546 Default_Stack_Size : Integer;
32547 pragma Import (C, Default_Stack_Size, "__gl_default_stack_size");
32548 Leap_Seconds_Support : Integer;
32549 pragma Import (C, Leap_Seconds_Support, "__gl_leap_seconds_support");
32551 procedure Runtime_Initialize;
32552 pragma Import (C, Runtime_Initialize, "__gnat_runtime_initialize");
32554 Finalize_Library_Objects : No_Param_Proc;
32555 pragma Import (C, Finalize_Library_Objects, "__gnat_finalize_library_objects");
32557 -- Start of processing for adainit
32561 -- Record various information for this partition. The values
32562 -- are derived by the binder from information stored in the ali
32563 -- files by the compiler.
32565 if Is_Elaborated then
32568 Is_Elaborated := True;
32569 Main_Priority := -1;
32570 Time_Slice_Value := -1;
32571 WC_Encoding := 'b';
32572 Locking_Policy := ' ';
32573 Queuing_Policy := ' ';
32574 Task_Dispatching_Policy := ' ';
32575 Priority_Specific_Dispatching :=
32576 Local_Priority_Specific_Dispatching'Address;
32577 Num_Specific_Dispatching := 0;
32579 Interrupt_States := Local_Interrupt_States'Address;
32580 Num_Interrupt_States := 0;
32581 Unreserve_All_Interrupts := 0;
32582 Detect_Blocking := 0;
32583 Default_Stack_Size := -1;
32584 Leap_Seconds_Support := 0;
32586 Runtime_Initialize;
32588 Finalize_Library_Objects := finalize_library'access;
32590 -- Now we have the elaboration calls for all units in the partition.
32591 -- The Elab_Spec and Elab_Body attributes generate references to the
32592 -- implicit elaboration procedures generated by the compiler for
32593 -- each unit that requires elaboration. Increment a counter of
32594 -- reference for each unit.
32596 System.Soft_Links'Elab_Spec;
32597 System.Exception_Table'Elab_Body;
32599 Ada.Io_Exceptions'Elab_Spec;
32601 Ada.Tags'Elab_Spec;
32602 Ada.Streams'Elab_Spec;
32604 Interfaces.C'Elab_Spec;
32605 System.Exceptions'Elab_Spec;
32607 System.Finalization_Root'Elab_Spec;
32609 Ada.Finalization'Elab_Spec;
32611 System.Storage_Pools'Elab_Spec;
32613 System.Finalization_Masters'Elab_Spec;
32614 System.Storage_Pools.Subpools'Elab_Spec;
32615 System.Pool_Global'Elab_Spec;
32617 System.File_Control_Block'Elab_Spec;
32619 System.File_Io'Elab_Body;
32622 System.Finalization_Masters'Elab_Body;
32625 Ada.Tags'Elab_Body;
32627 System.Soft_Links'Elab_Body;
32629 System.Os_Lib'Elab_Body;
32631 System.Secondary_Stack'Elab_Body;
32633 Ada.Text_Io'Elab_Spec;
32634 Ada.Text_Io'Elab_Body;
32642 procedure adafinal is
32643 procedure s_stalib_adafinal;
32644 pragma Import (C, s_stalib_adafinal, "system__standard_library__adafinal");
32646 procedure Runtime_Finalize;
32647 pragma Import (C, Runtime_Finalize, "__gnat_runtime_finalize");
32650 if not Is_Elaborated then
32653 Is_Elaborated := False;
32658 -- We get to the main program of the partition by using
32659 -- pragma Import because if we try to with the unit and
32660 -- call it Ada style, then not only do we waste time
32661 -- recompiling it, but also, we don't really know the right
32662 -- switches (e.g.@@: identifier character set) to be used
32665 procedure Ada_Main_Program;
32666 pragma Import (Ada, Ada_Main_Program, "_ada_hello");
32672 -- main is actually a function, as in the ANSI C standard,
32673 -- defined to return the exit status. The three parameters
32674 -- are the argument count, argument values and environment
32679 argv : System.Address;
32680 envp : System.Address)
32683 -- The initialize routine performs low level system
32684 -- initialization using a standard library routine which
32685 -- sets up signal handling and performs any other
32686 -- required setup. The routine can be found in file
32689 procedure initialize;
32690 pragma Import (C, initialize, "__gnat_initialize");
32692 -- The finalize routine performs low level system
32693 -- finalization using a standard library routine. The
32694 -- routine is found in file a-final.c and in the standard
32695 -- distribution is a dummy routine that does nothing, so
32696 -- really this is a hook for special user finalization.
32698 procedure finalize;
32699 pragma Import (C, finalize, "__gnat_finalize");
32701 -- The following is to initialize the SEH exceptions
32703 SEH : aliased array (1 .. 2) of Integer;
32705 Ensure_Reference : aliased System.Address := Ada_Main_Program_Name'Address;
32706 pragma Volatile (Ensure_Reference);
32708 -- Start of processing for main
32711 -- Save global variables
32717 -- Call low level system initialization
32719 Initialize (SEH'Address);
32721 -- Call our generated Ada initialization routine
32725 -- Now we call the main program of the partition
32729 -- Perform Ada finalization
32733 -- Perform low level system finalization
32737 -- Return the proper exit status
32738 return (gnat_exit_status);
32741 -- This section is entirely comments, so it has no effect on the
32742 -- compilation of the Ada_Main package. It provides the list of
32743 -- object files and linker options, as well as some standard
32744 -- libraries needed for the link. The gnatlink utility parses
32745 -- this b~hello.adb file to read these comment lines to generate
32746 -- the appropriate command line arguments for the call to the
32747 -- system linker. The BEGIN/END lines are used for sentinels for
32748 -- this parsing operation.
32750 -- The exact file names will of course depend on the environment,
32751 -- host/target and location of files on the host system.
32753 -- BEGIN Object file/option list
32756 -- -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
32757 -- /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
32758 -- END Object file/option list
32763 The Ada code in the above example is exactly what is generated by the
32764 binder. We have added comments to more clearly indicate the function
32765 of each part of the generated @cite{Ada_Main} package.
32767 The code is standard Ada in all respects, and can be processed by any
32768 tools that handle Ada. In particular, it is possible to use the debugger
32769 in Ada mode to debug the generated @cite{Ada_Main} package. For example,
32770 suppose that for reasons that you do not understand, your program is crashing
32771 during elaboration of the body of @cite{Ada.Text_IO}. To locate this bug,
32772 you can place a breakpoint on the call:
32777 Ada.Text_Io'Elab_Body;
32781 and trace the elaboration routine for this package to find out where
32782 the problem might be (more usually of course you would be debugging
32783 elaboration code in your own application).
32785 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
32787 @node Elaboration Order Handling in GNAT,Inline Assembler,Example of Binder Output File,Top
32788 @anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-order-handling-in-gnat}@anchor{11}@anchor{gnat_ugn/elaboration_order_handling_in_gnat doc}@anchor{2ae}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id1}@anchor{2af}
32789 @chapter Elaboration Order Handling in GNAT
32792 @geindex Order of elaboration
32794 @geindex Elaboration control
32796 This appendix describes the handling of elaboration code in Ada and
32797 in GNAT, and discusses how the order of elaboration of program units can
32798 be controlled in GNAT, either automatically or with explicit programming
32802 * Elaboration Code::
32803 * Checking the Elaboration Order::
32804 * Controlling the Elaboration Order::
32805 * Controlling Elaboration in GNAT - Internal Calls::
32806 * Controlling Elaboration in GNAT - External Calls::
32807 * Default Behavior in GNAT - Ensuring Safety::
32808 * Treatment of Pragma Elaborate::
32809 * Elaboration Issues for Library Tasks::
32810 * Mixing Elaboration Models::
32811 * What to Do If the Default Elaboration Behavior Fails::
32812 * Elaboration for Indirect Calls::
32813 * Summary of Procedures for Elaboration Control::
32814 * Other Elaboration Order Considerations::
32815 * Determining the Chosen Elaboration Order::
32819 @node Elaboration Code,Checking the Elaboration Order,,Elaboration Order Handling in GNAT
32820 @anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-code}@anchor{2b0}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id2}@anchor{2b1}
32821 @section Elaboration Code
32824 Ada provides rather general mechanisms for executing code at elaboration
32825 time, that is to say before the main program starts executing. Such code arises
32832 @emph{Initializers for variables}
32834 Variables declared at the library level, in package specs or bodies, can
32835 require initialization that is performed at elaboration time, as in:
32838 Sqrt_Half : Float := Sqrt (0.5);
32842 @emph{Package initialization code}
32844 Code in a @cite{BEGIN-END} section at the outer level of a package body is
32845 executed as part of the package body elaboration code.
32848 @emph{Library level task allocators}
32850 Tasks that are declared using task allocators at the library level
32851 start executing immediately and hence can execute at elaboration time.
32854 Subprogram calls are possible in any of these contexts, which means that
32855 any arbitrary part of the program may be executed as part of the elaboration
32856 code. It is even possible to write a program which does all its work at
32857 elaboration time, with a null main program, although stylistically this
32858 would usually be considered an inappropriate way to structure
32861 An important concern arises in the context of elaboration code:
32862 we have to be sure that it is executed in an appropriate order. What we
32863 have is a series of elaboration code sections, potentially one section
32864 for each unit in the program. It is important that these execute
32865 in the correct order. Correctness here means that, taking the above
32866 example of the declaration of @cite{Sqrt_Half},
32867 if some other piece of
32868 elaboration code references @cite{Sqrt_Half},
32869 then it must run after the
32870 section of elaboration code that contains the declaration of
32873 There would never be any order of elaboration problem if we made a rule
32874 that whenever you @emph{with} a unit, you must elaborate both the spec and body
32875 of that unit before elaborating the unit doing the @emph{with}ing:
32879 package Unit_2 is ...
32882 would require that both the body and spec of @cite{Unit_1} be elaborated
32883 before the spec of @cite{Unit_2}. However, a rule like that would be far too
32884 restrictive. In particular, it would make it impossible to have routines
32885 in separate packages that were mutually recursive.
32887 You might think that a clever enough compiler could look at the actual
32888 elaboration code and determine an appropriate correct order of elaboration,
32889 but in the general case, this is not possible. Consider the following
32892 In the body of @cite{Unit_1}, we have a procedure @cite{Func_1}
32894 the variable @cite{Sqrt_1}, which is declared in the elaboration code
32895 of the body of @cite{Unit_1}:
32898 Sqrt_1 : Float := Sqrt (0.1);
32901 The elaboration code of the body of @cite{Unit_1} also contains:
32904 if expression_1 = 1 then
32905 Q := Unit_2.Func_2;
32909 @cite{Unit_2} is exactly parallel,
32910 it has a procedure @cite{Func_2} that references
32911 the variable @cite{Sqrt_2}, which is declared in the elaboration code of
32912 the body @cite{Unit_2}:
32915 Sqrt_2 : Float := Sqrt (0.1);
32918 The elaboration code of the body of @cite{Unit_2} also contains:
32921 if expression_2 = 2 then
32922 Q := Unit_1.Func_1;
32926 Now the question is, which of the following orders of elaboration is
32945 If you carefully analyze the flow here, you will see that you cannot tell
32946 at compile time the answer to this question.
32947 If @cite{expression_1} is not equal to 1,
32948 and @cite{expression_2} is not equal to 2,
32949 then either order is acceptable, because neither of the function calls is
32950 executed. If both tests evaluate to true, then neither order is acceptable
32951 and in fact there is no correct order.
32953 If one of the two expressions is true, and the other is false, then one
32954 of the above orders is correct, and the other is incorrect. For example,
32955 if @cite{expression_1} /= 1 and @cite{expression_2} = 2,
32956 then the call to @cite{Func_1}
32957 will occur, but not the call to @cite{Func_2.}
32958 This means that it is essential
32959 to elaborate the body of @cite{Unit_1} before
32960 the body of @cite{Unit_2}, so the first
32961 order of elaboration is correct and the second is wrong.
32963 By making @cite{expression_1} and @cite{expression_2}
32964 depend on input data, or perhaps
32965 the time of day, we can make it impossible for the compiler or binder
32966 to figure out which of these expressions will be true, and hence it
32967 is impossible to guarantee a safe order of elaboration at run time.
32969 @node Checking the Elaboration Order,Controlling the Elaboration Order,Elaboration Code,Elaboration Order Handling in GNAT
32970 @anchor{gnat_ugn/elaboration_order_handling_in_gnat checking-the-elaboration-order}@anchor{2b2}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id3}@anchor{2b3}
32971 @section Checking the Elaboration Order
32974 In some languages that involve the same kind of elaboration problems,
32975 e.g., Java and C++, the programmer needs to take these
32976 ordering problems into account, and it is common to
32977 write a program in which an incorrect elaboration order gives
32978 surprising results, because it references variables before they
32980 Ada is designed to be a safe language, and a programmer-beware approach is
32981 clearly not sufficient. Consequently, the language provides three lines
32988 @emph{Standard rules}
32990 Some standard rules restrict the possible choice of elaboration
32991 order. In particular, if you @emph{with} a unit, then its spec is always
32992 elaborated before the unit doing the @emph{with}. Similarly, a parent
32993 spec is always elaborated before the child spec, and finally
32994 a spec is always elaborated before its corresponding body.
32997 @geindex Elaboration checks
33000 @geindex elaboration
33006 @emph{Dynamic elaboration checks}
33008 Dynamic checks are made at run time, so that if some entity is accessed
33009 before it is elaborated (typically by means of a subprogram call)
33010 then the exception (@cite{Program_Error}) is raised.
33013 @emph{Elaboration control}
33015 Facilities are provided for the programmer to specify the desired order
33019 Let's look at these facilities in more detail. First, the rules for
33020 dynamic checking. One possible rule would be simply to say that the
33021 exception is raised if you access a variable which has not yet been
33022 elaborated. The trouble with this approach is that it could require
33023 expensive checks on every variable reference. Instead Ada has two
33024 rules which are a little more restrictive, but easier to check, and
33031 @emph{Restrictions on calls}
33033 A subprogram can only be called at elaboration time if its body
33034 has been elaborated. The rules for elaboration given above guarantee
33035 that the spec of the subprogram has been elaborated before the
33036 call, but not the body. If this rule is violated, then the
33037 exception @cite{Program_Error} is raised.
33040 @emph{Restrictions on instantiations}
33042 A generic unit can only be instantiated if the body of the generic
33043 unit has been elaborated. Again, the rules for elaboration given above
33044 guarantee that the spec of the generic unit has been elaborated
33045 before the instantiation, but not the body. If this rule is
33046 violated, then the exception @cite{Program_Error} is raised.
33049 The idea is that if the body has been elaborated, then any variables
33050 it references must have been elaborated; by checking for the body being
33051 elaborated we guarantee that none of its references causes any
33052 trouble. As we noted above, this is a little too restrictive, because a
33053 subprogram that has no non-local references in its body may in fact be safe
33054 to call. However, it really would be unsafe to rely on this, because
33055 it would mean that the caller was aware of details of the implementation
33056 in the body. This goes against the basic tenets of Ada.
33058 A plausible implementation can be described as follows.
33059 A Boolean variable is associated with each subprogram
33060 and each generic unit. This variable is initialized to False, and is set to
33061 True at the point body is elaborated. Every call or instantiation checks the
33062 variable, and raises @cite{Program_Error} if the variable is False.
33064 Note that one might think that it would be good enough to have one Boolean
33065 variable for each package, but that would not deal with cases of trying
33066 to call a body in the same package as the call
33067 that has not been elaborated yet.
33068 Of course a compiler may be able to do enough analysis to optimize away
33069 some of the Boolean variables as unnecessary, and @cite{GNAT} indeed
33070 does such optimizations, but still the easiest conceptual model is to
33071 think of there being one variable per subprogram.
33073 @node Controlling the Elaboration Order,Controlling Elaboration in GNAT - Internal Calls,Checking the Elaboration Order,Elaboration Order Handling in GNAT
33074 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id4}@anchor{2b4}@anchor{gnat_ugn/elaboration_order_handling_in_gnat controlling-the-elaboration-order}@anchor{2b5}
33075 @section Controlling the Elaboration Order
33078 In the previous section we discussed the rules in Ada which ensure
33079 that @cite{Program_Error} is raised if an incorrect elaboration order is
33080 chosen. This prevents erroneous executions, but we need mechanisms to
33081 specify a correct execution and avoid the exception altogether.
33082 To achieve this, Ada provides a number of features for controlling
33083 the order of elaboration. We discuss these features in this section.
33085 First, there are several ways of indicating to the compiler that a given
33086 unit has no elaboration problems:
33092 @emph{packages that do not require a body}
33094 A library package that does not require a body does not permit
33095 a body (this rule was introduced in Ada 95).
33096 Thus if we have a such a package, as in:
33099 package Definitions is
33101 type m is new integer;
33103 type a is array (1 .. 10) of m;
33104 type b is array (1 .. 20) of m;
33109 A package that @emph{with}s @cite{Definitions} may safely instantiate
33110 @cite{Definitions.Subp} because the compiler can determine that there
33111 definitely is no package body to worry about in this case
33114 @geindex pragma Pure
33122 This pragma places sufficient restrictions on a unit to guarantee that
33123 no call to any subprogram in the unit can result in an
33124 elaboration problem. This means that the compiler does not need
33125 to worry about the point of elaboration of such units, and in
33126 particular, does not need to check any calls to any subprograms
33130 @geindex pragma Preelaborate
33136 @emph{pragma Preelaborate}
33138 This pragma places slightly less stringent restrictions on a unit than
33140 but these restrictions are still sufficient to ensure that there
33141 are no elaboration problems with any calls to the unit.
33144 @geindex pragma Elaborate_Body
33150 @emph{pragma Elaborate_Body}
33152 This pragma requires that the body of a unit be elaborated immediately
33153 after its spec. Suppose a unit @cite{A} has such a pragma,
33154 and unit @cite{B} does
33155 a @emph{with} of unit @cite{A}. Recall that the standard rules require
33156 the spec of unit @cite{A}
33157 to be elaborated before the @emph{with}ing unit; given the pragma in
33158 @cite{A}, we also know that the body of @cite{A}
33159 will be elaborated before @cite{B}, so
33160 that calls to @cite{A} are safe and do not need a check.
33162 Note that, unlike pragma @cite{Pure} and pragma @cite{Preelaborate},
33163 the use of @cite{Elaborate_Body} does not guarantee that the program is
33164 free of elaboration problems, because it may not be possible
33165 to satisfy the requested elaboration order.
33166 Let's go back to the example with @cite{Unit_1} and @cite{Unit_2}.
33167 If a programmer marks @cite{Unit_1} as @cite{Elaborate_Body},
33168 and not @cite{Unit_2@comma{}} then the order of
33169 elaboration will be:
33178 Now that means that the call to @cite{Func_1} in @cite{Unit_2}
33179 need not be checked,
33180 it must be safe. But the call to @cite{Func_2} in
33181 @cite{Unit_1} may still fail if
33182 @cite{Expression_1} is equal to 1,
33183 and the programmer must still take
33184 responsibility for this not being the case.
33186 If all units carry a pragma @cite{Elaborate_Body}, then all problems are
33187 eliminated, except for calls entirely within a body, which are
33188 in any case fully under programmer control. However, using the pragma
33189 everywhere is not always possible.
33190 In particular, for our @cite{Unit_1}/@cite{Unit_2} example, if
33191 we marked both of them as having pragma @cite{Elaborate_Body}, then
33192 clearly there would be no possible elaboration order.
33195 The above pragmas allow a server to guarantee safe use by clients, and
33196 clearly this is the preferable approach. Consequently a good rule
33197 is to mark units as @cite{Pure} or @cite{Preelaborate} if possible,
33198 and if this is not possible,
33199 mark them as @cite{Elaborate_Body} if possible.
33200 As we have seen, there are situations where neither of these
33201 three pragmas can be used.
33202 So we also provide methods for clients to control the
33203 order of elaboration of the servers on which they depend:
33205 @geindex pragma Elaborate
33211 @emph{pragma Elaborate (unit)}
33213 This pragma is placed in the context clause, after a @emph{with} clause,
33214 and it requires that the body of the named unit be elaborated before
33215 the unit in which the pragma occurs. The idea is to use this pragma
33216 if the current unit calls at elaboration time, directly or indirectly,
33217 some subprogram in the named unit.
33220 @geindex pragma Elaborate_All
33226 @emph{pragma Elaborate_All (unit)}
33228 This is a stronger version of the Elaborate pragma. Consider the
33232 Unit A |withs| unit B and calls B.Func in elab code
33233 Unit B |withs| unit C, and B.Func calls C.Func
33236 Now if we put a pragma @cite{Elaborate (B)}
33237 in unit @cite{A}, this ensures that the
33238 body of @cite{B} is elaborated before the call, but not the
33239 body of @cite{C}, so
33240 the call to @cite{C.Func} could still cause @cite{Program_Error} to
33243 The effect of a pragma @cite{Elaborate_All} is stronger, it requires
33244 not only that the body of the named unit be elaborated before the
33245 unit doing the @emph{with}, but also the bodies of all units that the
33246 named unit uses, following @emph{with} links transitively. For example,
33247 if we put a pragma @cite{Elaborate_All (B)} in unit @cite{A},
33248 then it requires not only that the body of @cite{B} be elaborated before @cite{A},
33249 but also the body of @cite{C}, because @cite{B} @emph{with}s @cite{C}.
33252 We are now in a position to give a usage rule in Ada for avoiding
33253 elaboration problems, at least if dynamic dispatching and access to
33254 subprogram values are not used. We will handle these cases separately
33257 The rule is simple:
33259 @emph{If a unit has elaboration code that can directly or
33260 indirectly make a call to a subprogram in a |withed| unit, or instantiate
33261 a generic package in a |withed| unit,
33262 then if the |withed| unit does not have
33263 pragma `Pure` or `Preelaborate`, then the client should have
33264 a pragma `Elaborate_All`for the |withed| unit.*}
33266 By following this rule a client is
33267 assured that calls can be made without risk of an exception.
33269 For generic subprogram instantiations, the rule can be relaxed to
33270 require only a pragma @cite{Elaborate} since elaborating the body
33271 of a subprogram cannot cause any transitive elaboration (we are
33272 not calling the subprogram in this case, just elaborating its
33275 If this rule is not followed, then a program may be in one of four
33282 @emph{No order exists}
33284 No order of elaboration exists which follows the rules, taking into
33285 account any @cite{Elaborate}, @cite{Elaborate_All},
33286 or @cite{Elaborate_Body} pragmas. In
33287 this case, an Ada compiler must diagnose the situation at bind
33288 time, and refuse to build an executable program.
33291 @emph{One or more orders exist, all incorrect}
33293 One or more acceptable elaboration orders exist, and all of them
33294 generate an elaboration order problem. In this case, the binder
33295 can build an executable program, but @cite{Program_Error} will be raised
33296 when the program is run.
33299 @emph{Several orders exist, some right, some incorrect}
33301 One or more acceptable elaboration orders exists, and some of them
33302 work, and some do not. The programmer has not controlled
33303 the order of elaboration, so the binder may or may not pick one of
33304 the correct orders, and the program may or may not raise an
33305 exception when it is run. This is the worst case, because it means
33306 that the program may fail when moved to another compiler, or even
33307 another version of the same compiler.
33310 @emph{One or more orders exists, all correct}
33312 One ore more acceptable elaboration orders exist, and all of them
33313 work. In this case the program runs successfully. This state of
33314 affairs can be guaranteed by following the rule we gave above, but
33315 may be true even if the rule is not followed.
33318 Note that one additional advantage of following our rules on the use
33319 of @cite{Elaborate} and @cite{Elaborate_All}
33320 is that the program continues to stay in the ideal (all orders OK) state
33321 even if maintenance
33322 changes some bodies of some units. Conversely, if a program that does
33323 not follow this rule happens to be safe at some point, this state of affairs
33324 may deteriorate silently as a result of maintenance changes.
33326 You may have noticed that the above discussion did not mention
33327 the use of @cite{Elaborate_Body}. This was a deliberate omission. If you
33328 @emph{with} an @cite{Elaborate_Body} unit, it still may be the case that
33329 code in the body makes calls to some other unit, so it is still necessary
33330 to use @cite{Elaborate_All} on such units.
33332 @node Controlling Elaboration in GNAT - Internal Calls,Controlling Elaboration in GNAT - External Calls,Controlling the Elaboration Order,Elaboration Order Handling in GNAT
33333 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id5}@anchor{2b6}@anchor{gnat_ugn/elaboration_order_handling_in_gnat controlling-elaboration-in-gnat-internal-calls}@anchor{2b7}
33334 @section Controlling Elaboration in GNAT - Internal Calls
33337 In the case of internal calls, i.e., calls within a single package, the
33338 programmer has full control over the order of elaboration, and it is up
33339 to the programmer to elaborate declarations in an appropriate order. For
33343 function One return Float;
33347 function One return Float is
33353 will obviously raise @cite{Program_Error} at run time, because function
33354 One will be called before its body is elaborated. In this case GNAT will
33355 generate a warning that the call will raise @cite{Program_Error}:
33359 2. function One return Float;
33361 4. Q : Float := One;
33363 >>> warning: cannot call "One" before body is elaborated
33364 >>> warning: Program_Error will be raised at run time
33367 6. function One return Float is
33377 Note that in this particular case, it is likely that the call is safe, because
33378 the function @cite{One} does not access any global variables.
33379 Nevertheless in Ada, we do not want the validity of the check to depend on
33380 the contents of the body (think about the separate compilation case), so this
33381 is still wrong, as we discussed in the previous sections.
33383 The error is easily corrected by rearranging the declarations so that the
33384 body of @cite{One} appears before the declaration containing the call
33385 (note that in Ada 95 as well as later versions of the Ada standard,
33386 declarations can appear in any order, so there is no restriction that
33387 would prevent this reordering, and if we write:
33390 function One return Float;
33392 function One return Float is
33400 then all is well, no warning is generated, and no
33401 @cite{Program_Error} exception
33403 Things are more complicated when a chain of subprograms is executed:
33406 function A return Integer;
33407 function B return Integer;
33408 function C return Integer;
33410 function B return Integer is begin return A; end;
33411 function C return Integer is begin return B; end;
33415 function A return Integer is begin return 1; end;
33418 Now the call to @cite{C}
33419 at elaboration time in the declaration of @cite{X} is correct, because
33420 the body of @cite{C} is already elaborated,
33421 and the call to @cite{B} within the body of
33422 @cite{C} is correct, but the call
33423 to @cite{A} within the body of @cite{B} is incorrect, because the body
33424 of @cite{A} has not been elaborated, so @cite{Program_Error}
33425 will be raised on the call to @cite{A}.
33426 In this case GNAT will generate a
33427 warning that @cite{Program_Error} may be
33428 raised at the point of the call. Let's look at the warning:
33432 2. function A return Integer;
33433 3. function B return Integer;
33434 4. function C return Integer;
33436 6. function B return Integer is begin return A; end;
33438 >>> warning: call to "A" before body is elaborated may
33439 raise Program_Error
33440 >>> warning: "B" called at line 7
33441 >>> warning: "C" called at line 9
33443 7. function C return Integer is begin return B; end;
33445 9. X : Integer := C;
33447 11. function A return Integer is begin return 1; end;
33454 Note that the message here says 'may raise', instead of the direct case,
33455 where the message says 'will be raised'. That's because whether
33457 actually called depends in general on run-time flow of control.
33458 For example, if the body of @cite{B} said
33461 function B return Integer is
33463 if some-condition-depending-on-input-data then
33471 then we could not know until run time whether the incorrect call to A would
33472 actually occur, so @cite{Program_Error} might
33473 or might not be raised. It is possible for a compiler to
33474 do a better job of analyzing bodies, to
33475 determine whether or not @cite{Program_Error}
33476 might be raised, but it certainly
33477 couldn't do a perfect job (that would require solving the halting problem
33478 and is provably impossible), and because this is a warning anyway, it does
33479 not seem worth the effort to do the analysis. Cases in which it
33480 would be relevant are rare.
33482 In practice, warnings of either of the forms given
33483 above will usually correspond to
33484 real errors, and should be examined carefully and eliminated.
33485 In the rare case where a warning is bogus, it can be suppressed by any of
33486 the following methods:
33492 Compile with the @emph{-gnatws} switch set
33495 Suppress @cite{Elaboration_Check} for the called subprogram
33498 Use pragma @cite{Warnings_Off} to turn warnings off for the call
33501 For the internal elaboration check case,
33502 GNAT by default generates the
33503 necessary run-time checks to ensure
33504 that @cite{Program_Error} is raised if any
33505 call fails an elaboration check. Of course this can only happen if a
33506 warning has been issued as described above. The use of pragma
33507 @cite{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
33508 some of these checks, meaning that it may be possible (but is not
33509 guaranteed) for a program to be able to call a subprogram whose body
33510 is not yet elaborated, without raising a @cite{Program_Error} exception.
33512 @node Controlling Elaboration in GNAT - External Calls,Default Behavior in GNAT - Ensuring Safety,Controlling Elaboration in GNAT - Internal Calls,Elaboration Order Handling in GNAT
33513 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id6}@anchor{2b8}@anchor{gnat_ugn/elaboration_order_handling_in_gnat controlling-elaboration-in-gnat-external-calls}@anchor{2b9}
33514 @section Controlling Elaboration in GNAT - External Calls
33517 The previous section discussed the case in which the execution of a
33518 particular thread of elaboration code occurred entirely within a
33519 single unit. This is the easy case to handle, because a programmer
33520 has direct and total control over the order of elaboration, and
33521 furthermore, checks need only be generated in cases which are rare
33522 and which the compiler can easily detect.
33523 The situation is more complex when separate compilation is taken into account.
33524 Consider the following:
33528 function Sqrt (Arg : Float) return Float;
33531 package body Math is
33532 function Sqrt (Arg : Float) return Float is
33540 X : Float := Math.Sqrt (0.5);
33550 where @cite{Main} is the main program. When this program is executed, the
33551 elaboration code must first be executed, and one of the jobs of the
33552 binder is to determine the order in which the units of a program are
33553 to be elaborated. In this case we have four units: the spec and body
33555 the spec of @cite{Stuff} and the body of @cite{Main}).
33556 In what order should the four separate sections of elaboration code
33559 There are some restrictions in the order of elaboration that the binder
33560 can choose. In particular, if unit U has a @emph{with}
33561 for a package @cite{X}, then you
33562 are assured that the spec of @cite{X}
33563 is elaborated before U , but you are
33564 not assured that the body of @cite{X}
33565 is elaborated before U.
33566 This means that in the above case, the binder is allowed to choose the
33576 but that's not good, because now the call to @cite{Math.Sqrt}
33577 that happens during
33578 the elaboration of the @cite{Stuff}
33579 spec happens before the body of @cite{Math.Sqrt} is
33580 elaborated, and hence causes @cite{Program_Error} exception to be raised.
33581 At first glance, one might say that the binder is misbehaving, because
33582 obviously you want to elaborate the body of something you @emph{with} first, but
33583 that is not a general rule that can be followed in all cases. Consider
33591 package body Y is ...
33594 package body X is ...
33597 This is a common arrangement, and, apart from the order of elaboration
33598 problems that might arise in connection with elaboration code, this works fine.
33599 A rule that says that you must first elaborate the body of anything you
33600 @emph{with} cannot work in this case:
33601 the body of @cite{X} @emph{with}s @cite{Y},
33602 which means you would have to
33603 elaborate the body of @cite{Y} first, but that @emph{with}s @cite{X},
33605 you have to elaborate the body of @cite{X} first, but ... and we have a
33606 loop that cannot be broken.
33608 It is true that the binder can in many cases guess an order of elaboration
33609 that is unlikely to cause a @cite{Program_Error}
33610 exception to be raised, and it tries to do so (in the
33611 above example of @cite{Math/Stuff/Spec}, the GNAT binder will
33613 elaborate the body of @cite{Math} right after its spec, so all will be well).
33615 However, a program that blindly relies on the binder to be helpful can
33616 get into trouble, as we discussed in the previous sections, so GNAT
33617 provides a number of facilities for assisting the programmer in
33618 developing programs that are robust with respect to elaboration order.
33620 @node Default Behavior in GNAT - Ensuring Safety,Treatment of Pragma Elaborate,Controlling Elaboration in GNAT - External Calls,Elaboration Order Handling in GNAT
33621 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id7}@anchor{2ba}@anchor{gnat_ugn/elaboration_order_handling_in_gnat default-behavior-in-gnat-ensuring-safety}@anchor{2bb}
33622 @section Default Behavior in GNAT - Ensuring Safety
33625 The default behavior in GNAT ensures elaboration safety. In its
33626 default mode GNAT implements the
33627 rule we previously described as the right approach. Let's restate it:
33629 @emph{If a unit has elaboration code that can directly or indirectly make a
33630 call to a subprogram in a |withed| unit, or instantiate a generic
33631 package in a |withed| unit, then if the |withed| unit
33632 does not have pragma `Pure` or `Preelaborate`, then the client should have an
33633 `Elaborate_All` pragma for the |withed| unit.}
33635 @emph{In the case of instantiating a generic subprogram, it is always
33636 sufficient to have only an `Elaborate` pragma for the
33639 By following this rule a client is assured that calls and instantiations
33640 can be made without risk of an exception.
33642 In this mode GNAT traces all calls that are potentially made from
33643 elaboration code, and puts in any missing implicit @cite{Elaborate}
33644 and @cite{Elaborate_All} pragmas.
33645 The advantage of this approach is that no elaboration problems
33646 are possible if the binder can find an elaboration order that is
33647 consistent with these implicit @cite{Elaborate} and
33648 @cite{Elaborate_All} pragmas. The
33649 disadvantage of this approach is that no such order may exist.
33651 If the binder does not generate any diagnostics, then it means that it has
33652 found an elaboration order that is guaranteed to be safe. However, the binder
33653 may still be relying on implicitly generated @cite{Elaborate} and
33654 @cite{Elaborate_All} pragmas so portability to other compilers than GNAT is not
33657 If it is important to guarantee portability, then the compilations should
33658 use the @emph{-gnatel}
33659 (info messages for elaboration pragmas) switch. This will cause info messages
33660 to be generated indicating the missing @cite{Elaborate} and
33661 @cite{Elaborate_All} pragmas.
33662 Consider the following source program:
33667 m : integer := k.r;
33671 where it is clear that there
33672 should be a pragma @cite{Elaborate_All}
33673 for unit @cite{k}. An implicit pragma will be generated, and it is
33674 likely that the binder will be able to honor it. However, if you want
33675 to port this program to some other Ada compiler than GNAT.
33676 it is safer to include the pragma explicitly in the source. If this
33677 unit is compiled with the @emph{-gnatel}
33678 switch, then the compiler outputs an information message:
33683 3. m : integer := k.r;
33685 >>> info: call to "r" may raise Program_Error
33686 >>> info: missing pragma Elaborate_All for "k"
33691 and these messages can be used as a guide for supplying manually
33692 the missing pragmas. It is usually a bad idea to use this
33693 option during development. That's because it will tell you when
33694 you need to put in a pragma, but cannot tell you when it is time
33695 to take it out. So the use of pragma @cite{Elaborate_All} may lead to
33696 unnecessary dependencies and even false circularities.
33698 This default mode is more restrictive than the Ada Reference
33699 Manual, and it is possible to construct programs which will compile
33700 using the dynamic model described there, but will run into a
33701 circularity using the safer static model we have described.
33703 Of course any Ada compiler must be able to operate in a mode
33704 consistent with the requirements of the Ada Reference Manual,
33705 and in particular must have the capability of implementing the
33706 standard dynamic model of elaboration with run-time checks.
33708 In GNAT, this standard mode can be achieved either by the use of
33709 the @emph{-gnatE} switch on the compiler (@emph{gcc} or
33710 @emph{gnatmake}) command, or by the use of the configuration pragma:
33713 pragma Elaboration_Checks (DYNAMIC);
33716 Either approach will cause the unit affected to be compiled using the
33717 standard dynamic run-time elaboration checks described in the Ada
33718 Reference Manual. The static model is generally preferable, since it
33719 is clearly safer to rely on compile and link time checks rather than
33720 run-time checks. However, in the case of legacy code, it may be
33721 difficult to meet the requirements of the static model. This
33722 issue is further discussed in
33723 @ref{2bc,,What to Do If the Default Elaboration Behavior Fails}.
33725 Note that the static model provides a strict subset of the allowed
33726 behavior and programs of the Ada Reference Manual, so if you do
33727 adhere to the static model and no circularities exist,
33728 then you are assured that your program will
33729 work using the dynamic model, providing that you remove any
33730 pragma Elaborate statements from the source.
33732 @node Treatment of Pragma Elaborate,Elaboration Issues for Library Tasks,Default Behavior in GNAT - Ensuring Safety,Elaboration Order Handling in GNAT
33733 @anchor{gnat_ugn/elaboration_order_handling_in_gnat treatment-of-pragma-elaborate}@anchor{2bd}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id8}@anchor{2be}
33734 @section Treatment of Pragma Elaborate
33737 @geindex Pragma Elaborate
33739 The use of @cite{pragma Elaborate}
33740 should generally be avoided in Ada 95 and Ada 2005 programs,
33741 since there is no guarantee that transitive calls
33742 will be properly handled. Indeed at one point, this pragma was placed
33743 in Annex J (Obsolescent Features), on the grounds that it is never useful.
33745 Now that's a bit restrictive. In practice, the case in which
33746 @cite{pragma Elaborate} is useful is when the caller knows that there
33747 are no transitive calls, or that the called unit contains all necessary
33748 transitive @cite{pragma Elaborate} statements, and legacy code often
33749 contains such uses.
33751 Strictly speaking the static mode in GNAT should ignore such pragmas,
33752 since there is no assurance at compile time that the necessary safety
33753 conditions are met. In practice, this would cause GNAT to be incompatible
33754 with correctly written Ada 83 code that had all necessary
33755 @cite{pragma Elaborate} statements in place. Consequently, we made the
33756 decision that GNAT in its default mode will believe that if it encounters
33757 a @cite{pragma Elaborate} then the programmer knows what they are doing,
33758 and it will trust that no elaboration errors can occur.
33760 The result of this decision is two-fold. First to be safe using the
33761 static mode, you should remove all @cite{pragma Elaborate} statements.
33762 Second, when fixing circularities in existing code, you can selectively
33763 use @cite{pragma Elaborate} statements to convince the static mode of
33764 GNAT that it need not generate an implicit @cite{pragma Elaborate_All}
33767 When using the static mode with @emph{-gnatwl}, any use of
33768 @cite{pragma Elaborate} will generate a warning about possible
33771 @node Elaboration Issues for Library Tasks,Mixing Elaboration Models,Treatment of Pragma Elaborate,Elaboration Order Handling in GNAT
33772 @anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-issues-for-library-tasks}@anchor{2bf}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id9}@anchor{2c0}
33773 @section Elaboration Issues for Library Tasks
33776 @geindex Library tasks
33777 @geindex elaboration issues
33779 @geindex Elaboration of library tasks
33781 In this section we examine special elaboration issues that arise for
33782 programs that declare library level tasks.
33784 Generally the model of execution of an Ada program is that all units are
33785 elaborated, and then execution of the program starts. However, the
33786 declaration of library tasks definitely does not fit this model. The
33787 reason for this is that library tasks start as soon as they are declared
33788 (more precisely, as soon as the statement part of the enclosing package
33789 body is reached), that is to say before elaboration
33790 of the program is complete. This means that if such a task calls a
33791 subprogram, or an entry in another task, the callee may or may not be
33792 elaborated yet, and in the standard
33793 Reference Manual model of dynamic elaboration checks, you can even
33794 get timing dependent Program_Error exceptions, since there can be
33795 a race between the elaboration code and the task code.
33797 The static model of elaboration in GNAT seeks to avoid all such
33798 dynamic behavior, by being conservative, and the conservative
33799 approach in this particular case is to assume that all the code
33800 in a task body is potentially executed at elaboration time if
33801 a task is declared at the library level.
33803 This can definitely result in unexpected circularities. Consider
33804 the following example
33812 type My_Int is new Integer;
33814 function Ident (M : My_Int) return My_Int;
33818 package body Decls is
33819 task body Lib_Task is
33825 function Ident (M : My_Int) return My_Int is
33833 procedure Put_Val (Arg : Decls.My_Int);
33837 package body Utils is
33838 procedure Put_Val (Arg : Decls.My_Int) is
33840 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
33847 Decls.Lib_Task.Start;
33851 If the above example is compiled in the default static elaboration
33852 mode, then a circularity occurs. The circularity comes from the call
33853 @cite{Utils.Put_Val} in the task body of @cite{Decls.Lib_Task}. Since
33854 this call occurs in elaboration code, we need an implicit pragma
33855 @cite{Elaborate_All} for @cite{Utils}. This means that not only must
33856 the spec and body of @cite{Utils} be elaborated before the body
33857 of @cite{Decls}, but also the spec and body of any unit that is
33858 @emph{with}ed by the body of @cite{Utils} must also be elaborated before
33859 the body of @cite{Decls}. This is the transitive implication of
33860 pragma @cite{Elaborate_All} and it makes sense, because in general
33861 the body of @cite{Put_Val} might have a call to something in a
33862 @emph{with}ed unit.
33864 In this case, the body of Utils (actually its spec) @emph{with}s
33865 @cite{Decls}. Unfortunately this means that the body of @cite{Decls}
33866 must be elaborated before itself, in case there is a call from the
33867 body of @cite{Utils}.
33869 Here is the exact chain of events we are worrying about:
33875 In the body of @cite{Decls} a call is made from within the body of a library
33876 task to a subprogram in the package @cite{Utils}. Since this call may
33877 occur at elaboration time (given that the task is activated at elaboration
33878 time), we have to assume the worst, i.e., that the
33879 call does happen at elaboration time.
33882 This means that the body and spec of @cite{Util} must be elaborated before
33883 the body of @cite{Decls} so that this call does not cause an access before
33887 Within the body of @cite{Util}, specifically within the body of
33888 @cite{Util.Put_Val} there may be calls to any unit @emph{with}ed
33892 One such @emph{with}ed package is package @cite{Decls}, so there
33893 might be a call to a subprogram in @cite{Decls} in @cite{Put_Val}.
33894 In fact there is such a call in this example, but we would have to
33895 assume that there was such a call even if it were not there, since
33896 we are not supposed to write the body of @cite{Decls} knowing what
33897 is in the body of @cite{Utils}; certainly in the case of the
33898 static elaboration model, the compiler does not know what is in
33899 other bodies and must assume the worst.
33902 This means that the spec and body of @cite{Decls} must also be
33903 elaborated before we elaborate the unit containing the call, but
33904 that unit is @cite{Decls}! This means that the body of @cite{Decls}
33905 must be elaborated before itself, and that's a circularity.
33908 Indeed, if you add an explicit pragma @cite{Elaborate_All} for @cite{Utils} in
33909 the body of @cite{Decls} you will get a true Ada Reference Manual
33910 circularity that makes the program illegal.
33912 In practice, we have found that problems with the static model of
33913 elaboration in existing code often arise from library tasks, so
33914 we must address this particular situation.
33916 Note that if we compile and run the program above, using the dynamic model of
33917 elaboration (that is to say use the @emph{-gnatE} switch),
33918 then it compiles, binds,
33919 links, and runs, printing the expected result of 2. Therefore in some sense
33920 the circularity here is only apparent, and we need to capture
33921 the properties of this program that distinguish it from other library-level
33922 tasks that have real elaboration problems.
33924 We have four possible answers to this question:
33930 Use the dynamic model of elaboration.
33932 If we use the @emph{-gnatE} switch, then as noted above, the program works.
33933 Why is this? If we examine the task body, it is apparent that the task cannot
33935 @cite{accept} statement until after elaboration has been completed, because
33936 the corresponding entry call comes from the main program, not earlier.
33937 This is why the dynamic model works here. But that's really giving
33938 up on a precise analysis, and we prefer to take this approach only if we cannot
33940 problem in any other manner. So let us examine two ways to reorganize
33941 the program to avoid the potential elaboration problem.
33944 Split library tasks into separate packages.
33946 Write separate packages, so that library tasks are isolated from
33947 other declarations as much as possible. Let us look at a variation on
33958 package body Decls1 is
33959 task body Lib_Task is
33967 type My_Int is new Integer;
33968 function Ident (M : My_Int) return My_Int;
33972 package body Decls2 is
33973 function Ident (M : My_Int) return My_Int is
33981 procedure Put_Val (Arg : Decls2.My_Int);
33985 package body Utils is
33986 procedure Put_Val (Arg : Decls2.My_Int) is
33988 Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
33995 Decls1.Lib_Task.Start;
33999 All we have done is to split @cite{Decls} into two packages, one
34000 containing the library task, and one containing everything else. Now
34001 there is no cycle, and the program compiles, binds, links and executes
34002 using the default static model of elaboration.
34005 Declare separate task types.
34007 A significant part of the problem arises because of the use of the
34008 single task declaration form. This means that the elaboration of
34009 the task type, and the elaboration of the task itself (i.e., the
34010 creation of the task) happen at the same time. A good rule
34011 of style in Ada is to always create explicit task types. By
34012 following the additional step of placing task objects in separate
34013 packages from the task type declaration, many elaboration problems
34014 are avoided. Here is another modified example of the example program:
34018 task type Lib_Task_Type is
34022 type My_Int is new Integer;
34024 function Ident (M : My_Int) return My_Int;
34028 package body Decls is
34029 task body Lib_Task_Type is
34035 function Ident (M : My_Int) return My_Int is
34043 procedure Put_Val (Arg : Decls.My_Int);
34047 package body Utils is
34048 procedure Put_Val (Arg : Decls.My_Int) is
34050 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
34056 Lib_Task : Decls.Lib_Task_Type;
34062 Declst.Lib_Task.Start;
34066 What we have done here is to replace the @cite{task} declaration in
34067 package @cite{Decls} with a @cite{task type} declaration. Then we
34068 introduce a separate package @cite{Declst} to contain the actual
34069 task object. This separates the elaboration issues for
34070 the @cite{task type}
34071 declaration, which causes no trouble, from the elaboration issues
34072 of the task object, which is also unproblematic, since it is now independent
34073 of the elaboration of @cite{Utils}.
34074 This separation of concerns also corresponds to
34075 a generally sound engineering principle of separating declarations
34076 from instances. This version of the program also compiles, binds, links,
34077 and executes, generating the expected output.
34080 @geindex No_Entry_Calls_In_Elaboration_Code restriction
34086 Use No_Entry_Calls_In_Elaboration_Code restriction.
34088 The previous two approaches described how a program can be restructured
34089 to avoid the special problems caused by library task bodies. in practice,
34090 however, such restructuring may be difficult to apply to existing legacy code,
34091 so we must consider solutions that do not require massive rewriting.
34093 Let us consider more carefully why our original sample program works
34094 under the dynamic model of elaboration. The reason is that the code
34095 in the task body blocks immediately on the @cite{accept}
34096 statement. Now of course there is nothing to prohibit elaboration
34097 code from making entry calls (for example from another library level task),
34098 so we cannot tell in isolation that
34099 the task will not execute the accept statement during elaboration.
34101 However, in practice it is very unusual to see elaboration code
34102 make any entry calls, and the pattern of tasks starting
34103 at elaboration time and then immediately blocking on @cite{accept} or
34104 @cite{select} statements is very common. What this means is that
34105 the compiler is being too pessimistic when it analyzes the
34106 whole package body as though it might be executed at elaboration
34109 If we know that the elaboration code contains no entry calls, (a very safe
34110 assumption most of the time, that could almost be made the default
34111 behavior), then we can compile all units of the program under control
34112 of the following configuration pragma:
34115 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
34118 This pragma can be placed in the @code{gnat.adc} file in the usual
34119 manner. If we take our original unmodified program and compile it
34120 in the presence of a @code{gnat.adc} containing the above pragma,
34121 then once again, we can compile, bind, link, and execute, obtaining
34122 the expected result. In the presence of this pragma, the compiler does
34123 not trace calls in a task body, that appear after the first @cite{accept}
34124 or @cite{select} statement, and therefore does not report a potential
34125 circularity in the original program.
34127 The compiler will check to the extent it can that the above
34128 restriction is not violated, but it is not always possible to do a
34129 complete check at compile time, so it is important to use this
34130 pragma only if the stated restriction is in fact met, that is to say
34131 no task receives an entry call before elaboration of all units is completed.
34134 @node Mixing Elaboration Models,What to Do If the Default Elaboration Behavior Fails,Elaboration Issues for Library Tasks,Elaboration Order Handling in GNAT
34135 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id10}@anchor{2c1}@anchor{gnat_ugn/elaboration_order_handling_in_gnat mixing-elaboration-models}@anchor{2c2}
34136 @section Mixing Elaboration Models
34139 So far, we have assumed that the entire program is either compiled
34140 using the dynamic model or static model, ensuring consistency. It
34141 is possible to mix the two models, but rules have to be followed
34142 if this mixing is done to ensure that elaboration checks are not
34145 The basic rule is that
34146 @strong{a unit compiled with the static model cannot
34147 be |withed| by a unit compiled with the dynamic model}.
34148 The reason for this is that in the static model, a unit assumes that
34149 its clients guarantee to use (the equivalent of) pragma
34150 @cite{Elaborate_All} so that no elaboration checks are required
34151 in inner subprograms, and this assumption is violated if the
34152 client is compiled with dynamic checks.
34154 The precise rule is as follows. A unit that is compiled with dynamic
34155 checks can only @emph{with} a unit that meets at least one of the
34156 following criteria:
34162 The @emph{with}ed unit is itself compiled with dynamic elaboration
34163 checks (that is with the @emph{-gnatE} switch.
34166 The @emph{with}ed unit is an internal GNAT implementation unit from
34167 the System, Interfaces, Ada, or GNAT hierarchies.
34170 The @emph{with}ed unit has pragma Preelaborate or pragma Pure.
34173 The @emph{with}ing unit (that is the client) has an explicit pragma
34174 @cite{Elaborate_All} for the @emph{with}ed unit.
34177 If this rule is violated, that is if a unit with dynamic elaboration
34178 checks @emph{with}s a unit that does not meet one of the above four
34179 criteria, then the binder (@cite{gnatbind}) will issue a warning
34180 similar to that in the following example:
34183 warning: "x.ads" has dynamic elaboration checks and with's
34184 warning: "y.ads" which has static elaboration checks
34187 These warnings indicate that the rule has been violated, and that as a result
34188 elaboration checks may be missed in the resulting executable file.
34189 This warning may be suppressed using the @emph{-ws} binder switch
34190 in the usual manner.
34192 One useful application of this mixing rule is in the case of a subsystem
34193 which does not itself @emph{with} units from the remainder of the
34194 application. In this case, the entire subsystem can be compiled with
34195 dynamic checks to resolve a circularity in the subsystem, while
34196 allowing the main application that uses this subsystem to be compiled
34197 using the more reliable default static model.
34199 @node What to Do If the Default Elaboration Behavior Fails,Elaboration for Indirect Calls,Mixing Elaboration Models,Elaboration Order Handling in GNAT
34200 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id11}@anchor{2c3}@anchor{gnat_ugn/elaboration_order_handling_in_gnat what-to-do-if-the-default-elaboration-behavior-fails}@anchor{2bc}
34201 @section What to Do If the Default Elaboration Behavior Fails
34204 If the binder cannot find an acceptable order, it outputs detailed
34205 diagnostics. For example:
34208 error: elaboration circularity detected
34209 info: "proc (body)" must be elaborated before "pack (body)"
34210 info: reason: Elaborate_All probably needed in unit "pack (body)"
34211 info: recompile "pack (body)" with -gnatel
34212 info: for full details
34213 info: "proc (body)"
34214 info: is needed by its spec:
34215 info: "proc (spec)"
34216 info: which is withed by:
34217 info: "pack (body)"
34218 info: "pack (body)" must be elaborated before "proc (body)"
34219 info: reason: pragma Elaborate in unit "proc (body)"
34222 In this case we have a cycle that the binder cannot break. On the one
34223 hand, there is an explicit pragma Elaborate in @cite{proc} for
34224 @cite{pack}. This means that the body of @cite{pack} must be elaborated
34225 before the body of @cite{proc}. On the other hand, there is elaboration
34226 code in @cite{pack} that calls a subprogram in @cite{proc}. This means
34227 that for maximum safety, there should really be a pragma
34228 Elaborate_All in @cite{pack} for @cite{proc} which would require that
34229 the body of @cite{proc} be elaborated before the body of
34230 @cite{pack}. Clearly both requirements cannot be satisfied.
34231 Faced with a circularity of this kind, you have three different options.
34237 @emph{Fix the program}
34239 The most desirable option from the point of view of long-term maintenance
34240 is to rearrange the program so that the elaboration problems are avoided.
34241 One useful technique is to place the elaboration code into separate
34242 child packages. Another is to move some of the initialization code to
34243 explicitly called subprograms, where the program controls the order
34244 of initialization explicitly. Although this is the most desirable option,
34245 it may be impractical and involve too much modification, especially in
34246 the case of complex legacy code.
34249 @emph{Perform dynamic checks}
34251 If the compilations are done using the @emph{-gnatE}
34252 (dynamic elaboration check) switch, then GNAT behaves in a quite different
34253 manner. Dynamic checks are generated for all calls that could possibly result
34254 in raising an exception. With this switch, the compiler does not generate
34255 implicit @cite{Elaborate} or @cite{Elaborate_All} pragmas. The behavior then is
34256 exactly as specified in the @cite{Ada Reference Manual}.
34257 The binder will generate
34258 an executable program that may or may not raise @cite{Program_Error}, and then
34259 it is the programmer's job to ensure that it does not raise an exception. Note
34260 that it is important to compile all units with the switch, it cannot be used
34264 @emph{Suppress checks}
34266 The drawback of dynamic checks is that they generate a
34267 significant overhead at run time, both in space and time. If you
34268 are absolutely sure that your program cannot raise any elaboration
34269 exceptions, and you still want to use the dynamic elaboration model,
34270 then you can use the configuration pragma
34271 @cite{Suppress (Elaboration_Check)} to suppress all such checks. For
34272 example this pragma could be placed in the @code{gnat.adc} file.
34275 @emph{Suppress checks selectively}
34277 When you know that certain calls or instantiations in elaboration code cannot
34278 possibly lead to an elaboration error, and the binder nevertheless complains
34279 about implicit @cite{Elaborate} and @cite{Elaborate_All} pragmas that lead to
34280 elaboration circularities, it is possible to remove those warnings locally and
34281 obtain a program that will bind. Clearly this can be unsafe, and it is the
34282 responsibility of the programmer to make sure that the resulting program has no
34283 elaboration anomalies. The pragma @cite{Suppress (Elaboration_Check)} can be
34284 used with different granularity to suppress warnings and break elaboration
34291 Place the pragma that names the called subprogram in the declarative part
34292 that contains the call.
34295 Place the pragma in the declarative part, without naming an entity. This
34296 disables warnings on all calls in the corresponding declarative region.
34299 Place the pragma in the package spec that declares the called subprogram,
34300 and name the subprogram. This disables warnings on all elaboration calls to
34304 Place the pragma in the package spec that declares the called subprogram,
34305 without naming any entity. This disables warnings on all elaboration calls to
34306 all subprograms declared in this spec.
34309 Use Pragma Elaborate.
34311 As previously described in section @ref{2bd,,Treatment of Pragma Elaborate},
34312 GNAT in static mode assumes that a @cite{pragma} Elaborate indicates correctly
34313 that no elaboration checks are required on calls to the designated unit.
34314 There may be cases in which the caller knows that no transitive calls
34315 can occur, so that a @cite{pragma Elaborate} will be sufficient in a
34316 case where @cite{pragma Elaborate_All} would cause a circularity.
34319 These five cases are listed in order of decreasing safety, and therefore
34320 require increasing programmer care in their application. Consider the
34325 function F1 return Integer;
34330 function F2 return Integer;
34331 function Pure (x : integer) return integer;
34332 -- pragma Suppress (Elaboration_Check, On => Pure); -- (3)
34333 -- pragma Suppress (Elaboration_Check); -- (4)
34337 package body Pack1 is
34338 function F1 return Integer is
34342 Val : integer := Pack2.Pure (11); -- Elab. call (1)
34345 -- pragma Suppress(Elaboration_Check, Pack2.F2); -- (1)
34346 -- pragma Suppress(Elaboration_Check); -- (2)
34348 X1 := Pack2.F2 + 1; -- Elab. call (2)
34353 package body Pack2 is
34354 function F2 return Integer is
34358 function Pure (x : integer) return integer is
34360 return x ** 3 - 3 * x;
34364 with Pack1, Ada.Text_IO;
34367 Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
34371 In the absence of any pragmas, an attempt to bind this program produces
34372 the following diagnostics:
34375 error: elaboration circularity detected
34376 info: "pack1 (body)" must be elaborated before "pack1 (body)"
34377 info: reason: Elaborate_All probably needed in unit "pack1 (body)"
34378 info: recompile "pack1 (body)" with -gnatel for full details
34379 info: "pack1 (body)"
34380 info: must be elaborated along with its spec:
34381 info: "pack1 (spec)"
34382 info: which is withed by:
34383 info: "pack2 (body)"
34384 info: which must be elaborated along with its spec:
34385 info: "pack2 (spec)"
34386 info: which is withed by:
34387 info: "pack1 (body)"
34390 The sources of the circularity are the two calls to @cite{Pack2.Pure} and
34391 @cite{Pack2.F2} in the body of @cite{Pack1}. We can see that the call to
34392 F2 is safe, even though F2 calls F1, because the call appears after the
34393 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
34394 remove the warning on the call. It is also possible to use pragma (2)
34395 because there are no other potentially unsafe calls in the block.
34397 The call to @cite{Pure} is safe because this function does not depend on the
34398 state of @cite{Pack2}. Therefore any call to this function is safe, and it
34399 is correct to place pragma (3) in the corresponding package spec.
34401 Finally, we could place pragma (4) in the spec of @cite{Pack2} to disable
34402 warnings on all calls to functions declared therein. Note that this is not
34403 necessarily safe, and requires more detailed examination of the subprogram
34404 bodies involved. In particular, a call to @cite{F2} requires that @cite{F1}
34405 be already elaborated.
34408 It is hard to generalize on which of these four approaches should be
34409 taken. Obviously if it is possible to fix the program so that the default
34410 treatment works, this is preferable, but this may not always be practical.
34411 It is certainly simple enough to use @emph{-gnatE}
34412 but the danger in this case is that, even if the GNAT binder
34413 finds a correct elaboration order, it may not always do so,
34414 and certainly a binder from another Ada compiler might not. A
34415 combination of testing and analysis (for which the
34416 information messages generated with the @emph{-gnatel}
34417 switch can be useful) must be used to ensure that the program is free
34418 of errors. One switch that is useful in this testing is the
34419 @emph{-p (pessimistic elaboration order)} switch for @cite{gnatbind}.
34420 Normally the binder tries to find an order that has the best chance
34421 of avoiding elaboration problems. However, if this switch is used, the binder
34422 plays a devil's advocate role, and tries to choose the order that
34423 has the best chance of failing. If your program works even with this
34424 switch, then it has a better chance of being error free, but this is still
34427 For an example of this approach in action, consider the C-tests (executable
34428 tests) from the ACATS suite. If these are compiled and run with the default
34429 treatment, then all but one of them succeed without generating any error
34430 diagnostics from the binder. However, there is one test that fails, and
34431 this is not surprising, because the whole point of this test is to ensure
34432 that the compiler can handle cases where it is impossible to determine
34433 a correct order statically, and it checks that an exception is indeed
34434 raised at run time.
34436 This one test must be compiled and run using the @emph{-gnatE}
34437 switch, and then it passes. Alternatively, the entire suite can
34438 be run using this switch. It is never wrong to run with the dynamic
34439 elaboration switch if your code is correct, and we assume that the
34440 C-tests are indeed correct (it is less efficient, but efficiency is
34441 not a factor in running the ACATS tests.)
34443 @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
34444 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id12}@anchor{2c4}@anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-for-indirect-calls}@anchor{2c5}
34445 @section Elaboration for Indirect Calls
34448 @geindex Dispatching calls
34450 @geindex Indirect calls
34452 In rare cases, the static elaboration model fails to prevent
34453 dispatching calls to not-yet-elaborated subprograms. In such cases, we
34454 fall back to run-time checks; premature calls to any primitive
34455 operation of a tagged type before the body of the operation has been
34456 elaborated will raise @cite{Program_Error}.
34458 Access-to-subprogram types, however, are handled conservatively, and
34459 do not require run-time checks. This was not true in earlier versions
34460 of the compiler; you can use the @emph{-gnatd.U} debug switch to
34461 revert to the old behavior if the new conservative behavior causes
34462 elaboration cycles. Here, 'conservative' means that if you do
34463 @cite{P'Access} during elaboration, the compiler will assume that you
34464 might call @cite{P} indirectly during elaboration, so it adds an
34465 implicit @cite{pragma Elaborate_All} on the library unit containing
34466 @cite{P}. The @emph{-gnatd.U} switch is safe if you know there are
34467 no such calls. If the program worked before, it will continue to work
34468 with @emph{-gnatd.U}. But beware that code modifications such as
34469 adding an indirect call can cause erroneous behavior in the presence
34470 of @emph{-gnatd.U}.
34472 @node Summary of Procedures for Elaboration Control,Other Elaboration Order Considerations,Elaboration for Indirect Calls,Elaboration Order Handling in GNAT
34473 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id13}@anchor{2c6}@anchor{gnat_ugn/elaboration_order_handling_in_gnat summary-of-procedures-for-elaboration-control}@anchor{2c7}
34474 @section Summary of Procedures for Elaboration Control
34477 @geindex Elaboration control
34479 First, compile your program with the default options, using none of
34480 the special elaboration control switches. If the binder successfully
34481 binds your program, then you can be confident that, apart from issues
34482 raised by the use of access-to-subprogram types and dynamic dispatching,
34483 the program is free of elaboration errors. If it is important that the
34484 program be portable to other compilers than GNAT, then use the
34486 switch to generate messages about missing @cite{Elaborate} or
34487 @cite{Elaborate_All} pragmas, and supply the missing pragmas.
34489 If the program fails to bind using the default static elaboration
34490 handling, then you can fix the program to eliminate the binder
34491 message, or recompile the entire program with the
34492 @emph{-gnatE} switch to generate dynamic elaboration checks,
34493 and, if you are sure there really are no elaboration problems,
34494 use a global pragma @cite{Suppress (Elaboration_Check)}.
34496 @node Other Elaboration Order Considerations,Determining the Chosen Elaboration Order,Summary of Procedures for Elaboration Control,Elaboration Order Handling in GNAT
34497 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id14}@anchor{2c8}@anchor{gnat_ugn/elaboration_order_handling_in_gnat other-elaboration-order-considerations}@anchor{2c9}
34498 @section Other Elaboration Order Considerations
34501 This section has been entirely concerned with the issue of finding a valid
34502 elaboration order, as defined by the Ada Reference Manual. In a case
34503 where several elaboration orders are valid, the task is to find one
34504 of the possible valid elaboration orders (and the static model in GNAT
34505 will ensure that this is achieved).
34507 The purpose of the elaboration rules in the Ada Reference Manual is to
34508 make sure that no entity is accessed before it has been elaborated. For
34509 a subprogram, this means that the spec and body must have been elaborated
34510 before the subprogram is called. For an object, this means that the object
34511 must have been elaborated before its value is read or written. A violation
34512 of either of these two requirements is an access before elaboration order,
34513 and this section has been all about avoiding such errors.
34515 In the case where more than one order of elaboration is possible, in the
34516 sense that access before elaboration errors are avoided, then any one of
34517 the orders is 'correct' in the sense that it meets the requirements of
34518 the Ada Reference Manual, and no such error occurs.
34520 However, it may be the case for a given program, that there are
34521 constraints on the order of elaboration that come not from consideration
34522 of avoiding elaboration errors, but rather from extra-lingual logic
34523 requirements. Consider this example:
34526 with Init_Constants;
34527 package Constants is
34532 package Init_Constants is
34533 procedure P; --* require a body*
34534 end Init_Constants;
34537 package body Init_Constants is
34538 procedure P is begin null; end;
34542 end Init_Constants;
34546 Z : Integer := Constants.X + Constants.Y;
34550 with Text_IO; use Text_IO;
34553 Put_Line (Calc.Z'Img);
34557 In this example, there is more than one valid order of elaboration. For
34558 example both the following are correct orders:
34561 Init_Constants spec
34564 Init_Constants body
34571 Init_Constants spec
34572 Init_Constants body
34578 There is no language rule to prefer one or the other, both are correct
34579 from an order of elaboration point of view. But the programmatic effects
34580 of the two orders are very different. In the first, the elaboration routine
34581 of @cite{Calc} initializes @cite{Z} to zero, and then the main program
34582 runs with this value of zero. But in the second order, the elaboration
34583 routine of @cite{Calc} runs after the body of Init_Constants has set
34584 @cite{X} and @cite{Y} and thus @cite{Z} is set to 7 before @cite{Main} runs.
34586 One could perhaps by applying pretty clever non-artificial intelligence
34587 to the situation guess that it is more likely that the second order of
34588 elaboration is the one desired, but there is no formal linguistic reason
34589 to prefer one over the other. In fact in this particular case, GNAT will
34590 prefer the second order, because of the rule that bodies are elaborated
34591 as soon as possible, but it's just luck that this is what was wanted
34592 (if indeed the second order was preferred).
34594 If the program cares about the order of elaboration routines in a case like
34595 this, it is important to specify the order required. In this particular
34596 case, that could have been achieved by adding to the spec of Calc:
34599 pragma Elaborate_All (Constants);
34602 which requires that the body (if any) and spec of @cite{Constants},
34603 as well as the body and spec of any unit @emph{with}ed by
34604 @cite{Constants} be elaborated before @cite{Calc} is elaborated.
34606 Clearly no automatic method can always guess which alternative you require,
34607 and if you are working with legacy code that had constraints of this kind
34608 which were not properly specified by adding @cite{Elaborate} or
34609 @cite{Elaborate_All} pragmas, then indeed it is possible that two different
34610 compilers can choose different orders.
34612 However, GNAT does attempt to diagnose the common situation where there
34613 are uninitialized variables in the visible part of a package spec, and the
34614 corresponding package body has an elaboration block that directly or
34615 indirectly initialized one or more of these variables. This is the situation
34616 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
34617 a warning that suggests this addition if it detects this situation.
34619 The @cite{gnatbind} @emph{-p} switch may be useful in smoking
34620 out problems. This switch causes bodies to be elaborated as late as possible
34621 instead of as early as possible. In the example above, it would have forced
34622 the choice of the first elaboration order. If you get different results
34623 when using this switch, and particularly if one set of results is right,
34624 and one is wrong as far as you are concerned, it shows that you have some
34625 missing @cite{Elaborate} pragmas. For the example above, we have the
34629 $ gnatmake -f -q main
34632 $ gnatmake -f -q main -bargs -p
34637 It is of course quite unlikely that both these results are correct, so
34638 it is up to you in a case like this to investigate the source of the
34639 difference, by looking at the two elaboration orders that are chosen,
34640 and figuring out which is correct, and then adding the necessary
34641 @cite{Elaborate} or @cite{Elaborate_All} pragmas to ensure the desired order.
34643 @node Determining the Chosen Elaboration Order,,Other Elaboration Order Considerations,Elaboration Order Handling in GNAT
34644 @anchor{gnat_ugn/elaboration_order_handling_in_gnat determining-the-chosen-elaboration-order}@anchor{2ca}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id15}@anchor{2cb}
34645 @section Determining the Chosen Elaboration Order
34648 To see the elaboration order that the binder chooses, you can look at
34649 the last part of the file:@cite{b~xxx.adb} binder output file. Here is an example:
34652 System.Soft_Links'Elab_Body;
34654 System.Secondary_Stack'Elab_Body;
34656 System.Exception_Table'Elab_Body;
34658 Ada.Io_Exceptions'Elab_Spec;
34660 Ada.Tags'Elab_Spec;
34661 Ada.Streams'Elab_Spec;
34663 Interfaces.C'Elab_Spec;
34665 System.Finalization_Root'Elab_Spec;
34667 System.Os_Lib'Elab_Body;
34669 System.Finalization_Implementation'Elab_Spec;
34670 System.Finalization_Implementation'Elab_Body;
34672 Ada.Finalization'Elab_Spec;
34674 Ada.Finalization.List_Controller'Elab_Spec;
34676 System.File_Control_Block'Elab_Spec;
34678 System.File_Io'Elab_Body;
34680 Ada.Tags'Elab_Body;
34682 Ada.Text_Io'Elab_Spec;
34683 Ada.Text_Io'Elab_Body;
34687 Here Elab_Spec elaborates the spec
34688 and Elab_Body elaborates the body. The assignments to the @code{E@emph{xx}} flags
34689 flag that the corresponding body is now elaborated.
34691 You can also ask the binder to generate a more
34692 readable list of the elaboration order using the
34693 @cite{-l} switch when invoking the binder. Here is
34694 an example of the output generated by this switch:
34700 system.case_util (spec)
34701 system.case_util (body)
34702 system.concat_2 (spec)
34703 system.concat_2 (body)
34704 system.concat_3 (spec)
34705 system.concat_3 (body)
34706 system.htable (spec)
34707 system.parameters (spec)
34708 system.parameters (body)
34710 interfaces.c_streams (spec)
34711 interfaces.c_streams (body)
34712 system.restrictions (spec)
34713 system.restrictions (body)
34714 system.standard_library (spec)
34715 system.exceptions (spec)
34716 system.exceptions (body)
34717 system.storage_elements (spec)
34718 system.storage_elements (body)
34719 system.secondary_stack (spec)
34720 system.stack_checking (spec)
34721 system.stack_checking (body)
34722 system.string_hash (spec)
34723 system.string_hash (body)
34724 system.htable (body)
34725 system.strings (spec)
34726 system.strings (body)
34727 system.traceback (spec)
34728 system.traceback (body)
34729 system.traceback_entries (spec)
34730 system.traceback_entries (body)
34731 ada.exceptions (spec)
34732 ada.exceptions.last_chance_handler (spec)
34733 system.soft_links (spec)
34734 system.soft_links (body)
34735 ada.exceptions.last_chance_handler (body)
34736 system.secondary_stack (body)
34737 system.exception_table (spec)
34738 system.exception_table (body)
34739 ada.io_exceptions (spec)
34742 interfaces.c (spec)
34743 interfaces.c (body)
34744 system.finalization_root (spec)
34745 system.finalization_root (body)
34746 system.memory (spec)
34747 system.memory (body)
34748 system.standard_library (body)
34749 system.os_lib (spec)
34750 system.os_lib (body)
34751 system.unsigned_types (spec)
34752 system.stream_attributes (spec)
34753 system.stream_attributes (body)
34754 system.finalization_implementation (spec)
34755 system.finalization_implementation (body)
34756 ada.finalization (spec)
34757 ada.finalization (body)
34758 ada.finalization.list_controller (spec)
34759 ada.finalization.list_controller (body)
34760 system.file_control_block (spec)
34761 system.file_io (spec)
34762 system.file_io (body)
34763 system.val_uns (spec)
34764 system.val_util (spec)
34765 system.val_util (body)
34766 system.val_uns (body)
34767 system.wch_con (spec)
34768 system.wch_con (body)
34769 system.wch_cnv (spec)
34770 system.wch_jis (spec)
34771 system.wch_jis (body)
34772 system.wch_cnv (body)
34773 system.wch_stw (spec)
34774 system.wch_stw (body)
34776 ada.exceptions (body)
34783 @node Inline Assembler,GNU Free Documentation License,Elaboration Order Handling in GNAT,Top
34784 @anchor{gnat_ugn/inline_assembler inline-assembler}@anchor{12}@anchor{gnat_ugn/inline_assembler doc}@anchor{2cc}@anchor{gnat_ugn/inline_assembler id1}@anchor{2cd}
34785 @chapter Inline Assembler
34788 @geindex Inline Assembler
34790 If you need to write low-level software that interacts directly
34791 with the hardware, Ada provides two ways to incorporate assembly
34792 language code into your program. First, you can import and invoke
34793 external routines written in assembly language, an Ada feature fully
34794 supported by GNAT. However, for small sections of code it may be simpler
34795 or more efficient to include assembly language statements directly
34796 in your Ada source program, using the facilities of the implementation-defined
34797 package @cite{System.Machine_Code}, which incorporates the gcc
34798 Inline Assembler. The Inline Assembler approach offers a number of advantages,
34799 including the following:
34805 No need to use non-Ada tools
34808 Consistent interface over different targets
34811 Automatic usage of the proper calling conventions
34814 Access to Ada constants and variables
34817 Definition of intrinsic routines
34820 Possibility of inlining a subprogram comprising assembler code
34823 Code optimizer can take Inline Assembler code into account
34826 This appendix presents a series of examples to show you how to use
34827 the Inline Assembler. Although it focuses on the Intel x86,
34828 the general approach applies also to other processors.
34829 It is assumed that you are familiar with Ada
34830 and with assembly language programming.
34833 * Basic Assembler Syntax::
34834 * A Simple Example of Inline Assembler::
34835 * Output Variables in Inline Assembler::
34836 * Input Variables in Inline Assembler::
34837 * Inlining Inline Assembler Code::
34838 * Other Asm Functionality::
34842 @node Basic Assembler Syntax,A Simple Example of Inline Assembler,,Inline Assembler
34843 @anchor{gnat_ugn/inline_assembler id2}@anchor{2ce}@anchor{gnat_ugn/inline_assembler basic-assembler-syntax}@anchor{2cf}
34844 @section Basic Assembler Syntax
34847 The assembler used by GNAT and gcc is based not on the Intel assembly
34848 language, but rather on a language that descends from the AT&T Unix
34849 assembler @emph{as} (and which is often referred to as 'AT&T syntax').
34850 The following table summarizes the main features of @emph{as} syntax
34851 and points out the differences from the Intel conventions.
34852 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
34853 pre-processor) documentation for further information.
34857 @emph{Register names}@w{ }
34859 gcc / @emph{as}: Prefix with '%'; for example @cite{%eax}@w{ }
34860 Intel: No extra punctuation; for example @cite{eax}@w{ }
34868 @emph{Immediate operand}@w{ }
34870 gcc / @emph{as}: Prefix with '$'; for example @cite{$4}@w{ }
34871 Intel: No extra punctuation; for example @cite{4}@w{ }
34879 @emph{Address}@w{ }
34881 gcc / @emph{as}: Prefix with '$'; for example @cite{$loc}@w{ }
34882 Intel: No extra punctuation; for example @cite{loc}@w{ }
34890 @emph{Memory contents}@w{ }
34892 gcc / @emph{as}: No extra punctuation; for example @cite{loc}@w{ }
34893 Intel: Square brackets; for example @cite{[loc]}@w{ }
34901 @emph{Register contents}@w{ }
34903 gcc / @emph{as}: Parentheses; for example @cite{(%eax)}@w{ }
34904 Intel: Square brackets; for example @cite{[eax]}@w{ }
34912 @emph{Hexadecimal numbers}@w{ }
34914 gcc / @emph{as}: Leading '0x' (C language syntax); for example @cite{0xA0}@w{ }
34915 Intel: Trailing 'h'; for example @cite{A0h}@w{ }
34923 @emph{Operand size}@w{ }
34925 gcc / @emph{as}: Explicit in op code; for example @cite{movw} to move a 16-bit word@w{ }
34926 Intel: Implicit, deduced by assembler; for example @cite{mov}@w{ }
34934 @emph{Instruction repetition}@w{ }
34936 gcc / @emph{as}: Split into two lines; for example@w{ }
34941 Intel: Keep on one line; for example @cite{rep stosl}@w{ }
34949 @emph{Order of operands}@w{ }
34951 gcc / @emph{as}: Source first; for example @cite{movw $4@comma{} %eax}@w{ }
34952 Intel: Destination first; for example @cite{mov eax@comma{} 4}@w{ }
34958 @node A Simple Example of Inline Assembler,Output Variables in Inline Assembler,Basic Assembler Syntax,Inline Assembler
34959 @anchor{gnat_ugn/inline_assembler a-simple-example-of-inline-assembler}@anchor{2d0}@anchor{gnat_ugn/inline_assembler id3}@anchor{2d1}
34960 @section A Simple Example of Inline Assembler
34963 The following example will generate a single assembly language statement,
34964 @cite{nop}, which does nothing. Despite its lack of run-time effect,
34965 the example will be useful in illustrating the basics of
34966 the Inline Assembler facility.
34971 with System.Machine_Code; use System.Machine_Code;
34972 procedure Nothing is
34979 @cite{Asm} is a procedure declared in package @cite{System.Machine_Code};
34980 here it takes one parameter, a @emph{template string} that must be a static
34981 expression and that will form the generated instruction.
34982 @cite{Asm} may be regarded as a compile-time procedure that parses
34983 the template string and additional parameters (none here),
34984 from which it generates a sequence of assembly language instructions.
34986 The examples in this chapter will illustrate several of the forms
34987 for invoking @cite{Asm}; a complete specification of the syntax
34988 is found in the @cite{Machine_Code_Insertions} section of the
34989 @cite{GNAT Reference Manual}.
34991 Under the standard GNAT conventions, the @cite{Nothing} procedure
34992 should be in a file named @code{nothing.adb}.
34993 You can build the executable in the usual way:
35002 However, the interesting aspect of this example is not its run-time behavior
35003 but rather the generated assembly code.
35004 To see this output, invoke the compiler as follows:
35009 $ gcc -c -S -fomit-frame-pointer -gnatp nothing.adb
35013 where the options are:
35024 compile only (no bind or link)
35033 generate assembler listing
35040 @item @code{-fomit-frame-pointer}
35042 do not set up separate stack frames
35049 @item @code{-gnatp}
35051 do not add runtime checks
35055 This gives a human-readable assembler version of the code. The resulting
35056 file will have the same name as the Ada source file, but with a @cite{.s}
35057 extension. In our example, the file @code{nothing.s} has the following
35063 .file "nothing.adb"
35065 ___gnu_compiled_ada:
35068 .globl __ada_nothing
35080 The assembly code you included is clearly indicated by
35081 the compiler, between the @cite{#APP} and @cite{#NO_APP}
35082 delimiters. The character before the 'APP' and 'NOAPP'
35083 can differ on different targets. For example, GNU/Linux uses '#APP' while
35084 on NT you will see '/APP'.
35086 If you make a mistake in your assembler code (such as using the
35087 wrong size modifier, or using a wrong operand for the instruction) GNAT
35088 will report this error in a temporary file, which will be deleted when
35089 the compilation is finished. Generating an assembler file will help
35090 in such cases, since you can assemble this file separately using the
35091 @emph{as} assembler that comes with gcc.
35093 Assembling the file using the command
35102 will give you error messages whose lines correspond to the assembler
35103 input file, so you can easily find and correct any mistakes you made.
35104 If there are no errors, @emph{as} will generate an object file
35105 @code{nothing.out}.
35107 @node Output Variables in Inline Assembler,Input Variables in Inline Assembler,A Simple Example of Inline Assembler,Inline Assembler
35108 @anchor{gnat_ugn/inline_assembler id4}@anchor{2d2}@anchor{gnat_ugn/inline_assembler output-variables-in-inline-assembler}@anchor{2d3}
35109 @section Output Variables in Inline Assembler
35112 The examples in this section, showing how to access the processor flags,
35113 illustrate how to specify the destination operands for assembly language
35119 with Interfaces; use Interfaces;
35120 with Ada.Text_IO; use Ada.Text_IO;
35121 with System.Machine_Code; use System.Machine_Code;
35122 procedure Get_Flags is
35123 Flags : Unsigned_32;
35126 Asm ("pushfl" & LF & HT & -- push flags on stack
35127 "popl %%eax" & LF & HT & -- load eax with flags
35128 "movl %%eax, %0", -- store flags in variable
35129 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
35130 Put_Line ("Flags register:" & Flags'Img);
35135 In order to have a nicely aligned assembly listing, we have separated
35136 multiple assembler statements in the Asm template string with linefeed
35137 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
35138 The resulting section of the assembly output file is:
35146 movl %eax, -40(%ebp)
35151 It would have been legal to write the Asm invocation as:
35156 Asm ("pushfl popl %%eax movl %%eax, %0")
35160 but in the generated assembler file, this would come out as:
35166 pushfl popl %eax movl %eax, -40(%ebp)
35171 which is not so convenient for the human reader.
35173 We use Ada comments
35174 at the end of each line to explain what the assembler instructions
35175 actually do. This is a useful convention.
35177 When writing Inline Assembler instructions, you need to precede each register
35178 and variable name with a percent sign. Since the assembler already requires
35179 a percent sign at the beginning of a register name, you need two consecutive
35180 percent signs for such names in the Asm template string, thus @cite{%%eax}.
35181 In the generated assembly code, one of the percent signs will be stripped off.
35183 Names such as @cite{%0}, @cite{%1}, @cite{%2}, etc., denote input or output
35184 variables: operands you later define using @cite{Input} or @cite{Output}
35185 parameters to @cite{Asm}.
35186 An output variable is illustrated in
35187 the third statement in the Asm template string:
35196 The intent is to store the contents of the eax register in a variable that can
35197 be accessed in Ada. Simply writing @cite{movl %%eax@comma{} Flags} would not
35198 necessarily work, since the compiler might optimize by using a register
35199 to hold Flags, and the expansion of the @cite{movl} instruction would not be
35200 aware of this optimization. The solution is not to store the result directly
35201 but rather to advise the compiler to choose the correct operand form;
35202 that is the purpose of the @cite{%0} output variable.
35204 Information about the output variable is supplied in the @cite{Outputs}
35205 parameter to @cite{Asm}:
35210 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
35214 The output is defined by the @cite{Asm_Output} attribute of the target type;
35215 the general format is
35220 Type'Asm_Output (constraint_string, variable_name)
35224 The constraint string directs the compiler how
35225 to store/access the associated variable. In the example
35230 Unsigned_32'Asm_Output ("=m", Flags);
35234 the @cite{"m"} (memory) constraint tells the compiler that the variable
35235 @cite{Flags} should be stored in a memory variable, thus preventing
35236 the optimizer from keeping it in a register. In contrast,
35241 Unsigned_32'Asm_Output ("=r", Flags);
35245 uses the @cite{"r"} (register) constraint, telling the compiler to
35246 store the variable in a register.
35248 If the constraint is preceded by the equal character '=', it tells
35249 the compiler that the variable will be used to store data into it.
35251 In the @cite{Get_Flags} example, we used the @cite{"g"} (global) constraint,
35252 allowing the optimizer to choose whatever it deems best.
35254 There are a fairly large number of constraints, but the ones that are
35255 most useful (for the Intel x86 processor) are the following:
35260 @multitable {xxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
35275 global (i.e., can be stored anywhere)
35347 use one of eax, ebx, ecx or edx
35355 use one of eax, ebx, ecx, edx, esi or edi
35361 The full set of constraints is described in the gcc and @emph{as}
35362 documentation; note that it is possible to combine certain constraints
35363 in one constraint string.
35365 You specify the association of an output variable with an assembler operand
35366 through the @code{%@emph{n}} notation, where @emph{n} is a non-negative
35372 Asm ("pushfl" & LF & HT & -- push flags on stack
35373 "popl %%eax" & LF & HT & -- load eax with flags
35374 "movl %%eax, %0", -- store flags in variable
35375 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
35379 @cite{%0} will be replaced in the expanded code by the appropriate operand,
35381 the compiler decided for the @cite{Flags} variable.
35383 In general, you may have any number of output variables:
35389 Count the operands starting at 0; thus @cite{%0}, @cite{%1}, etc.
35392 Specify the @cite{Outputs} parameter as a parenthesized comma-separated list
35393 of @cite{Asm_Output} attributes
35401 Asm ("movl %%eax, %0" & LF & HT &
35402 "movl %%ebx, %1" & LF & HT &
35404 Outputs => (Unsigned_32'Asm_Output ("=g", Var_A), -- %0 = Var_A
35405 Unsigned_32'Asm_Output ("=g", Var_B), -- %1 = Var_B
35406 Unsigned_32'Asm_Output ("=g", Var_C))); -- %2 = Var_C
35410 where @cite{Var_A}, @cite{Var_B}, and @cite{Var_C} are variables
35411 in the Ada program.
35413 As a variation on the @cite{Get_Flags} example, we can use the constraints
35414 string to direct the compiler to store the eax register into the @cite{Flags}
35415 variable, instead of including the store instruction explicitly in the
35416 @cite{Asm} template string:
35421 with Interfaces; use Interfaces;
35422 with Ada.Text_IO; use Ada.Text_IO;
35423 with System.Machine_Code; use System.Machine_Code;
35424 procedure Get_Flags_2 is
35425 Flags : Unsigned_32;
35428 Asm ("pushfl" & LF & HT & -- push flags on stack
35429 "popl %%eax", -- save flags in eax
35430 Outputs => Unsigned_32'Asm_Output ("=a", Flags));
35431 Put_Line ("Flags register:" & Flags'Img);
35436 The @cite{"a"} constraint tells the compiler that the @cite{Flags}
35437 variable will come from the eax register. Here is the resulting code:
35446 movl %eax,-40(%ebp)
35450 The compiler generated the store of eax into Flags after
35451 expanding the assembler code.
35453 Actually, there was no need to pop the flags into the eax register;
35454 more simply, we could just pop the flags directly into the program variable:
35459 with Interfaces; use Interfaces;
35460 with Ada.Text_IO; use Ada.Text_IO;
35461 with System.Machine_Code; use System.Machine_Code;
35462 procedure Get_Flags_3 is
35463 Flags : Unsigned_32;
35466 Asm ("pushfl" & LF & HT & -- push flags on stack
35467 "pop %0", -- save flags in Flags
35468 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
35469 Put_Line ("Flags register:" & Flags'Img);
35474 @node Input Variables in Inline Assembler,Inlining Inline Assembler Code,Output Variables in Inline Assembler,Inline Assembler
35475 @anchor{gnat_ugn/inline_assembler id5}@anchor{2d4}@anchor{gnat_ugn/inline_assembler input-variables-in-inline-assembler}@anchor{2d5}
35476 @section Input Variables in Inline Assembler
35479 The example in this section illustrates how to specify the source operands
35480 for assembly language statements.
35481 The program simply increments its input value by 1:
35486 with Interfaces; use Interfaces;
35487 with Ada.Text_IO; use Ada.Text_IO;
35488 with System.Machine_Code; use System.Machine_Code;
35489 procedure Increment is
35491 function Incr (Value : Unsigned_32) return Unsigned_32 is
35492 Result : Unsigned_32;
35495 Outputs => Unsigned_32'Asm_Output ("=a", Result),
35496 Inputs => Unsigned_32'Asm_Input ("a", Value));
35500 Value : Unsigned_32;
35504 Put_Line ("Value before is" & Value'Img);
35505 Value := Incr (Value);
35506 Put_Line ("Value after is" & Value'Img);
35511 The @cite{Outputs} parameter to @cite{Asm} specifies
35512 that the result will be in the eax register and that it is to be stored
35513 in the @cite{Result} variable.
35515 The @cite{Inputs} parameter looks much like the @cite{Outputs} parameter,
35516 but with an @cite{Asm_Input} attribute.
35517 The @cite{"="} constraint, indicating an output value, is not present.
35519 You can have multiple input variables, in the same way that you can have more
35520 than one output variable.
35522 The parameter count (%0, %1) etc, still starts at the first output statement,
35523 and continues with the input statements.
35525 Just as the @cite{Outputs} parameter causes the register to be stored into the
35526 target variable after execution of the assembler statements, so does the
35527 @cite{Inputs} parameter cause its variable to be loaded into the register
35528 before execution of the assembler statements.
35530 Thus the effect of the @cite{Asm} invocation is:
35536 load the 32-bit value of @cite{Value} into eax
35539 execute the @cite{incl %eax} instruction
35542 store the contents of eax into the @cite{Result} variable
35545 The resulting assembler file (with @emph{-O2} optimization) contains:
35550 _increment__incr.1:
35563 @node Inlining Inline Assembler Code,Other Asm Functionality,Input Variables in Inline Assembler,Inline Assembler
35564 @anchor{gnat_ugn/inline_assembler id6}@anchor{2d6}@anchor{gnat_ugn/inline_assembler inlining-inline-assembler-code}@anchor{2d7}
35565 @section Inlining Inline Assembler Code
35568 For a short subprogram such as the @cite{Incr} function in the previous
35569 section, the overhead of the call and return (creating / deleting the stack
35570 frame) can be significant, compared to the amount of code in the subprogram
35571 body. A solution is to apply Ada's @cite{Inline} pragma to the subprogram,
35572 which directs the compiler to expand invocations of the subprogram at the
35573 point(s) of call, instead of setting up a stack frame for out-of-line calls.
35574 Here is the resulting program:
35579 with Interfaces; use Interfaces;
35580 with Ada.Text_IO; use Ada.Text_IO;
35581 with System.Machine_Code; use System.Machine_Code;
35582 procedure Increment_2 is
35584 function Incr (Value : Unsigned_32) return Unsigned_32 is
35585 Result : Unsigned_32;
35588 Outputs => Unsigned_32'Asm_Output ("=a", Result),
35589 Inputs => Unsigned_32'Asm_Input ("a", Value));
35592 pragma Inline (Increment);
35594 Value : Unsigned_32;
35598 Put_Line ("Value before is" & Value'Img);
35599 Value := Increment (Value);
35600 Put_Line ("Value after is" & Value'Img);
35605 Compile the program with both optimization (@emph{-O2}) and inlining
35606 (@emph{-gnatn}) enabled.
35608 The @cite{Incr} function is still compiled as usual, but at the
35609 point in @cite{Increment} where our function used to be called:
35615 call _increment__incr.1
35619 the code for the function body directly appears:
35632 thus saving the overhead of stack frame setup and an out-of-line call.
35634 @node Other Asm Functionality,,Inlining Inline Assembler Code,Inline Assembler
35635 @anchor{gnat_ugn/inline_assembler other-asm-functionality}@anchor{2d8}@anchor{gnat_ugn/inline_assembler id7}@anchor{2d9}
35636 @section Other @cite{Asm} Functionality
35639 This section describes two important parameters to the @cite{Asm}
35640 procedure: @cite{Clobber}, which identifies register usage;
35641 and @cite{Volatile}, which inhibits unwanted optimizations.
35644 * The Clobber Parameter::
35645 * The Volatile Parameter::
35649 @node The Clobber Parameter,The Volatile Parameter,,Other Asm Functionality
35650 @anchor{gnat_ugn/inline_assembler the-clobber-parameter}@anchor{2da}@anchor{gnat_ugn/inline_assembler id8}@anchor{2db}
35651 @subsection The @cite{Clobber} Parameter
35654 One of the dangers of intermixing assembly language and a compiled language
35655 such as Ada is that the compiler needs to be aware of which registers are
35656 being used by the assembly code. In some cases, such as the earlier examples,
35657 the constraint string is sufficient to indicate register usage (e.g.,
35659 the eax register). But more generally, the compiler needs an explicit
35660 identification of the registers that are used by the Inline Assembly
35663 Using a register that the compiler doesn't know about
35664 could be a side effect of an instruction (like @cite{mull}
35665 storing its result in both eax and edx).
35666 It can also arise from explicit register usage in your
35667 assembly code; for example:
35672 Asm ("movl %0, %%ebx" & LF & HT &
35674 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
35675 Inputs => Unsigned_32'Asm_Input ("g", Var_In));
35679 where the compiler (since it does not analyze the @cite{Asm} template string)
35680 does not know you are using the ebx register.
35682 In such cases you need to supply the @cite{Clobber} parameter to @cite{Asm},
35683 to identify the registers that will be used by your assembly code:
35688 Asm ("movl %0, %%ebx" & LF & HT &
35690 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
35691 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
35696 The Clobber parameter is a static string expression specifying the
35697 register(s) you are using. Note that register names are @emph{not} prefixed
35698 by a percent sign. Also, if more than one register is used then their names
35699 are separated by commas; e.g., @cite{"eax@comma{} ebx"}
35701 The @cite{Clobber} parameter has several additional uses:
35707 Use 'register' name @cite{cc} to indicate that flags might have changed
35710 Use 'register' name @cite{memory} if you changed a memory location
35713 @node The Volatile Parameter,,The Clobber Parameter,Other Asm Functionality
35714 @anchor{gnat_ugn/inline_assembler the-volatile-parameter}@anchor{2dc}@anchor{gnat_ugn/inline_assembler id9}@anchor{2dd}
35715 @subsection The @cite{Volatile} Parameter
35718 @geindex Volatile parameter
35720 Compiler optimizations in the presence of Inline Assembler may sometimes have
35721 unwanted effects. For example, when an @cite{Asm} invocation with an input
35722 variable is inside a loop, the compiler might move the loading of the input
35723 variable outside the loop, regarding it as a one-time initialization.
35725 If this effect is not desired, you can disable such optimizations by setting
35726 the @cite{Volatile} parameter to @cite{True}; for example:
35731 Asm ("movl %0, %%ebx" & LF & HT &
35733 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
35734 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
35740 By default, @cite{Volatile} is set to @cite{False} unless there is no
35741 @cite{Outputs} parameter.
35743 Although setting @cite{Volatile} to @cite{True} prevents unwanted
35744 optimizations, it will also disable other optimizations that might be
35745 important for efficiency. In general, you should set @cite{Volatile}
35746 to @cite{True} only if the compiler's optimizations have created
35749 @node GNU Free Documentation License,Index,Inline Assembler,Top
35750 @anchor{share/gnu_free_documentation_license gnu-fdl}@anchor{1}@anchor{share/gnu_free_documentation_license doc}@anchor{2de}@anchor{share/gnu_free_documentation_license gnu-free-documentation-license}@anchor{2df}
35751 @chapter GNU Free Documentation License
35754 Version 1.3, 3 November 2008
35756 Copyright 2000, 2001, 2002, 2007, 2008 Free Software Foundation, Inc
35757 @indicateurl{http://fsf.org/}
35759 Everyone is permitted to copy and distribute verbatim copies of this
35760 license document, but changing it is not allowed.
35764 The purpose of this License is to make a manual, textbook, or other
35765 functional and useful document "free" in the sense of freedom: to
35766 assure everyone the effective freedom to copy and redistribute it,
35767 with or without modifying it, either commercially or noncommercially.
35768 Secondarily, this License preserves for the author and publisher a way
35769 to get credit for their work, while not being considered responsible
35770 for modifications made by others.
35772 This License is a kind of "copyleft", which means that derivative
35773 works of the document must themselves be free in the same sense. It
35774 complements the GNU General Public License, which is a copyleft
35775 license designed for free software.
35777 We have designed this License in order to use it for manuals for free
35778 software, because free software needs free documentation: a free
35779 program should come with manuals providing the same freedoms that the
35780 software does. But this License is not limited to software manuals;
35781 it can be used for any textual work, regardless of subject matter or
35782 whether it is published as a printed book. We recommend this License
35783 principally for works whose purpose is instruction or reference.
35785 @strong{1. APPLICABILITY AND DEFINITIONS}
35787 This License applies to any manual or other work, in any medium, that
35788 contains a notice placed by the copyright holder saying it can be
35789 distributed under the terms of this License. Such a notice grants a
35790 world-wide, royalty-free license, unlimited in duration, to use that
35791 work under the conditions stated herein. The @strong{Document}, below,
35792 refers to any such manual or work. Any member of the public is a
35793 licensee, and is addressed as "@strong{you}". You accept the license if you
35794 copy, modify or distribute the work in a way requiring permission
35795 under copyright law.
35797 A "@strong{Modified Version}" of the Document means any work containing the
35798 Document or a portion of it, either copied verbatim, or with
35799 modifications and/or translated into another language.
35801 A "@strong{Secondary Section}" is a named appendix or a front-matter section of
35802 the Document that deals exclusively with the relationship of the
35803 publishers or authors of the Document to the Document's overall subject
35804 (or to related matters) and contains nothing that could fall directly
35805 within that overall subject. (Thus, if the Document is in part a
35806 textbook of mathematics, a Secondary Section may not explain any
35807 mathematics.) The relationship could be a matter of historical
35808 connection with the subject or with related matters, or of legal,
35809 commercial, philosophical, ethical or political position regarding
35812 The "@strong{Invariant Sections}" are certain Secondary Sections whose titles
35813 are designated, as being those of Invariant Sections, in the notice
35814 that says that the Document is released under this License. If a
35815 section does not fit the above definition of Secondary then it is not
35816 allowed to be designated as Invariant. The Document may contain zero
35817 Invariant Sections. If the Document does not identify any Invariant
35818 Sections then there are none.
35820 The "@strong{Cover Texts}" are certain short passages of text that are listed,
35821 as Front-Cover Texts or Back-Cover Texts, in the notice that says that
35822 the Document is released under this License. A Front-Cover Text may
35823 be at most 5 words, and a Back-Cover Text may be at most 25 words.
35825 A "@strong{Transparent}" copy of the Document means a machine-readable copy,
35826 represented in a format whose specification is available to the
35827 general public, that is suitable for revising the document
35828 straightforwardly with generic text editors or (for images composed of
35829 pixels) generic paint programs or (for drawings) some widely available
35830 drawing editor, and that is suitable for input to text formatters or
35831 for automatic translation to a variety of formats suitable for input
35832 to text formatters. A copy made in an otherwise Transparent file
35833 format whose markup, or absence of markup, has been arranged to thwart
35834 or discourage subsequent modification by readers is not Transparent.
35835 An image format is not Transparent if used for any substantial amount
35836 of text. A copy that is not "Transparent" is called @strong{Opaque}.
35838 Examples of suitable formats for Transparent copies include plain
35839 ASCII without markup, Texinfo input format, LaTeX input format, SGML
35840 or XML using a publicly available DTD, and standard-conforming simple
35841 HTML, PostScript or PDF designed for human modification. Examples of
35842 transparent image formats include PNG, XCF and JPG. Opaque formats
35843 include proprietary formats that can be read and edited only by
35844 proprietary word processors, SGML or XML for which the DTD and/or
35845 processing tools are not generally available, and the
35846 machine-generated HTML, PostScript or PDF produced by some word
35847 processors for output purposes only.
35849 The "@strong{Title Page}" means, for a printed book, the title page itself,
35850 plus such following pages as are needed to hold, legibly, the material
35851 this License requires to appear in the title page. For works in
35852 formats which do not have any title page as such, "Title Page" means
35853 the text near the most prominent appearance of the work's title,
35854 preceding the beginning of the body of the text.
35856 The "@strong{publisher}" means any person or entity that distributes
35857 copies of the Document to the public.
35859 A section "@strong{Entitled XYZ}" means a named subunit of the Document whose
35860 title either is precisely XYZ or contains XYZ in parentheses following
35861 text that translates XYZ in another language. (Here XYZ stands for a
35862 specific section name mentioned below, such as "@strong{Acknowledgements}",
35863 "@strong{Dedications}", "@strong{Endorsements}", or "@strong{History}".)
35864 To "@strong{Preserve the Title}"
35865 of such a section when you modify the Document means that it remains a
35866 section "Entitled XYZ" according to this definition.
35868 The Document may include Warranty Disclaimers next to the notice which
35869 states that this License applies to the Document. These Warranty
35870 Disclaimers are considered to be included by reference in this
35871 License, but only as regards disclaiming warranties: any other
35872 implication that these Warranty Disclaimers may have is void and has
35873 no effect on the meaning of this License.
35875 @strong{2. VERBATIM COPYING}
35877 You may copy and distribute the Document in any medium, either
35878 commercially or noncommercially, provided that this License, the
35879 copyright notices, and the license notice saying this License applies
35880 to the Document are reproduced in all copies, and that you add no other
35881 conditions whatsoever to those of this License. You may not use
35882 technical measures to obstruct or control the reading or further
35883 copying of the copies you make or distribute. However, you may accept
35884 compensation in exchange for copies. If you distribute a large enough
35885 number of copies you must also follow the conditions in section 3.
35887 You may also lend copies, under the same conditions stated above, and
35888 you may publicly display copies.
35890 @strong{3. COPYING IN QUANTITY}
35892 If you publish printed copies (or copies in media that commonly have
35893 printed covers) of the Document, numbering more than 100, and the
35894 Document's license notice requires Cover Texts, you must enclose the
35895 copies in covers that carry, clearly and legibly, all these Cover
35896 Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on
35897 the back cover. Both covers must also clearly and legibly identify
35898 you as the publisher of these copies. The front cover must present
35899 the full title with all words of the title equally prominent and
35900 visible. You may add other material on the covers in addition.
35901 Copying with changes limited to the covers, as long as they preserve
35902 the title of the Document and satisfy these conditions, can be treated
35903 as verbatim copying in other respects.
35905 If the required texts for either cover are too voluminous to fit
35906 legibly, you should put the first ones listed (as many as fit
35907 reasonably) on the actual cover, and continue the rest onto adjacent
35910 If you publish or distribute Opaque copies of the Document numbering
35911 more than 100, you must either include a machine-readable Transparent
35912 copy along with each Opaque copy, or state in or with each Opaque copy
35913 a computer-network location from which the general network-using
35914 public has access to download using public-standard network protocols
35915 a complete Transparent copy of the Document, free of added material.
35916 If you use the latter option, you must take reasonably prudent steps,
35917 when you begin distribution of Opaque copies in quantity, to ensure
35918 that this Transparent copy will remain thus accessible at the stated
35919 location until at least one year after the last time you distribute an
35920 Opaque copy (directly or through your agents or retailers) of that
35921 edition to the public.
35923 It is requested, but not required, that you contact the authors of the
35924 Document well before redistributing any large number of copies, to give
35925 them a chance to provide you with an updated version of the Document.
35927 @strong{4. MODIFICATIONS}
35929 You may copy and distribute a Modified Version of the Document under
35930 the conditions of sections 2 and 3 above, provided that you release
35931 the Modified Version under precisely this License, with the Modified
35932 Version filling the role of the Document, thus licensing distribution
35933 and modification of the Modified Version to whoever possesses a copy
35934 of it. In addition, you must do these things in the Modified Version:
35940 Use in the Title Page (and on the covers, if any) a title distinct
35941 from that of the Document, and from those of previous versions
35942 (which should, if there were any, be listed in the History section
35943 of the Document). You may use the same title as a previous version
35944 if the original publisher of that version gives permission.
35947 List on the Title Page, as authors, one or more persons or entities
35948 responsible for authorship of the modifications in the Modified
35949 Version, together with at least five of the principal authors of the
35950 Document (all of its principal authors, if it has fewer than five),
35951 unless they release you from this requirement.
35954 State on the Title page the name of the publisher of the
35955 Modified Version, as the publisher.
35958 Preserve all the copyright notices of the Document.
35961 Add an appropriate copyright notice for your modifications
35962 adjacent to the other copyright notices.
35965 Include, immediately after the copyright notices, a license notice
35966 giving the public permission to use the Modified Version under the
35967 terms of this License, in the form shown in the Addendum below.
35970 Preserve in that license notice the full lists of Invariant Sections
35971 and required Cover Texts given in the Document's license notice.
35974 Include an unaltered copy of this License.
35977 Preserve the section Entitled "History", Preserve its Title, and add
35978 to it an item stating at least the title, year, new authors, and
35979 publisher of the Modified Version as given on the Title Page. If
35980 there is no section Entitled "History" in the Document, create one
35981 stating the title, year, authors, and publisher of the Document as
35982 given on its Title Page, then add an item describing the Modified
35983 Version as stated in the previous sentence.
35986 Preserve the network location, if any, given in the Document for
35987 public access to a Transparent copy of the Document, and likewise
35988 the network locations given in the Document for previous versions
35989 it was based on. These may be placed in the "History" section.
35990 You may omit a network location for a work that was published at
35991 least four years before the Document itself, or if the original
35992 publisher of the version it refers to gives permission.
35995 For any section Entitled "Acknowledgements" or "Dedications",
35996 Preserve the Title of the section, and preserve in the section all
35997 the substance and tone of each of the contributor acknowledgements
35998 and/or dedications given therein.
36001 Preserve all the Invariant Sections of the Document,
36002 unaltered in their text and in their titles. Section numbers
36003 or the equivalent are not considered part of the section titles.
36006 Delete any section Entitled "Endorsements". Such a section
36007 may not be included in the Modified Version.
36010 Do not retitle any existing section to be Entitled "Endorsements"
36011 or to conflict in title with any Invariant Section.
36014 Preserve any Warranty Disclaimers.
36017 If the Modified Version includes new front-matter sections or
36018 appendices that qualify as Secondary Sections and contain no material
36019 copied from the Document, you may at your option designate some or all
36020 of these sections as invariant. To do this, add their titles to the
36021 list of Invariant Sections in the Modified Version's license notice.
36022 These titles must be distinct from any other section titles.
36024 You may add a section Entitled "Endorsements", provided it contains
36025 nothing but endorsements of your Modified Version by various
36026 parties---for example, statements of peer review or that the text has
36027 been approved by an organization as the authoritative definition of a
36030 You may add a passage of up to five words as a Front-Cover Text, and a
36031 passage of up to 25 words as a Back-Cover Text, to the end of the list
36032 of Cover Texts in the Modified Version. Only one passage of
36033 Front-Cover Text and one of Back-Cover Text may be added by (or
36034 through arrangements made by) any one entity. If the Document already
36035 includes a cover text for the same cover, previously added by you or
36036 by arrangement made by the same entity you are acting on behalf of,
36037 you may not add another; but you may replace the old one, on explicit
36038 permission from the previous publisher that added the old one.
36040 The author(s) and publisher(s) of the Document do not by this License
36041 give permission to use their names for publicity for or to assert or
36042 imply endorsement of any Modified Version.
36044 @strong{5. COMBINING DOCUMENTS}
36046 You may combine the Document with other documents released under this
36047 License, under the terms defined in section 4 above for modified
36048 versions, provided that you include in the combination all of the
36049 Invariant Sections of all of the original documents, unmodified, and
36050 list them all as Invariant Sections of your combined work in its
36051 license notice, and that you preserve all their Warranty Disclaimers.
36053 The combined work need only contain one copy of this License, and
36054 multiple identical Invariant Sections may be replaced with a single
36055 copy. If there are multiple Invariant Sections with the same name but
36056 different contents, make the title of each such section unique by
36057 adding at the end of it, in parentheses, the name of the original
36058 author or publisher of that section if known, or else a unique number.
36059 Make the same adjustment to the section titles in the list of
36060 Invariant Sections in the license notice of the combined work.
36062 In the combination, you must combine any sections Entitled "History"
36063 in the various original documents, forming one section Entitled
36064 "History"; likewise combine any sections Entitled "Acknowledgements",
36065 and any sections Entitled "Dedications". You must delete all sections
36066 Entitled "Endorsements".
36068 @strong{6. COLLECTIONS OF DOCUMENTS}
36070 You may make a collection consisting of the Document and other documents
36071 released under this License, and replace the individual copies of this
36072 License in the various documents with a single copy that is included in
36073 the collection, provided that you follow the rules of this License for
36074 verbatim copying of each of the documents in all other respects.
36076 You may extract a single document from such a collection, and distribute
36077 it individually under this License, provided you insert a copy of this
36078 License into the extracted document, and follow this License in all
36079 other respects regarding verbatim copying of that document.
36081 @strong{7. AGGREGATION WITH INDEPENDENT WORKS}
36083 A compilation of the Document or its derivatives with other separate
36084 and independent documents or works, in or on a volume of a storage or
36085 distribution medium, is called an "aggregate" if the copyright
36086 resulting from the compilation is not used to limit the legal rights
36087 of the compilation's users beyond what the individual works permit.
36088 When the Document is included in an aggregate, this License does not
36089 apply to the other works in the aggregate which are not themselves
36090 derivative works of the Document.
36092 If the Cover Text requirement of section 3 is applicable to these
36093 copies of the Document, then if the Document is less than one half of
36094 the entire aggregate, the Document's Cover Texts may be placed on
36095 covers that bracket the Document within the aggregate, or the
36096 electronic equivalent of covers if the Document is in electronic form.
36097 Otherwise they must appear on printed covers that bracket the whole
36100 @strong{8. TRANSLATION}
36102 Translation is considered a kind of modification, so you may
36103 distribute translations of the Document under the terms of section 4.
36104 Replacing Invariant Sections with translations requires special
36105 permission from their copyright holders, but you may include
36106 translations of some or all Invariant Sections in addition to the
36107 original versions of these Invariant Sections. You may include a
36108 translation of this License, and all the license notices in the
36109 Document, and any Warranty Disclaimers, provided that you also include
36110 the original English version of this License and the original versions
36111 of those notices and disclaimers. In case of a disagreement between
36112 the translation and the original version of this License or a notice
36113 or disclaimer, the original version will prevail.
36115 If a section in the Document is Entitled "Acknowledgements",
36116 "Dedications", or "History", the requirement (section 4) to Preserve
36117 its Title (section 1) will typically require changing the actual
36120 @strong{9. TERMINATION}
36122 You may not copy, modify, sublicense, or distribute the Document
36123 except as expressly provided under this License. Any attempt
36124 otherwise to copy, modify, sublicense, or distribute it is void, and
36125 will automatically terminate your rights under this License.
36127 However, if you cease all violation of this License, then your license
36128 from a particular copyright holder is reinstated (a) provisionally,
36129 unless and until the copyright holder explicitly and finally
36130 terminates your license, and (b) permanently, if the copyright holder
36131 fails to notify you of the violation by some reasonable means prior to
36132 60 days after the cessation.
36134 Moreover, your license from a particular copyright holder is
36135 reinstated permanently if the copyright holder notifies you of the
36136 violation by some reasonable means, this is the first time you have
36137 received notice of violation of this License (for any work) from that
36138 copyright holder, and you cure the violation prior to 30 days after
36139 your receipt of the notice.
36141 Termination of your rights under this section does not terminate the
36142 licenses of parties who have received copies or rights from you under
36143 this License. If your rights have been terminated and not permanently
36144 reinstated, receipt of a copy of some or all of the same material does
36145 not give you any rights to use it.
36147 @strong{10. FUTURE REVISIONS OF THIS LICENSE}
36149 The Free Software Foundation may publish new, revised versions
36150 of the GNU Free Documentation License from time to time. Such new
36151 versions will be similar in spirit to the present version, but may
36152 differ in detail to address new problems or concerns. See
36153 @indicateurl{http://www.gnu.org/copyleft/}.
36155 Each version of the License is given a distinguishing version number.
36156 If the Document specifies that a particular numbered version of this
36157 License "or any later version" applies to it, you have the option of
36158 following the terms and conditions either of that specified version or
36159 of any later version that has been published (not as a draft) by the
36160 Free Software Foundation. If the Document does not specify a version
36161 number of this License, you may choose any version ever published (not
36162 as a draft) by the Free Software Foundation. If the Document
36163 specifies that a proxy can decide which future versions of this
36164 License can be used, that proxy's public statement of acceptance of a
36165 version permanently authorizes you to choose that version for the
36168 @strong{11. RELICENSING}
36170 "Massive Multiauthor Collaboration Site" (or "MMC Site") means any
36171 World Wide Web server that publishes copyrightable works and also
36172 provides prominent facilities for anybody to edit those works. A
36173 public wiki that anybody can edit is an example of such a server. A
36174 "Massive Multiauthor Collaboration" (or "MMC") contained in the
36175 site means any set of copyrightable works thus published on the MMC
36178 "CC-BY-SA" means the Creative Commons Attribution-Share Alike 3.0
36179 license published by Creative Commons Corporation, a not-for-profit
36180 corporation with a principal place of business in San Francisco,
36181 California, as well as future copyleft versions of that license
36182 published by that same organization.
36184 "Incorporate" means to publish or republish a Document, in whole or
36185 in part, as part of another Document.
36187 An MMC is "eligible for relicensing" if it is licensed under this
36188 License, and if all works that were first published under this License
36189 somewhere other than this MMC, and subsequently incorporated in whole
36190 or in part into the MMC, (1) had no cover texts or invariant sections,
36191 and (2) were thus incorporated prior to November 1, 2008.
36193 The operator of an MMC Site may republish an MMC contained in the site
36194 under CC-BY-SA on the same site at any time before August 1, 2009,
36195 provided the MMC is eligible for relicensing.
36197 @strong{ADDENDUM: How to use this License for your documents}
36199 To use this License in a document you have written, include a copy of
36200 the License in the document and put the following copyright and
36201 license notices just after the title page:
36205 Copyright © YEAR YOUR NAME.
36206 Permission is granted to copy, distribute and/or modify this document
36207 under the terms of the GNU Free Documentation License, Version 1.3
36208 or any later version published by the Free Software Foundation;
36209 with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
36210 A copy of the license is included in the section entitled "GNU
36211 Free Documentation License".
36214 If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts,
36215 replace the "with ... Texts." line with this:
36219 with the Invariant Sections being LIST THEIR TITLES, with the
36220 Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST.
36223 If you have Invariant Sections without Cover Texts, or some other
36224 combination of the three, merge those two alternatives to suit the
36227 If your document contains nontrivial examples of program code, we
36228 recommend releasing these examples in parallel under your choice of
36229 free software license, such as the GNU General Public License,
36230 to permit their use in free software.
36232 @node Index,,GNU Free Documentation License,Top