1\input texinfo   @c -*-texinfo-*-
2@c %**start of header
3@setfilename gnat_ugn.info
4@documentencoding UTF-8
5@ifinfo
6@*Generated by Sphinx 1.3b2.@*
7@end ifinfo
8@settitle GNAT User's Guide for Native Platforms
9@defindex ge
10@paragraphindent 0
11@exampleindent 4
12@finalout
13@dircategory GNU Ada Tools
14@direntry
15* gnat_ugn: (gnat_ugn.info). gnat_ugn
16@end direntry
17
18@definfoenclose strong,`,'
19@definfoenclose emph,`,'
20@c %**end of header
21
22@copying
23@quotation
24GNAT User's Guide for Native Platforms , November 18, 2015
25
26AdaCore
27
28Copyright @copyright{} 2008-2016, Free Software Foundation
29@end quotation
30
31@end copying
32
33@titlepage
34@title GNAT User's Guide for Native Platforms
35@insertcopying
36@end titlepage
37@contents
38
39@c %** start of user preamble
40
41@c %** end of user preamble
42
43@ifnottex
44@node Top
45@top GNAT User's Guide for Native Platforms
46@insertcopying
47@end ifnottex
48
49@c %**start of body
50@anchor{gnat_ugn doc}@anchor{0}
51@emph{GNAT, The GNU Ada Development Environment}
52
53
54@include gcc-common.texi
55GCC version @value{version-GCC}@*
56AdaCore
57
58Permission is granted to copy, distribute and/or modify this document
59under the terms of the GNU Free Documentation License, Version 1.3 or
60any later version published by the Free Software Foundation; with no
61Invariant Sections, with the Front-Cover Texts being
62"GNAT User's Guide for Native Platforms",
63and with no Back-Cover Texts.  A copy of the license is
64included in the section entitled @ref{1,,GNU Free Documentation License}.
65
66@menu
67* About This Guide::
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::
78* Inline Assembler::
79* GNU Free Documentation License::
80* Index::
81
82@detailmenu
83 --- The Detailed Node Listing ---
84
85About This Guide
86
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::
91* Conventions::
92
93Getting Started with GNAT
94
95* Running GNAT::
96* Running a Simple Ada Program::
97* Running a Program with Multiple Units::
98* Using the gnatmake Utility::
99
100The GNAT Compilation Model
101
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::
115
116Foreign Language Representation
117
118* Latin-1::
119* Other 8-Bit Codes::
120* Wide_Character Encodings::
121* Wide_Wide_Character Encodings::
122
123File Naming Topics and Utilities
124
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::
131
132Handling Arbitrary File Naming Conventions with gnatname
133
134* Arbitrary File Naming Conventions::
135* Running gnatname::
136* Switches for gnatname::
137* Examples of gnatname Usage::
138
139File Name Krunching with gnatkr
140
141* About gnatkr::
142* Using gnatkr::
143* Krunching Method::
144* Examples of gnatkr Usage::
145
146Renaming Files with gnatchop
147
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::
153
154Configuration Pragmas
155
156* Handling of Configuration Pragmas::
157* The Configuration Pragmas Files::
158
159GNAT and Libraries
160
161* Introduction to Libraries in GNAT::
162* General Ada Libraries::
163* Stand-alone Ada Libraries::
164* Rebuilding the GNAT Run-Time Library::
165
166General Ada Libraries
167
168* Building a library::
169* Installing a library::
170* Using a library::
171
172Stand-alone Ada Libraries
173
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::
178
179Conditional Compilation
180
181* Modeling Conditional Compilation in Ada::
182* Preprocessing with gnatprep::
183* Integrated Preprocessing::
184
185Modeling Conditional Compilation in Ada
186
187* Use of Boolean Constants::
188* Debugging - A Special Case::
189* Conditionalizing Declarations::
190* Use of Alternative Implementations::
191* Preprocessing::
192
193Preprocessing with gnatprep
194
195* Preprocessing Symbols::
196* Using gnatprep::
197* Switches for gnatprep::
198* Form of Definitions File::
199* Form of Input Text for gnatprep::
200
201Mixed Language Programming
202
203* Interfacing to C::
204* Calling Conventions::
205* Building Mixed Ada and C++ Programs::
206* Generating Ada Bindings for C and C++ headers::
207* Generating C Headers for Ada Specifications::
208
209Building Mixed Ada and C++ Programs
210
211* Interfacing to C++::
212* Linking a Mixed C++ & Ada Program::
213* A Simple Example::
214* Interfacing with C++ constructors::
215* Interfacing with C++ at the Class Level::
216
217Generating Ada Bindings for C and C++ headers
218
219* Running the Binding Generator::
220* Generating Bindings for C++ Headers::
221* Switches::
222
223Generating C Headers for Ada Specifications
224
225* Running the C Header Generator::
226
227GNAT and Other Compilation Models
228
229* Comparison between GNAT and C/C++ Compilation Models::
230* Comparison between GNAT and Conventional Ada Library Models::
231
232Using GNAT Files with External Tools
233
234* Using Other Utility Programs with GNAT::
235* The External Symbol Naming Scheme of GNAT::
236
237Building Executable Programs with GNAT
238
239* Building with gnatmake::
240* Compiling with gcc::
241* Compiler Switches::
242* Binding with gnatbind::
243* Linking with gnatlink::
244* Using the GNU make Utility::
245
246Building with gnatmake
247
248* Running gnatmake::
249* Switches for gnatmake::
250* Mode Switches for gnatmake::
251* Notes on the Command Line::
252* How gnatmake Works::
253* Examples of gnatmake Usage::
254
255Compiling with gcc
256
257* Compiling Programs::
258* Search Paths and the Run-Time Library (RTL): Search Paths and the Run-Time Library RTL.
259* Order of Compilation Issues::
260* Examples::
261
262Compiler Switches
263
264* Alphabetical List of All Switches::
265* Output and Error Message Control::
266* Warning Message Control::
267* Debugging and Assertion Control::
268* Validity Checking::
269* Style Checking::
270* Run-Time Checks::
271* Using gcc for Syntax Checking::
272* Using gcc for Semantic Checking::
273* Compiling Different Versions of Ada::
274* Character Set Control::
275* File Naming Control::
276* Subprogram Inlining Control::
277* Auxiliary Output Control::
278* Debugging Control::
279* Exception Handling Control::
280* Units to Sources Mapping Files::
281* Code Generation Control::
282
283Binding with gnatbind
284
285* Running gnatbind::
286* Switches for gnatbind::
287* Command-Line Access::
288* Search Paths for gnatbind::
289* Examples of gnatbind Usage::
290
291Switches for gnatbind
292
293* Consistency-Checking Modes::
294* Binder Error Message Control::
295* Elaboration Control::
296* Output Control::
297* Dynamic Allocation Control::
298* Binding with Non-Ada Main Programs::
299* Binding Programs with No Main Subprogram::
300
301Linking with gnatlink
302
303* Running gnatlink::
304* Switches for gnatlink::
305
306Using the GNU make Utility
307
308* Using gnatmake in a Makefile::
309* Automatically Creating a List of Directories::
310* Generating the Command Line Switches::
311* Overcoming Command Line Length Limits::
312
313GNAT Project Manager
314
315* Introduction::
316* Building With Projects::
317* Organizing Projects into Subsystems::
318* Scenarios in Projects::
319* Library Projects::
320* Project Extension::
321* Aggregate Projects::
322* Aggregate Library Projects::
323* Project File Reference::
324
325Building With Projects
326
327* Source Files and Directories::
328* Duplicate Sources in Projects::
329* Object and Exec Directory::
330* Main Subprograms::
331* Tools Options in Project Files::
332* Compiling with Project Files::
333* Executable File Names::
334* Avoid Duplication With Variables::
335* Naming Schemes::
336* Installation::
337* Distributed support::
338
339Organizing Projects into Subsystems
340
341* Project Dependencies::
342* Cyclic Project Dependencies::
343* Sharing Between Projects::
344* Global Attributes::
345
346Library Projects
347
348* Building Libraries::
349* Using Library Projects::
350* Stand-alone Library Projects::
351* Installing a library with project files::
352
353Project Extension
354
355* Project Hierarchy Extension::
356
357Aggregate Projects
358
359* Building all main programs from a single project tree::
360* Building a set of projects with a single command::
361* Define a build environment::
362* Performance improvements in builder::
363* Syntax of aggregate projects::
364* package Builder in aggregate projects::
365
366Aggregate Library Projects
367
368* Building aggregate library projects::
369* Syntax of aggregate library projects::
370
371Project File Reference
372
373* Project Declaration::
374* Qualified Projects::
375* Declarations::
376* Packages::
377* Expressions::
378* External Values::
379* Typed String Declaration::
380* Variables::
381* Case Constructions::
382* Attributes::
383
384Attributes
385
386* Project Level Attributes::
387* Package Binder Attributes::
388* Package Builder Attributes::
389* Package Clean Attributes::
390* Package Compiler Attributes::
391* Package Cross_Reference Attributes::
392* Package Finder Attributes::
393* Package gnatls Attributes::
394* Package IDE Attributes::
395* Package Install Attributes::
396* Package Linker Attributes::
397* Package Naming Attributes::
398* Package Remote Attributes::
399* Package Stack Attributes::
400* Package Synchronize Attributes::
401
402Tools Supporting Project Files
403
404* gnatmake and Project Files::
405* The GNAT Driver and Project Files::
406
407gnatmake and Project Files
408
409* Switches Related to Project Files::
410* Switches and Project Files::
411* Specifying Configuration Pragmas::
412* Project Files and Main Subprograms::
413* Library Project Files::
414
415GNAT Utility Programs
416
417* The File Cleanup Utility gnatclean::
418* The GNAT Library Browser gnatls::
419* The Cross-Referencing Tools gnatxref and gnatfind::
420* The Ada to HTML Converter gnathtml::
421
422The File Cleanup Utility gnatclean
423
424* Running gnatclean::
425* Switches for gnatclean::
426
427The GNAT Library Browser gnatls
428
429* Running gnatls::
430* Switches for gnatls::
431* Example of gnatls Usage::
432
433The Cross-Referencing Tools gnatxref and gnatfind
434
435* gnatxref Switches::
436* gnatfind Switches::
437* Project Files for gnatxref and gnatfind::
438* Regular Expressions in gnatfind and gnatxref::
439* Examples of gnatxref Usage::
440* Examples of gnatfind Usage::
441
442Examples of gnatxref Usage
443
444* General Usage::
445* Using gnatxref with vi::
446
447The Ada to HTML Converter gnathtml
448
449* Invoking gnathtml::
450* Installing gnathtml::
451
452GNAT and Program Execution
453
454* Running and Debugging Ada Programs::
455* Code Coverage and Profiling::
456* Improving Performance::
457* Overflow Check Handling in GNAT::
458* Performing Dimensionality Analysis in GNAT::
459* Stack Related Facilities::
460* Memory Management Issues::
461
462Running and Debugging Ada Programs
463
464* The GNAT Debugger GDB::
465* Running GDB::
466* Introduction to GDB Commands::
467* Using Ada Expressions::
468* Calling User-Defined Subprograms::
469* Using the next Command in a Function::
470* Stopping When Ada Exceptions Are Raised::
471* Ada Tasks::
472* Debugging Generic Units::
473* Remote Debugging with gdbserver::
474* GNAT Abnormal Termination or Failure to Terminate::
475* Naming Conventions for GNAT Source Files::
476* Getting Internal Debugging Information::
477* Stack Traceback::
478
479Stack Traceback
480
481* Non-Symbolic Traceback::
482* Symbolic Traceback::
483
484Code Coverage and Profiling
485
486* Code Coverage of Ada Programs with gcov::
487* Profiling an Ada Program with gprof::
488
489Code Coverage of Ada Programs with gcov
490
491* Quick startup guide::
492* GNAT specifics::
493
494Profiling an Ada Program with gprof
495
496* Compilation for profiling::
497* Program execution::
498* Running gprof::
499* Interpretation of profiling results::
500
501Improving Performance
502
503* Performance Considerations::
504* Text_IO Suggestions::
505* Reducing Size of Executables with Unused Subprogram/Data Elimination::
506
507Performance Considerations
508
509* Controlling Run-Time Checks::
510* Use of Restrictions::
511* Optimization Levels::
512* Debugging Optimized Code::
513* Inlining of Subprograms::
514* Floating_Point_Operations::
515* Vectorization of loops::
516* Other Optimization Switches::
517* Optimization and Strict Aliasing::
518* Aliased Variables and Optimization::
519* Atomic Variables and Optimization::
520* Passive Task Optimization::
521
522Reducing Size of Executables with Unused Subprogram/Data Elimination
523
524* About unused subprogram/data elimination::
525* Compilation options::
526* Example of unused subprogram/data elimination::
527
528Overflow Check Handling in GNAT
529
530* Background::
531* Management of Overflows in GNAT::
532* Specifying the Desired Mode::
533* Default Settings::
534* Implementation Notes::
535
536Stack Related Facilities
537
538* Stack Overflow Checking::
539* Static Stack Usage Analysis::
540* Dynamic Stack Usage Analysis::
541
542Memory Management Issues
543
544* Some Useful Memory Pools::
545* The GNAT Debug Pool Facility::
546
547Platform-Specific Information
548
549* Run-Time Libraries::
550* Specifying a Run-Time Library::
551* Microsoft Windows Topics::
552* Mac OS Topics::
553
554Run-Time Libraries
555
556* Summary of Run-Time Configurations::
557
558Specifying a Run-Time Library
559
560* Choosing the Scheduling Policy::
561* Solaris-Specific Considerations::
562* Solaris Threads Issues::
563* AIX-Specific Considerations::
564
565Microsoft Windows Topics
566
567* Using GNAT on Windows::
568* Using a network installation of GNAT::
569* CONSOLE and WINDOWS subsystems::
570* Temporary Files::
571* Mixed-Language Programming on Windows::
572* Windows Specific Add-Ons::
573
574Mixed-Language Programming on Windows
575
576* Windows Calling Conventions::
577* Introduction to Dynamic Link Libraries (DLLs): Introduction to Dynamic Link Libraries DLLs.
578* Using DLLs with GNAT::
579* Building DLLs with GNAT Project files::
580* Building DLLs with GNAT::
581* Building DLLs with gnatdll::
582* Ada DLLs and Finalization::
583* Creating a Spec for Ada DLLs::
584* GNAT and Windows Resources::
585* Using GNAT DLLs from Microsoft Visual Studio Applications::
586* Debugging a DLL::
587* Setting Stack Size from gnatlink::
588* Setting Heap Size from gnatlink::
589
590Windows Calling Conventions
591
592* C Calling Convention::
593* Stdcall Calling Convention::
594* Win32 Calling Convention::
595* DLL Calling Convention::
596
597Using DLLs with GNAT
598
599* Creating an Ada Spec for the DLL Services::
600* Creating an Import Library::
601
602Building DLLs with gnatdll
603
604* Limitations When Using Ada DLLs from Ada::
605* Exporting Ada Entities::
606* Ada DLLs and Elaboration::
607
608Creating a Spec for Ada DLLs
609
610* Creating the Definition File::
611* Using gnatdll::
612
613GNAT and Windows Resources
614
615* Building Resources::
616* Compiling Resources::
617* Using Resources::
618
619Debugging a DLL
620
621* Program and DLL Both Built with GCC/GNAT::
622* Program Built with Foreign Tools and DLL Built with GCC/GNAT::
623
624Windows Specific Add-Ons
625
626* Win32Ada::
627* wPOSIX::
628
629Mac OS Topics
630
631* Codesigning the Debugger::
632
633Elaboration Order Handling in GNAT
634
635* Elaboration Code::
636* Checking the Elaboration Order::
637* Controlling the Elaboration Order::
638* Controlling Elaboration in GNAT - Internal Calls::
639* Controlling Elaboration in GNAT - External Calls::
640* Default Behavior in GNAT - Ensuring Safety::
641* Treatment of Pragma Elaborate::
642* Elaboration Issues for Library Tasks::
643* Mixing Elaboration Models::
644* What to Do If the Default Elaboration Behavior Fails::
645* Elaboration for Indirect Calls::
646* Summary of Procedures for Elaboration Control::
647* Other Elaboration Order Considerations::
648* Determining the Chosen Elaboration Order::
649
650Inline Assembler
651
652* Basic Assembler Syntax::
653* A Simple Example of Inline Assembler::
654* Output Variables in Inline Assembler::
655* Input Variables in Inline Assembler::
656* Inlining Inline Assembler Code::
657* Other Asm Functionality::
658
659Other Asm Functionality
660
661* The Clobber Parameter::
662* The Volatile Parameter::
663
664@end detailmenu
665@end menu
666
667@node About This Guide,Getting Started with GNAT,Top,Top
668@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}
669@chapter About This Guide
670
671
672
673This guide describes the use of GNAT,
674a compiler and software development
675toolset for the full Ada programming language.
676It documents the features of the compiler and tools, and explains
677how to use them to build Ada applications.
678
679GNAT implements Ada 95, Ada 2005 and Ada 2012, and it may also be
680invoked in Ada 83 compatibility mode.
681By default, GNAT assumes Ada 2012, but you can override with a
682compiler switch (@ref{6,,Compiling Different Versions of Ada})
683to explicitly specify the language version.
684Throughout this manual, references to 'Ada' without a year suffix
685apply to all Ada 95/2005/2012 versions of the language.
686
687@menu
688* What This Guide Contains::
689* What You Should Know before Reading This Guide::
690* Related Information::
691* A Note to Readers of Previous Versions of the Manual::
692* Conventions::
693
694@end menu
695
696@node What This Guide Contains,What You Should Know before Reading This Guide,,About This Guide
697@anchor{gnat_ugn/about_this_guide what-this-guide-contains}@anchor{7}
698@section What This Guide Contains
699
700
701This guide contains the following chapters:
702
703
704@itemize *
705
706@item
707@ref{8,,Getting Started with GNAT} describes how to get started compiling
708and running Ada programs with the GNAT Ada programming environment.
709
710@item
711@ref{9,,The GNAT Compilation Model} describes the compilation model used
712by GNAT.
713
714@item
715@ref{a,,Building Executable Programs with GNAT} describes how to use the
716main GNAT tools to build executable programs, and it also gives examples of
717using the GNU make utility with GNAT.
718
719@item
720@ref{b,,GNAT Project Manager} describes how to use project files
721to organize large projects.
722
723@item
724@ref{c,,Tools Supporting Project Files} described how to use the project
725facility in conjunction with various GNAT tools.
726
727@item
728@ref{d,,GNAT Utility Programs} explains the various utility programs that
729are included in the GNAT environment
730
731@item
732@ref{e,,GNAT and Program Execution} covers a number of topics related to
733running, debugging, and tuning the performace of programs developed
734with GNAT
735@end itemize
736
737Appendices cover several additional topics:
738
739
740@itemize *
741
742@item
743@ref{f,,Platform-Specific Information} describes the different run-time
744library implementations and also presents information on how to use
745GNAT on several specific platforms
746
747@item
748@ref{10,,Example of Binder Output File} shows the source code for the binder
749output file for a sample program.
750
751@item
752@ref{11,,Elaboration Order Handling in GNAT} describes how GNAT helps
753you deal with elaboration order issues.
754
755@item
756@ref{12,,Inline Assembler} shows how to use the inline assembly facility
757in an Ada program.
758@end itemize
759
760@node What You Should Know before Reading This Guide,Related Information,What This Guide Contains,About This Guide
761@anchor{gnat_ugn/about_this_guide what-you-should-know-before-reading-this-guide}@anchor{13}
762@section What You Should Know before Reading This Guide
763
764
765@geindex Ada 95 Language Reference Manual
766
767@geindex Ada 2005 Language Reference Manual
768
769This guide assumes a basic familiarity with the Ada 95 language, as
770described in the International Standard ANSI/ISO/IEC-8652:1995, January
7711995.
772It does not require knowledge of the features introduced by Ada 2005
773or Ada 2012.
774Reference manuals for Ada 95, Ada 2005, and Ada 2012 are included in
775the GNAT documentation package.
776
777@node Related Information,A Note to Readers of Previous Versions of the Manual,What You Should Know before Reading This Guide,About This Guide
778@anchor{gnat_ugn/about_this_guide related-information}@anchor{14}
779@section Related Information
780
781
782For further information about Ada and related tools, please refer to the
783following documents:
784
785
786@itemize *
787
788@item
789@cite{Ada 95 Reference Manual}, @cite{Ada 2005 Reference Manual}, and
790@cite{Ada 2012 Reference Manual}, which contain reference
791material for the several revisions of the Ada language standard.
792
793@item
794@cite{GNAT Reference_Manual}, which contains all reference material for the GNAT
795implementation of Ada.
796
797@item
798@cite{Using the GNAT Programming Studio}, which describes the GPS
799Integrated Development Environment.
800
801@item
802@cite{GNAT Programming Studio Tutorial}, which introduces the
803main GPS features through examples.
804
805@item
806@cite{Debugging with GDB},
807for all details on the use of the GNU source-level debugger.
808
809@item
810@cite{GNU Emacs Manual},
811for full information on the extensible editor and programming
812environment Emacs.
813@end itemize
814
815@node A Note to Readers of Previous Versions of the Manual,Conventions,Related Information,About This Guide
816@anchor{gnat_ugn/about_this_guide a-note-to-readers-of-previous-versions-of-the-manual}@anchor{15}
817@section A Note to Readers of Previous Versions of the Manual
818
819
820In early 2015 the GNAT manuals were transitioned to the
821reStructuredText (rst) / Sphinx documentation generator technology.
822During that process the @cite{GNAT User's Guide} was reorganized
823so that related topics would be described together in the same chapter
824or appendix.  Here's a summary of the major changes realized in
825the new document structure.
826
827
828@itemize *
829
830@item
831@ref{9,,The GNAT Compilation Model} has been extended so that it now covers
832the following material:
833
834
835@itemize -
836
837@item
838The @cite{gnatname}, @cite{gnatkr}, and @cite{gnatchop} tools
839
840@item
841@ref{16,,Configuration Pragmas}
842
843@item
844@ref{17,,GNAT and Libraries}
845
846@item
847@ref{18,,Conditional Compilation} including @ref{19,,Preprocessing with gnatprep}
848and @ref{1a,,Integrated Preprocessing}
849
850@item
851@ref{1b,,Generating Ada Bindings for C and C++ headers}
852
853@item
854@ref{1c,,Using GNAT Files with External Tools}
855@end itemize
856
857@item
858@ref{a,,Building Executable Programs with GNAT} is a new chapter consolidating
859the following content:
860
861
862@itemize -
863
864@item
865@ref{1d,,Building with gnatmake}
866
867@item
868@ref{1e,,Compiling with gcc}
869
870@item
871@ref{1f,,Binding with gnatbind}
872
873@item
874@ref{20,,Linking with gnatlink}
875
876@item
877@ref{21,,Using the GNU make Utility}
878@end itemize
879
880@item
881@ref{d,,GNAT Utility Programs} is a new chapter consolidating the information about several
882GNAT tools:
883
884
885
886@itemize -
887
888@item
889@ref{22,,The File Cleanup Utility gnatclean}
890
891@item
892@ref{23,,The GNAT Library Browser gnatls}
893
894@item
895@ref{24,,The Cross-Referencing Tools gnatxref and gnatfind}
896
897@item
898@ref{25,,The Ada to HTML Converter gnathtml}
899@end itemize
900
901@item
902@ref{e,,GNAT and Program Execution} is a new chapter consolidating the following:
903
904
905@itemize -
906
907@item
908@ref{26,,Running and Debugging Ada Programs}
909
910@item
911@ref{27,,Code Coverage and Profiling}
912
913@item
914@ref{28,,Improving Performance}
915
916@item
917@ref{29,,Overflow Check Handling in GNAT}
918
919@item
920@ref{2a,,Performing Dimensionality Analysis in GNAT}
921
922@item
923@ref{2b,,Stack Related Facilities}
924
925@item
926@ref{2c,,Memory Management Issues}
927@end itemize
928
929@item
930@ref{f,,Platform-Specific Information} is a new appendix consolidating the following:
931
932
933@itemize -
934
935@item
936@ref{2d,,Run-Time Libraries}
937
938@item
939@ref{2e,,Microsoft Windows Topics}
940
941@item
942@ref{2f,,Mac OS Topics}
943@end itemize
944
945@item
946The @cite{Compatibility and Porting Guide} appendix has been moved to the
947@cite{GNAT Reference Manual}. It now includes a section
948@cite{Writing Portable Fixed-Point Declarations} which was previously
949a separate chapter in the @cite{GNAT User's Guide}.
950@end itemize
951
952@node Conventions,,A Note to Readers of Previous Versions of the Manual,About This Guide
953@anchor{gnat_ugn/about_this_guide conventions}@anchor{30}
954@section Conventions
955
956
957@geindex Conventions
958@geindex typographical
959
960@geindex Typographical conventions
961
962Following are examples of the typographical and graphic conventions used
963in this guide:
964
965
966@itemize *
967
968@item
969@cite{Functions}, @cite{utility program names}, @cite{standard names},
970and @cite{classes}.
971
972@item
973@cite{Option flags}
974
975@item
976@code{File names}
977
978@item
979@cite{Variables}
980
981@item
982@emph{Emphasis}
983
984@item
985[optional information or parameters]
986
987@item
988Examples are described by text
989
990@example
991and then shown this way.
992@end example
993
994@item
995Commands that are entered by the user are shown as preceded by a prompt string
996comprising the @code{$} character followed by a space.
997
998@item
999Full file names are shown with the '/' character
1000as the directory separator; e.g., @code{parent-dir/subdir/myfile.adb}.
1001If you are using GNAT on a Windows platform, please note that
1002the '\' character should be used instead.
1003@end itemize
1004
1005@node Getting Started with GNAT,The GNAT Compilation Model,About This Guide,Top
1006@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}
1007@chapter Getting Started with GNAT
1008
1009
1010This chapter describes how to use GNAT's command line interface to build
1011executable Ada programs.
1012On most platforms a visually oriented Integrated Development Environment
1013is also available, the GNAT Programming Studio (GPS).
1014GPS offers a graphical "look and feel", support for development in
1015other programming languages, comprehensive browsing features, and
1016many other capabilities.
1017For information on GPS please refer to
1018@cite{Using the GNAT Programming Studio}.
1019
1020@menu
1021* Running GNAT::
1022* Running a Simple Ada Program::
1023* Running a Program with Multiple Units::
1024* Using the gnatmake Utility::
1025
1026@end menu
1027
1028@node Running GNAT,Running a Simple Ada Program,,Getting Started with GNAT
1029@anchor{gnat_ugn/getting_started_with_gnat running-gnat}@anchor{33}@anchor{gnat_ugn/getting_started_with_gnat id2}@anchor{34}
1030@section Running GNAT
1031
1032
1033Three steps are needed to create an executable file from an Ada source
1034file:
1035
1036
1037@itemize *
1038
1039@item
1040The source file(s) must be compiled.
1041
1042@item
1043The file(s) must be bound using the GNAT binder.
1044
1045@item
1046All appropriate object files must be linked to produce an executable.
1047@end itemize
1048
1049All three steps are most commonly handled by using the @emph{gnatmake}
1050utility program that, given the name of the main program, automatically
1051performs the necessary compilation, binding and linking steps.
1052
1053@node Running a Simple Ada Program,Running a Program with Multiple Units,Running GNAT,Getting Started with GNAT
1054@anchor{gnat_ugn/getting_started_with_gnat running-a-simple-ada-program}@anchor{35}@anchor{gnat_ugn/getting_started_with_gnat id3}@anchor{36}
1055@section Running a Simple Ada Program
1056
1057
1058Any text editor may be used to prepare an Ada program.
1059(If Emacs is used, the optional Ada mode may be helpful in laying out the
1060program.)
1061The program text is a normal text file. We will assume in our initial
1062example that you have used your editor to prepare the following
1063standard format text file:
1064
1065@example
1066with Ada.Text_IO; use Ada.Text_IO;
1067procedure Hello is
1068begin
1069   Put_Line ("Hello WORLD!");
1070end Hello;
1071@end example
1072
1073This file should be named @code{hello.adb}.
1074With the normal default file naming conventions, GNAT requires
1075that each file
1076contain a single compilation unit whose file name is the
1077unit name,
1078with periods replaced by hyphens; the
1079extension is @code{ads} for a
1080spec and @code{adb} for a body.
1081You can override this default file naming convention by use of the
1082special pragma @cite{Source_File_Name} (for further information please
1083see @ref{37,,Using Other File Names}).
1084Alternatively, if you want to rename your files according to this default
1085convention, which is probably more convenient if you will be using GNAT
1086for all your compilations, then the @cite{gnatchop} utility
1087can be used to generate correctly-named source files
1088(see @ref{38,,Renaming Files with gnatchop}).
1089
1090You can compile the program using the following command (@cite{$} is used
1091as the command prompt in the examples in this document):
1092
1093@example
1094$ gcc -c hello.adb
1095@end example
1096
1097@emph{gcc} is the command used to run the compiler. This compiler is
1098capable of compiling programs in several languages, including Ada and
1099C. It assumes that you have given it an Ada program if the file extension is
1100either @code{.ads} or @code{.adb}, and it will then call
1101the GNAT compiler to compile the specified file.
1102
1103The @code{-c} switch is required. It tells @emph{gcc} to only do a
1104compilation. (For C programs, @emph{gcc} can also do linking, but this
1105capability is not used directly for Ada programs, so the @code{-c}
1106switch must always be present.)
1107
1108This compile command generates a file
1109@code{hello.o}, which is the object
1110file corresponding to your Ada program. It also generates
1111an 'Ada Library Information' file @code{hello.ali},
1112which contains additional information used to check
1113that an Ada program is consistent.
1114To build an executable file,
1115use @cite{gnatbind} to bind the program
1116and @emph{gnatlink} to link it. The
1117argument to both @cite{gnatbind} and @emph{gnatlink} is the name of the
1118@code{ALI} file, but the default extension of @code{.ali} can
1119be omitted. This means that in the most common case, the argument
1120is simply the name of the main program:
1121
1122@example
1123$ gnatbind hello
1124$ gnatlink hello
1125@end example
1126
1127A simpler method of carrying out these steps is to use @emph{gnatmake},
1128a master program that invokes all the required
1129compilation, binding and linking tools in the correct order. In particular,
1130@emph{gnatmake} automatically recompiles any sources that have been
1131modified since they were last compiled, or sources that depend
1132on such modified sources, so that 'version skew' is avoided.
1133
1134@geindex Version skew (avoided by *gnatmake*)
1135
1136@example
1137$ gnatmake hello.adb
1138@end example
1139
1140The result is an executable program called @code{hello}, which can be
1141run by entering:
1142
1143@example
1144$ hello
1145@end example
1146
1147assuming that the current directory is on the search path
1148for executable programs.
1149
1150and, if all has gone well, you will see:
1151
1152@example
1153Hello WORLD!
1154@end example
1155
1156appear in response to this command.
1157
1158@node Running a Program with Multiple Units,Using the gnatmake Utility,Running a Simple Ada Program,Getting Started with GNAT
1159@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}
1160@section Running a Program with Multiple Units
1161
1162
1163Consider a slightly more complicated example that has three files: a
1164main program, and the spec and body of a package:
1165
1166@example
1167package Greetings is
1168   procedure Hello;
1169   procedure Goodbye;
1170end Greetings;
1171
1172with Ada.Text_IO; use Ada.Text_IO;
1173package body Greetings is
1174   procedure Hello is
1175   begin
1176      Put_Line ("Hello WORLD!");
1177   end Hello;
1178
1179   procedure Goodbye is
1180   begin
1181      Put_Line ("Goodbye WORLD!");
1182   end Goodbye;
1183end Greetings;
1184
1185with Greetings;
1186procedure Gmain is
1187begin
1188   Greetings.Hello;
1189   Greetings.Goodbye;
1190end Gmain;
1191@end example
1192
1193Following the one-unit-per-file rule, place this program in the
1194following three separate files:
1195
1196
1197@table @asis
1198
1199@item @emph{greetings.ads}
1200
1201spec of package @cite{Greetings}
1202
1203@item @emph{greetings.adb}
1204
1205body of package @cite{Greetings}
1206
1207@item @emph{gmain.adb}
1208
1209body of main program
1210@end table
1211
1212To build an executable version of
1213this program, we could use four separate steps to compile, bind, and link
1214the program, as follows:
1215
1216@example
1217$ gcc -c gmain.adb
1218$ gcc -c greetings.adb
1219$ gnatbind gmain
1220$ gnatlink gmain
1221@end example
1222
1223Note that there is no required order of compilation when using GNAT.
1224In particular it is perfectly fine to compile the main program first.
1225Also, it is not necessary to compile package specs in the case where
1226there is an accompanying body; you only need to compile the body. If you want
1227to submit these files to the compiler for semantic checking and not code
1228generation, then use the @code{-gnatc} switch:
1229
1230@example
1231$ gcc -c greetings.ads -gnatc
1232@end example
1233
1234Although the compilation can be done in separate steps as in the
1235above example, in practice it is almost always more convenient
1236to use the @emph{gnatmake} tool. All you need to know in this case
1237is the name of the main program's source file. The effect of the above four
1238commands can be achieved with a single one:
1239
1240@example
1241$ gnatmake gmain.adb
1242@end example
1243
1244In the next section we discuss the advantages of using @emph{gnatmake} in
1245more detail.
1246
1247@node Using the gnatmake Utility,,Running a Program with Multiple Units,Getting Started with GNAT
1248@anchor{gnat_ugn/getting_started_with_gnat using-the-gnatmake-utility}@anchor{3b}@anchor{gnat_ugn/getting_started_with_gnat id5}@anchor{3c}
1249@section Using the @emph{gnatmake} Utility
1250
1251
1252If you work on a program by compiling single components at a time using
1253@emph{gcc}, you typically keep track of the units you modify. In order to
1254build a consistent system, you compile not only these units, but also any
1255units that depend on the units you have modified.
1256For example, in the preceding case,
1257if you edit @code{gmain.adb}, you only need to recompile that file. But if
1258you edit @code{greetings.ads}, you must recompile both
1259@code{greetings.adb} and @code{gmain.adb}, because both files contain
1260units that depend on @code{greetings.ads}.
1261
1262@emph{gnatbind} will warn you if you forget one of these compilation
1263steps, so that it is impossible to generate an inconsistent program as a
1264result of forgetting to do a compilation. Nevertheless it is tedious and
1265error-prone to keep track of dependencies among units.
1266One approach to handle the dependency-bookkeeping is to use a
1267makefile. However, makefiles present maintenance problems of their own:
1268if the dependencies change as you change the program, you must make
1269sure that the makefile is kept up-to-date manually, which is also an
1270error-prone process.
1271
1272The @emph{gnatmake} utility takes care of these details automatically.
1273Invoke it using either one of the following forms:
1274
1275@example
1276$ gnatmake gmain.adb
1277$ gnatmake gmain
1278@end example
1279
1280The argument is the name of the file containing the main program;
1281you may omit the extension. @emph{gnatmake}
1282examines the environment, automatically recompiles any files that need
1283recompiling, and binds and links the resulting set of object files,
1284generating the executable file, @code{gmain}.
1285In a large program, it
1286can be extremely helpful to use @emph{gnatmake}, because working out by hand
1287what needs to be recompiled can be difficult.
1288
1289Note that @emph{gnatmake} takes into account all the Ada rules that
1290establish dependencies among units. These include dependencies that result
1291from inlining subprogram bodies, and from
1292generic instantiation. Unlike some other
1293Ada make tools, @emph{gnatmake} does not rely on the dependencies that were
1294found by the compiler on a previous compilation, which may possibly
1295be wrong when sources change. @emph{gnatmake} determines the exact set of
1296dependencies from scratch each time it is run.
1297
1298@c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
1299
1300@node The GNAT Compilation Model,Building Executable Programs with GNAT,Getting Started with GNAT,Top
1301@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}
1302@chapter The GNAT Compilation Model
1303
1304
1305@geindex GNAT compilation model
1306
1307@geindex Compilation model
1308
1309This chapter describes the compilation model used by GNAT. Although
1310similar to that used by other languages such as C and C++, this model
1311is substantially different from the traditional Ada compilation models,
1312which are based on a centralized program library. The chapter covers
1313the following material:
1314
1315
1316@itemize *
1317
1318@item
1319Topics related to source file makeup and naming
1320
1321
1322@itemize *
1323
1324@item
1325@ref{3f,,Source Representation}
1326
1327@item
1328@ref{40,,Foreign Language Representation}
1329
1330@item
1331@ref{41,,File Naming Topics and Utilities}
1332@end itemize
1333
1334@item
1335@ref{16,,Configuration Pragmas}
1336
1337@item
1338@ref{42,,Generating Object Files}
1339
1340@item
1341@ref{43,,Source Dependencies}
1342
1343@item
1344@ref{44,,The Ada Library Information Files}
1345
1346@item
1347@ref{45,,Binding an Ada Program}
1348
1349@item
1350@ref{17,,GNAT and Libraries}
1351
1352@item
1353@ref{18,,Conditional Compilation}
1354
1355@item
1356@ref{46,,Mixed Language Programming}
1357
1358@item
1359@ref{47,,GNAT and Other Compilation Models}
1360
1361@item
1362@ref{1c,,Using GNAT Files with External Tools}
1363@end itemize
1364
1365@menu
1366* Source Representation::
1367* Foreign Language Representation::
1368* File Naming Topics and Utilities::
1369* Configuration Pragmas::
1370* Generating Object Files::
1371* Source Dependencies::
1372* The Ada Library Information Files::
1373* Binding an Ada Program::
1374* GNAT and Libraries::
1375* Conditional Compilation::
1376* Mixed Language Programming::
1377* GNAT and Other Compilation Models::
1378* Using GNAT Files with External Tools::
1379
1380@end menu
1381
1382@node Source Representation,Foreign Language Representation,,The GNAT Compilation Model
1383@anchor{gnat_ugn/the_gnat_compilation_model source-representation}@anchor{3f}@anchor{gnat_ugn/the_gnat_compilation_model id2}@anchor{48}
1384@section Source Representation
1385
1386
1387@geindex Latin-1
1388
1389@geindex VT
1390@geindex HT
1391@geindex CR
1392@geindex LF
1393@geindex FF
1394
1395Ada source programs are represented in standard text files, using
1396Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
13977-bit ASCII set, plus additional characters used for
1398representing foreign languages (see @ref{40,,Foreign Language Representation}
1399for support of non-USA character sets). The format effector characters
1400are represented using their standard ASCII encodings, as follows:
1401
1402@quotation
1403
1404
1405@multitable {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxx}
1406@item
1407
1408Character
1409
1410@tab
1411
1412Effect
1413
1414@tab
1415
1416Code
1417
1418@item
1419
1420@code{VT}
1421
1422@tab
1423
1424Vertical tab
1425
1426@tab
1427
1428@cite{16#0B#}
1429
1430@item
1431
1432@code{HT}
1433
1434@tab
1435
1436Horizontal tab
1437
1438@tab
1439
1440@cite{16#09#}
1441
1442@item
1443
1444@code{CR}
1445
1446@tab
1447
1448Carriage return
1449
1450@tab
1451
1452@cite{16#0D#}
1453
1454@item
1455
1456@code{LF}
1457
1458@tab
1459
1460Line feed
1461
1462@tab
1463
1464@cite{16#0A#}
1465
1466@item
1467
1468@code{FF}
1469
1470@tab
1471
1472Form feed
1473
1474@tab
1475
1476@cite{16#0C#}
1477
1478@end multitable
1479
1480@end quotation
1481
1482Source files are in standard text file format. In addition, GNAT will
1483recognize a wide variety of stream formats, in which the end of
1484physical lines is marked by any of the following sequences:
1485@cite{LF}, @cite{CR}, @cite{CR-LF}, or @cite{LF-CR}. This is useful
1486in accommodating files that are imported from other operating systems.
1487
1488@geindex End of source file; Source file@comma{} end
1489
1490@geindex SUB (control character)
1491
1492The end of a source file is normally represented by the physical end of
1493file. However, the control character @cite{16#1A#} (@code{SUB}) is also
1494recognized as signalling the end of the source file. Again, this is
1495provided for compatibility with other operating systems where this
1496code is used to represent the end of file.
1497
1498@geindex spec (definition)
1499@geindex compilation (definition)
1500
1501Each file contains a single Ada compilation unit, including any pragmas
1502associated with the unit. For example, this means you must place a
1503package declaration (a package @cite{spec}) and the corresponding body in
1504separate files. An Ada @cite{compilation} (which is a sequence of
1505compilation units) is represented using a sequence of files. Similarly,
1506you will place each subunit or child unit in a separate file.
1507
1508@node Foreign Language Representation,File Naming Topics and Utilities,Source Representation,The GNAT Compilation Model
1509@anchor{gnat_ugn/the_gnat_compilation_model foreign-language-representation}@anchor{40}@anchor{gnat_ugn/the_gnat_compilation_model id3}@anchor{49}
1510@section Foreign Language Representation
1511
1512
1513GNAT supports the standard character sets defined in Ada as well as
1514several other non-standard character sets for use in localized versions
1515of the compiler (@ref{4a,,Character Set Control}).
1516
1517@menu
1518* Latin-1::
1519* Other 8-Bit Codes::
1520* Wide_Character Encodings::
1521* Wide_Wide_Character Encodings::
1522
1523@end menu
1524
1525@node Latin-1,Other 8-Bit Codes,,Foreign Language Representation
1526@anchor{gnat_ugn/the_gnat_compilation_model id4}@anchor{4b}@anchor{gnat_ugn/the_gnat_compilation_model latin-1}@anchor{4c}
1527@subsection Latin-1
1528
1529
1530@geindex Latin-1
1531
1532The basic character set is Latin-1. This character set is defined by ISO
1533standard 8859, part 1. The lower half (character codes @cite{16#00#}
1534... @cite{16#7F#)} is identical to standard ASCII coding, but the upper
1535half is used to represent additional characters. These include extended letters
1536used by European languages, such as French accents, the vowels with umlauts
1537used in German, and the extra letter A-ring used in Swedish.
1538
1539@geindex Ada.Characters.Latin_1
1540
1541For a complete list of Latin-1 codes and their encodings, see the source
1542file of library unit @cite{Ada.Characters.Latin_1} in file
1543@code{a-chlat1.ads}.
1544You may use any of these extended characters freely in character or
1545string literals. In addition, the extended characters that represent
1546letters can be used in identifiers.
1547
1548@node Other 8-Bit Codes,Wide_Character Encodings,Latin-1,Foreign Language Representation
1549@anchor{gnat_ugn/the_gnat_compilation_model other-8-bit-codes}@anchor{4d}@anchor{gnat_ugn/the_gnat_compilation_model id5}@anchor{4e}
1550@subsection Other 8-Bit Codes
1551
1552
1553GNAT also supports several other 8-bit coding schemes:
1554
1555@geindex Latin-2
1556
1557@geindex ISO 8859-2
1558
1559
1560@table @asis
1561
1562@item @emph{ISO 8859-2 (Latin-2)}
1563
1564Latin-2 letters allowed in identifiers, with uppercase and lowercase
1565equivalence.
1566@end table
1567
1568@geindex Latin-3
1569
1570@geindex ISO 8859-3
1571
1572
1573@table @asis
1574
1575@item @emph{ISO 8859-3 (Latin-3)}
1576
1577Latin-3 letters allowed in identifiers, with uppercase and lowercase
1578equivalence.
1579@end table
1580
1581@geindex Latin-4
1582
1583@geindex ISO 8859-4
1584
1585
1586@table @asis
1587
1588@item @emph{ISO 8859-4 (Latin-4)}
1589
1590Latin-4 letters allowed in identifiers, with uppercase and lowercase
1591equivalence.
1592@end table
1593
1594@geindex ISO 8859-5
1595
1596@geindex Cyrillic
1597
1598
1599@table @asis
1600
1601@item @emph{ISO 8859-5 (Cyrillic)}
1602
1603ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1604lowercase equivalence.
1605@end table
1606
1607@geindex ISO 8859-15
1608
1609@geindex Latin-9
1610
1611
1612@table @asis
1613
1614@item @emph{ISO 8859-15 (Latin-9)}
1615
1616ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1617lowercase equivalence
1618@end table
1619
1620@geindex code page 437 (IBM PC)
1621
1622
1623@table @asis
1624
1625@item @emph{IBM PC (code page 437)}
1626
1627This code page is the normal default for PCs in the U.S. It corresponds
1628to the original IBM PC character set. This set has some, but not all, of
1629the extended Latin-1 letters, but these letters do not have the same
1630encoding as Latin-1. In this mode, these letters are allowed in
1631identifiers with uppercase and lowercase equivalence.
1632@end table
1633
1634@geindex code page 850 (IBM PC)
1635
1636
1637@table @asis
1638
1639@item @emph{IBM PC (code page 850)}
1640
1641This code page is a modification of 437 extended to include all the
1642Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1643mode, all these letters are allowed in identifiers with uppercase and
1644lowercase equivalence.
1645
1646@item @emph{Full Upper 8-bit}
1647
1648Any character in the range 80-FF allowed in identifiers, and all are
1649considered distinct. In other words, there are no uppercase and lowercase
1650equivalences in this range. This is useful in conjunction with
1651certain encoding schemes used for some foreign character sets (e.g.,
1652the typical method of representing Chinese characters on the PC).
1653
1654@item @emph{No Upper-Half}
1655
1656No upper-half characters in the range 80-FF are allowed in identifiers.
1657This gives Ada 83 compatibility for identifier names.
1658@end table
1659
1660For precise data on the encodings permitted, and the uppercase and lowercase
1661equivalences that are recognized, see the file @code{csets.adb} in
1662the GNAT compiler sources. You will need to obtain a full source release
1663of GNAT to obtain this file.
1664
1665@node Wide_Character Encodings,Wide_Wide_Character Encodings,Other 8-Bit Codes,Foreign Language Representation
1666@anchor{gnat_ugn/the_gnat_compilation_model id6}@anchor{4f}@anchor{gnat_ugn/the_gnat_compilation_model wide-character-encodings}@anchor{50}
1667@subsection Wide_Character Encodings
1668
1669
1670GNAT allows wide character codes to appear in character and string
1671literals, and also optionally in identifiers, by means of the following
1672possible encoding schemes:
1673
1674
1675@table @asis
1676
1677@item @emph{Hex Coding}
1678
1679In this encoding, a wide character is represented by the following five
1680character sequence:
1681
1682@example
1683ESC a b c d
1684@end example
1685
1686where @cite{a}, @cite{b}, @cite{c}, @cite{d} are the four hexadecimal
1687characters (using uppercase letters) of the wide character code. For
1688example, ESC A345 is used to represent the wide character with code
1689@cite{16#A345#}.
1690This scheme is compatible with use of the full Wide_Character set.
1691
1692@item @emph{Upper-Half Coding}
1693
1694@geindex Upper-Half Coding
1695
1696The wide character with encoding @cite{16#abcd#} where the upper bit is on
1697(in other words, 'a' is in the range 8-F) is represented as two bytes,
1698@cite{16#ab#} and @cite{16#cd#}. The second byte cannot be a format control
1699character, but is not required to be in the upper half. This method can
1700be also used for shift-JIS or EUC, where the internal coding matches the
1701external coding.
1702
1703@item @emph{Shift JIS Coding}
1704
1705@geindex Shift JIS Coding
1706
1707A wide character is represented by a two-character sequence,
1708@cite{16#ab#} and
1709@cite{16#cd#}, with the restrictions described for upper-half encoding as
1710described above. The internal character code is the corresponding JIS
1711character according to the standard algorithm for Shift-JIS
1712conversion. Only characters defined in the JIS code set table can be
1713used with this encoding method.
1714
1715@item @emph{EUC Coding}
1716
1717@geindex EUC Coding
1718
1719A wide character is represented by a two-character sequence
1720@cite{16#ab#} and
1721@cite{16#cd#}, with both characters being in the upper half. The internal
1722character code is the corresponding JIS character according to the EUC
1723encoding algorithm. Only characters defined in the JIS code set table
1724can be used with this encoding method.
1725
1726@item @emph{UTF-8 Coding}
1727
1728A wide character is represented using
1729UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
173010646-1/Am.2. Depending on the character value, the representation
1731is a one, two, or three byte sequence:
1732
1733@example
173416#0000#-16#007f#: 2#0`xxxxxxx`#
173516#0080#-16#07ff#: 2#110`xxxxx`# 2#10`xxxxxx`#
173616#0800#-16#ffff#: 2#1110`xxxx`# 2#10`xxxxxx`# 2#10`xxxxxx`#
1737@end example
1738
1739where the @cite{xxx} bits correspond to the left-padded bits of the
174016-bit character value. Note that all lower half ASCII characters
1741are represented as ASCII bytes and all upper half characters and
1742other wide characters are represented as sequences of upper-half
1743(The full UTF-8 scheme allows for encoding 31-bit characters as
17446-byte sequences, and in the following section on wide wide
1745characters, the use of these sequences is documented).
1746
1747@item @emph{Brackets Coding}
1748
1749In this encoding, a wide character is represented by the following eight
1750character sequence:
1751
1752@example
1753[ " a b c d " ]
1754@end example
1755
1756where @cite{a}, @cite{b}, @cite{c}, @cite{d} are the four hexadecimal
1757characters (using uppercase letters) of the wide character code. For
1758example, ['A345'] is used to represent the wide character with code
1759@cite{16#A345#}. It is also possible (though not required) to use the
1760Brackets coding for upper half characters. For example, the code
1761@cite{16#A3#} can be represented as @cite{['A3']}.
1762
1763This scheme is compatible with use of the full Wide_Character set,
1764and is also the method used for wide character encoding in some standard
1765ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
1766@end table
1767
1768@cartouche
1769@quotation Note
1770Some of these coding schemes do not permit the full use of the
1771Ada character set. For example, neither Shift JIS nor EUC allow the
1772use of the upper half of the Latin-1 set.
1773@end quotation
1774@end cartouche
1775
1776@node Wide_Wide_Character Encodings,,Wide_Character Encodings,Foreign Language Representation
1777@anchor{gnat_ugn/the_gnat_compilation_model id7}@anchor{51}@anchor{gnat_ugn/the_gnat_compilation_model wide-wide-character-encodings}@anchor{52}
1778@subsection Wide_Wide_Character Encodings
1779
1780
1781GNAT allows wide wide character codes to appear in character and string
1782literals, and also optionally in identifiers, by means of the following
1783possible encoding schemes:
1784
1785
1786@table @asis
1787
1788@item @emph{UTF-8 Coding}
1789
1790A wide character is represented using
1791UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
179210646-1/Am.2. Depending on the character value, the representation
1793of character codes with values greater than 16#FFFF# is a
1794is a four, five, or six byte sequence:
1795
1796@example
179716#01_0000#-16#10_FFFF#:     11110xxx 10xxxxxx 10xxxxxx
1798                             10xxxxxx
179916#0020_0000#-16#03FF_FFFF#: 111110xx 10xxxxxx 10xxxxxx
1800                             10xxxxxx 10xxxxxx
180116#0400_0000#-16#7FFF_FFFF#: 1111110x 10xxxxxx 10xxxxxx
1802                             10xxxxxx 10xxxxxx 10xxxxxx
1803@end example
1804
1805where the @cite{xxx} bits correspond to the left-padded bits of the
180632-bit character value.
1807
1808@item @emph{Brackets Coding}
1809
1810In this encoding, a wide wide character is represented by the following ten or
1811twelve byte character sequence:
1812
1813@example
1814[ " a b c d e f " ]
1815[ " a b c d e f g h " ]
1816@end example
1817
1818where @cite{a-h} are the six or eight hexadecimal
1819characters (using uppercase letters) of the wide wide character code. For
1820example, ["1F4567"] is used to represent the wide wide character with code
1821@cite{16#001F_4567#}.
1822
1823This scheme is compatible with use of the full Wide_Wide_Character set,
1824and is also the method used for wide wide character encoding in some standard
1825ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
1826@end table
1827
1828@node File Naming Topics and Utilities,Configuration Pragmas,Foreign Language Representation,The GNAT Compilation Model
1829@anchor{gnat_ugn/the_gnat_compilation_model id8}@anchor{53}@anchor{gnat_ugn/the_gnat_compilation_model file-naming-topics-and-utilities}@anchor{41}
1830@section File Naming Topics and Utilities
1831
1832
1833GNAT has a default file naming scheme and also provides the user with
1834a high degree of control over how the names and extensions of the
1835source files correspond to the Ada compilation units that they contain.
1836
1837@menu
1838* File Naming Rules::
1839* Using Other File Names::
1840* Alternative File Naming Schemes::
1841* Handling Arbitrary File Naming Conventions with gnatname::
1842* File Name Krunching with gnatkr::
1843* Renaming Files with gnatchop::
1844
1845@end menu
1846
1847@node File Naming Rules,Using Other File Names,,File Naming Topics and Utilities
1848@anchor{gnat_ugn/the_gnat_compilation_model file-naming-rules}@anchor{54}@anchor{gnat_ugn/the_gnat_compilation_model id9}@anchor{55}
1849@subsection File Naming Rules
1850
1851
1852The default file name is determined by the name of the unit that the
1853file contains. The name is formed by taking the full expanded name of
1854the unit and replacing the separating dots with hyphens and using
1855lowercase for all letters.
1856
1857An exception arises if the file name generated by the above rules starts
1858with one of the characters
1859@cite{a}, @cite{g}, @cite{i}, or @cite{s}, and the second character is a
1860minus. In this case, the character tilde is used in place
1861of the minus. The reason for this special rule is to avoid clashes with
1862the standard names for child units of the packages System, Ada,
1863Interfaces, and GNAT, which use the prefixes
1864@cite{s-}, @cite{a-}, @cite{i-}, and @cite{g-},
1865respectively.
1866
1867The file extension is @code{.ads} for a spec and
1868@code{.adb} for a body. The following table shows some
1869examples of these rules.
1870
1871@quotation
1872
1873
1874@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
1875@item
1876
1877Source File
1878
1879@tab
1880
1881Ada Compilation Unit
1882
1883@item
1884
1885@code{main.ads}
1886
1887@tab
1888
1889Main (spec)
1890
1891@item
1892
1893@code{main.adb}
1894
1895@tab
1896
1897Main (body)
1898
1899@item
1900
1901@code{arith_functions.ads}
1902
1903@tab
1904
1905Arith_Functions (package spec)
1906
1907@item
1908
1909@code{arith_functions.adb}
1910
1911@tab
1912
1913Arith_Functions (package body)
1914
1915@item
1916
1917@code{func-spec.ads}
1918
1919@tab
1920
1921Func.Spec (child package spec)
1922
1923@item
1924
1925@code{func-spec.adb}
1926
1927@tab
1928
1929Func.Spec (child package body)
1930
1931@item
1932
1933@code{main-sub.adb}
1934
1935@tab
1936
1937Sub (subunit of Main)
1938
1939@item
1940
1941@code{a~bad.adb}
1942
1943@tab
1944
1945A.Bad (child package body)
1946
1947@end multitable
1948
1949@end quotation
1950
1951Following these rules can result in excessively long
1952file names if corresponding
1953unit names are long (for example, if child units or subunits are
1954heavily nested). An option is available to shorten such long file names
1955(called file name 'krunching'). This may be particularly useful when
1956programs being developed with GNAT are to be used on operating systems
1957with limited file name lengths. @ref{56,,Using gnatkr}.
1958
1959Of course, no file shortening algorithm can guarantee uniqueness over
1960all possible unit names; if file name krunching is used, it is your
1961responsibility to ensure no name clashes occur. Alternatively you
1962can specify the exact file names that you want used, as described
1963in the next section. Finally, if your Ada programs are migrating from a
1964compiler with a different naming convention, you can use the gnatchop
1965utility to produce source files that follow the GNAT naming conventions.
1966(For details see @ref{38,,Renaming Files with gnatchop}.)
1967
1968Note: in the case of Windows or Mac OS operating systems, case is not
1969significant. So for example on @cite{Windows} if the canonical name is
1970@cite{main-sub.adb}, you can use the file name @code{Main-Sub.adb} instead.
1971However, case is significant for other operating systems, so for example,
1972if you want to use other than canonically cased file names on a Unix system,
1973you need to follow the procedures described in the next section.
1974
1975@node Using Other File Names,Alternative File Naming Schemes,File Naming Rules,File Naming Topics and Utilities
1976@anchor{gnat_ugn/the_gnat_compilation_model id10}@anchor{57}@anchor{gnat_ugn/the_gnat_compilation_model using-other-file-names}@anchor{37}
1977@subsection Using Other File Names
1978
1979
1980@geindex File names
1981
1982In the previous section, we have described the default rules used by
1983GNAT to determine the file name in which a given unit resides. It is
1984often convenient to follow these default rules, and if you follow them,
1985the compiler knows without being explicitly told where to find all
1986the files it needs.
1987
1988@geindex Source_File_Name pragma
1989
1990However, in some cases, particularly when a program is imported from
1991another Ada compiler environment, it may be more convenient for the
1992programmer to specify which file names contain which units. GNAT allows
1993arbitrary file names to be used by means of the Source_File_Name pragma.
1994The form of this pragma is as shown in the following examples:
1995
1996@example
1997pragma Source_File_Name (My_Utilities.Stacks,
1998  Spec_File_Name => "myutilst_a.ada");
1999pragma Source_File_name (My_Utilities.Stacks,
2000  Body_File_Name => "myutilst.ada");
2001@end example
2002
2003As shown in this example, the first argument for the pragma is the unit
2004name (in this example a child unit). The second argument has the form
2005of a named association. The identifier
2006indicates whether the file name is for a spec or a body;
2007the file name itself is given by a string literal.
2008
2009The source file name pragma is a configuration pragma, which means that
2010normally it will be placed in the @code{gnat.adc}
2011file used to hold configuration
2012pragmas that apply to a complete compilation environment.
2013For more details on how the @code{gnat.adc} file is created and used
2014see @ref{58,,Handling of Configuration Pragmas}.
2015
2016@geindex gnat.adc
2017
2018GNAT allows completely arbitrary file names to be specified using the
2019source file name pragma. However, if the file name specified has an
2020extension other than @code{.ads} or @code{.adb} it is necessary to use
2021a special syntax when compiling the file. The name in this case must be
2022preceded by the special sequence @emph{-x} followed by a space and the name
2023of the language, here @cite{ada}, as in:
2024
2025@example
2026$ gcc -c -x ada peculiar_file_name.sim
2027@end example
2028
2029@cite{gnatmake} handles non-standard file names in the usual manner (the
2030non-standard file name for the main program is simply used as the
2031argument to gnatmake). Note that if the extension is also non-standard,
2032then it must be included in the @cite{gnatmake} command, it may not
2033be omitted.
2034
2035@node Alternative File Naming Schemes,Handling Arbitrary File Naming Conventions with gnatname,Using Other File Names,File Naming Topics and Utilities
2036@anchor{gnat_ugn/the_gnat_compilation_model id11}@anchor{59}@anchor{gnat_ugn/the_gnat_compilation_model alternative-file-naming-schemes}@anchor{5a}
2037@subsection Alternative File Naming Schemes
2038
2039
2040@geindex File naming schemes
2041@geindex alternative
2042
2043@geindex File names
2044
2045The previous section described the use of the @cite{Source_File_Name}
2046pragma to allow arbitrary names to be assigned to individual source files.
2047However, this approach requires one pragma for each file, and especially in
2048large systems can result in very long @code{gnat.adc} files, and also create
2049a maintenance problem.
2050
2051@geindex Source_File_Name pragma
2052
2053GNAT also provides a facility for specifying systematic file naming schemes
2054other than the standard default naming scheme previously described. An
2055alternative scheme for naming is specified by the use of
2056@cite{Source_File_Name} pragmas having the following format:
2057
2058@example
2059pragma Source_File_Name (
2060   Spec_File_Name  => FILE_NAME_PATTERN
2061 [ , Casing          => CASING_SPEC]
2062 [ , Dot_Replacement => STRING_LITERAL ] );
2063
2064pragma Source_File_Name (
2065   Body_File_Name  => FILE_NAME_PATTERN
2066 [ , Casing          => CASING_SPEC ]
2067 [ , Dot_Replacement => STRING_LITERAL ] ) ;
2068
2069pragma Source_File_Name (
2070   Subunit_File_Name  => FILE_NAME_PATTERN
2071 [ , Casing          => CASING_SPEC ]
2072 [ , Dot_Replacement => STRING_LITERAL ] ) ;
2073
2074FILE_NAME_PATTERN ::= STRING_LITERAL
2075CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2076@end example
2077
2078The @cite{FILE_NAME_PATTERN} string shows how the file name is constructed.
2079It contains a single asterisk character, and the unit name is substituted
2080systematically for this asterisk. The optional parameter
2081@cite{Casing} indicates
2082whether the unit name is to be all upper-case letters, all lower-case letters,
2083or mixed-case. If no
2084@cite{Casing} parameter is used, then the default is all
2085lower-case.
2086
2087The optional @cite{Dot_Replacement} string is used to replace any periods
2088that occur in subunit or child unit names. If no @cite{Dot_Replacement}
2089argument is used then separating dots appear unchanged in the resulting
2090file name.
2091Although the above syntax indicates that the
2092@cite{Casing} argument must appear
2093before the @cite{Dot_Replacement} argument, but it
2094is also permissible to write these arguments in the opposite order.
2095
2096As indicated, it is possible to specify different naming schemes for
2097bodies, specs, and subunits. Quite often the rule for subunits is the
2098same as the rule for bodies, in which case, there is no need to give
2099a separate @cite{Subunit_File_Name} rule, and in this case the
2100@cite{Body_File_name} rule is used for subunits as well.
2101
2102The separate rule for subunits can also be used to implement the rather
2103unusual case of a compilation environment (e.g., a single directory) which
2104contains a subunit and a child unit with the same unit name. Although
2105both units cannot appear in the same partition, the Ada Reference Manual
2106allows (but does not require) the possibility of the two units coexisting
2107in the same environment.
2108
2109The file name translation works in the following steps:
2110
2111
2112@itemize *
2113
2114@item
2115If there is a specific @cite{Source_File_Name} pragma for the given unit,
2116then this is always used, and any general pattern rules are ignored.
2117
2118@item
2119If there is a pattern type @cite{Source_File_Name} pragma that applies to
2120the unit, then the resulting file name will be used if the file exists. If
2121more than one pattern matches, the latest one will be tried first, and the
2122first attempt resulting in a reference to a file that exists will be used.
2123
2124@item
2125If no pattern type @cite{Source_File_Name} pragma that applies to the unit
2126for which the corresponding file exists, then the standard GNAT default
2127naming rules are used.
2128@end itemize
2129
2130As an example of the use of this mechanism, consider a commonly used scheme
2131in which file names are all lower case, with separating periods copied
2132unchanged to the resulting file name, and specs end with @code{.1.ada}, and
2133bodies end with @code{.2.ada}. GNAT will follow this scheme if the following
2134two pragmas appear:
2135
2136@example
2137pragma Source_File_Name
2138  (Spec_File_Name => ".1.ada");
2139pragma Source_File_Name
2140  (Body_File_Name => ".2.ada");
2141@end example
2142
2143The default GNAT scheme is actually implemented by providing the following
2144default pragmas internally:
2145
2146@example
2147pragma Source_File_Name
2148  (Spec_File_Name => ".ads", Dot_Replacement => "-");
2149pragma Source_File_Name
2150  (Body_File_Name => ".adb", Dot_Replacement => "-");
2151@end example
2152
2153Our final example implements a scheme typically used with one of the
2154Ada 83 compilers, where the separator character for subunits was '__'
2155(two underscores), specs were identified by adding @code{_.ADA}, bodies
2156by adding @code{.ADA}, and subunits by
2157adding @code{.SEP}. All file names were
2158upper case. Child units were not present of course since this was an
2159Ada 83 compiler, but it seems reasonable to extend this scheme to use
2160the same double underscore separator for child units.
2161
2162@example
2163pragma Source_File_Name
2164  (Spec_File_Name => "_.ADA",
2165   Dot_Replacement => "__",
2166   Casing = Uppercase);
2167pragma Source_File_Name
2168  (Body_File_Name => ".ADA",
2169   Dot_Replacement => "__",
2170   Casing = Uppercase);
2171pragma Source_File_Name
2172  (Subunit_File_Name => ".SEP",
2173   Dot_Replacement => "__",
2174   Casing = Uppercase);
2175@end example
2176
2177@geindex gnatname
2178
2179@node Handling Arbitrary File Naming Conventions with gnatname,File Name Krunching with gnatkr,Alternative File Naming Schemes,File Naming Topics and Utilities
2180@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}
2181@subsection Handling Arbitrary File Naming Conventions with @cite{gnatname}
2182
2183
2184@geindex File Naming Conventions
2185
2186@menu
2187* Arbitrary File Naming Conventions::
2188* Running gnatname::
2189* Switches for gnatname::
2190* Examples of gnatname Usage::
2191
2192@end menu
2193
2194@node Arbitrary File Naming Conventions,Running gnatname,,Handling Arbitrary File Naming Conventions with gnatname
2195@anchor{gnat_ugn/the_gnat_compilation_model arbitrary-file-naming-conventions}@anchor{5d}@anchor{gnat_ugn/the_gnat_compilation_model id13}@anchor{5e}
2196@subsubsection Arbitrary File Naming Conventions
2197
2198
2199The GNAT compiler must be able to know the source file name of a compilation
2200unit.  When using the standard GNAT default file naming conventions
2201(@cite{.ads} for specs, @cite{.adb} for bodies), the GNAT compiler
2202does not need additional information.
2203
2204When the source file names do not follow the standard GNAT default file naming
2205conventions, the GNAT compiler must be given additional information through
2206a configuration pragmas file (@ref{16,,Configuration Pragmas})
2207or a project file.
2208When the non-standard file naming conventions are well-defined,
2209a small number of pragmas @cite{Source_File_Name} specifying a naming pattern
2210(@ref{5a,,Alternative File Naming Schemes}) may be sufficient. However,
2211if the file naming conventions are irregular or arbitrary, a number
2212of pragma @cite{Source_File_Name} for individual compilation units
2213must be defined.
2214To help maintain the correspondence between compilation unit names and
2215source file names within the compiler,
2216GNAT provides a tool @cite{gnatname} to generate the required pragmas for a
2217set of files.
2218
2219@node Running gnatname,Switches for gnatname,Arbitrary File Naming Conventions,Handling Arbitrary File Naming Conventions with gnatname
2220@anchor{gnat_ugn/the_gnat_compilation_model running-gnatname}@anchor{5f}@anchor{gnat_ugn/the_gnat_compilation_model id14}@anchor{60}
2221@subsubsection Running @cite{gnatname}
2222
2223
2224The usual form of the @cite{gnatname} command is:
2225
2226@example
2227$ gnatname [`switches`] `naming_pattern` [`naming_patterns`]
2228    [--and [`switches`] `naming_pattern` [`naming_patterns`]]
2229@end example
2230
2231All of the arguments are optional. If invoked without any argument,
2232@cite{gnatname} will display its usage.
2233
2234When used with at least one naming pattern, @cite{gnatname} will attempt to
2235find all the compilation units in files that follow at least one of the
2236naming patterns. To find these compilation units,
2237@cite{gnatname} will use the GNAT compiler in syntax-check-only mode on all
2238regular files.
2239
2240One or several Naming Patterns may be given as arguments to @cite{gnatname}.
2241Each Naming Pattern is enclosed between double quotes (or single
2242quotes on Windows).
2243A Naming Pattern is a regular expression similar to the wildcard patterns
2244used in file names by the Unix shells or the DOS prompt.
2245
2246@cite{gnatname} may be called with several sections of directories/patterns.
2247Sections are separated by switch @cite{--and}. In each section, there must be
2248at least one pattern. If no directory is specified in a section, the current
2249directory (or the project directory is @cite{-P} is used) is implied.
2250The options other that the directory switches and the patterns apply globally
2251even if they are in different sections.
2252
2253Examples of Naming Patterns are:
2254
2255@example
2256"*.[12].ada"
2257"*.ad[sb]*"
2258"body_*"    "spec_*"
2259@end example
2260
2261For a more complete description of the syntax of Naming Patterns,
2262see the second kind of regular expressions described in @code{g-regexp.ads}
2263(the 'Glob' regular expressions).
2264
2265When invoked with no switch @cite{-P}, @cite{gnatname} will create a
2266configuration pragmas file @code{gnat.adc} in the current working directory,
2267with pragmas @cite{Source_File_Name} for each file that contains a valid Ada
2268unit.
2269
2270@node Switches for gnatname,Examples of gnatname Usage,Running gnatname,Handling Arbitrary File Naming Conventions with gnatname
2271@anchor{gnat_ugn/the_gnat_compilation_model id15}@anchor{61}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatname}@anchor{62}
2272@subsubsection Switches for @cite{gnatname}
2273
2274
2275Switches for @cite{gnatname} must precede any specified Naming Pattern.
2276
2277You may specify any of the following switches to @cite{gnatname}:
2278
2279@geindex --version (gnatname)
2280
2281
2282@table @asis
2283
2284@item @code{--version}
2285
2286Display Copyright and version, then exit disregarding all other options.
2287@end table
2288
2289@geindex --help (gnatname)
2290
2291
2292@table @asis
2293
2294@item @code{--help}
2295
2296If @emph{--version} was not used, display usage, then exit disregarding
2297all other options.
2298
2299@item @code{--subdirs=@emph{dir}}
2300
2301Real object, library or exec directories are subdirectories <dir> of the
2302specified ones.
2303
2304@item @code{--no-backup}
2305
2306Do not create a backup copy of an existing project file.
2307
2308@item @code{--and}
2309
2310Start another section of directories/patterns.
2311@end table
2312
2313@geindex -c (gnatname)
2314
2315
2316@table @asis
2317
2318@item @code{-c@emph{filename}}
2319
2320Create a configuration pragmas file @code{filename} (instead of the default
2321@code{gnat.adc}).
2322There may be zero, one or more space between @emph{-c} and
2323@code{filename}.
2324@code{filename} may include directory information. @code{filename} must be
2325writable. There may be only one switch @emph{-c}.
2326When a switch @emph{-c} is
2327specified, no switch @emph{-P} may be specified (see below).
2328@end table
2329
2330@geindex -d (gnatname)
2331
2332
2333@table @asis
2334
2335@item @code{-d@emph{dir}}
2336
2337Look for source files in directory @code{dir}. There may be zero, one or more
2338spaces between @emph{-d} and @code{dir}.
2339@code{dir} may end with @cite{/**}, that is it may be of the form
2340@cite{root_dir/**}. In this case, the directory @cite{root_dir} and all of its
2341subdirectories, recursively, have to be searched for sources.
2342When a switch @emph{-d}
2343is specified, the current working directory will not be searched for source
2344files, unless it is explicitly specified with a @emph{-d}
2345or @emph{-D} switch.
2346Several switches @emph{-d} may be specified.
2347If @code{dir} is a relative path, it is relative to the directory of
2348the configuration pragmas file specified with switch
2349@emph{-c},
2350or to the directory of the project file specified with switch
2351@emph{-P} or,
2352if neither switch @emph{-c}
2353nor switch @emph{-P} are specified, it is relative to the
2354current working directory. The directory
2355specified with switch @emph{-d} must exist and be readable.
2356@end table
2357
2358@geindex -D (gnatname)
2359
2360
2361@table @asis
2362
2363@item @code{-D@emph{filename}}
2364
2365Look for source files in all directories listed in text file @code{filename}.
2366There may be zero, one or more spaces between @emph{-D}
2367and @code{filename}.
2368@code{filename} must be an existing, readable text file.
2369Each nonempty line in @code{filename} must be a directory.
2370Specifying switch @emph{-D} is equivalent to specifying as many
2371switches @emph{-d} as there are nonempty lines in
2372@code{file}.
2373
2374@item @code{-eL}
2375
2376Follow symbolic links when processing project files.
2377
2378@geindex -f (gnatname)
2379
2380@item @code{-f@emph{pattern}}
2381
2382Foreign patterns. Using this switch, it is possible to add sources of languages
2383other than Ada to the list of sources of a project file.
2384It is only useful if a -P switch is used.
2385For example,
2386
2387@example
2388gnatname -Pprj -f"*.c" "*.ada"
2389@end example
2390
2391will look for Ada units in all files with the @code{.ada} extension,
2392and will add to the list of file for project @code{prj.gpr} the C files
2393with extension @code{.c}.
2394
2395@geindex -h (gnatname)
2396
2397@item @code{-h}
2398
2399Output usage (help) information. The output is written to @code{stdout}.
2400
2401@geindex -P (gnatname)
2402
2403@item @code{-P@emph{proj}}
2404
2405Create or update project file @code{proj}. There may be zero, one or more space
2406between @emph{-P} and @code{proj}. @code{proj} may include directory
2407information. @code{proj} must be writable.
2408There may be only one switch @emph{-P}.
2409When a switch @emph{-P} is specified,
2410no switch @emph{-c} may be specified.
2411On all platforms, except on VMS, when @cite{gnatname} is invoked for an
2412existing project file <proj>.gpr, a backup copy of the project file is created
2413in the project directory with file name <proj>.gpr.saved_x. 'x' is the first
2414non negative number that makes this backup copy a new file.
2415
2416@geindex -v (gnatname)
2417
2418@item @code{-v}
2419
2420Verbose mode. Output detailed explanation of behavior to @code{stdout}.
2421This includes name of the file written, the name of the directories to search
2422and, for each file in those directories whose name matches at least one of
2423the Naming Patterns, an indication of whether the file contains a unit,
2424and if so the name of the unit.
2425@end table
2426
2427@geindex -v -v (gnatname)
2428
2429
2430@table @asis
2431
2432@item @code{-v -v}
2433
2434Very Verbose mode. In addition to the output produced in verbose mode,
2435for each file in the searched directories whose name matches none of
2436the Naming Patterns, an indication is given that there is no match.
2437
2438@geindex -x (gnatname)
2439
2440@item @code{-x@emph{pattern}}
2441
2442Excluded patterns. Using this switch, it is possible to exclude some files
2443that would match the name patterns. For example,
2444
2445@example
2446gnatname -x "*_nt.ada" "*.ada"
2447@end example
2448
2449will look for Ada units in all files with the @code{.ada} extension,
2450except those whose names end with @code{_nt.ada}.
2451@end table
2452
2453@node Examples of gnatname Usage,,Switches for gnatname,Handling Arbitrary File Naming Conventions with gnatname
2454@anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatname-usage}@anchor{63}@anchor{gnat_ugn/the_gnat_compilation_model id16}@anchor{64}
2455@subsubsection Examples of @cite{gnatname} Usage
2456
2457
2458@example
2459$ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
2460@end example
2461
2462In this example, the directory @code{/home/me} must already exist
2463and be writable. In addition, the directory
2464@code{/home/me/sources} (specified by
2465@emph{-d sources}) must exist and be readable.
2466
2467Note the optional spaces after @emph{-c} and @emph{-d}.
2468
2469@example
2470$ gnatname -P/home/me/proj -x "*_nt_body.ada"
2471-dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
2472@end example
2473
2474Note that several switches @emph{-d} may be used,
2475even in conjunction with one or several switches
2476@emph{-D}. Several Naming Patterns and one excluded pattern
2477are used in this example.
2478
2479@node File Name Krunching with gnatkr,Renaming Files with gnatchop,Handling Arbitrary File Naming Conventions with gnatname,File Naming Topics and Utilities
2480@anchor{gnat_ugn/the_gnat_compilation_model file-name-krunching-with-gnatkr}@anchor{65}@anchor{gnat_ugn/the_gnat_compilation_model id17}@anchor{66}
2481@subsection File Name Krunching with @cite{gnatkr}
2482
2483
2484@geindex gnatkr
2485
2486This chapter discusses the method used by the compiler to shorten
2487the default file names chosen for Ada units so that they do not
2488exceed the maximum length permitted. It also describes the
2489@cite{gnatkr} utility that can be used to determine the result of
2490applying this shortening.
2491
2492@menu
2493* About gnatkr::
2494* Using gnatkr::
2495* Krunching Method::
2496* Examples of gnatkr Usage::
2497
2498@end menu
2499
2500@node About gnatkr,Using gnatkr,,File Name Krunching with gnatkr
2501@anchor{gnat_ugn/the_gnat_compilation_model id18}@anchor{67}@anchor{gnat_ugn/the_gnat_compilation_model about-gnatkr}@anchor{68}
2502@subsubsection About @cite{gnatkr}
2503
2504
2505The default file naming rule in GNAT
2506is that the file name must be derived from
2507the unit name. The exact default rule is as follows:
2508
2509
2510@itemize *
2511
2512@item
2513Take the unit name and replace all dots by hyphens.
2514
2515@item
2516If such a replacement occurs in the
2517second character position of a name, and the first character is
2518@code{a}, @code{g}, @code{s}, or @code{i},
2519then replace the dot by the character
2520@code{~} (tilde)
2521instead of a minus.
2522
2523The reason for this exception is to avoid clashes
2524with the standard names for children of System, Ada, Interfaces,
2525and GNAT, which use the prefixes
2526@code{s-}, @code{a-}, @code{i-}, and @code{g-},
2527respectively.
2528@end itemize
2529
2530The @code{-gnatk@emph{nn}}
2531switch of the compiler activates a 'krunching'
2532circuit that limits file names to nn characters (where nn is a decimal
2533integer).
2534
2535The @cite{gnatkr} utility can be used to determine the krunched name for
2536a given file, when krunched to a specified maximum length.
2537
2538@node Using gnatkr,Krunching Method,About gnatkr,File Name Krunching with gnatkr
2539@anchor{gnat_ugn/the_gnat_compilation_model id19}@anchor{69}@anchor{gnat_ugn/the_gnat_compilation_model using-gnatkr}@anchor{56}
2540@subsubsection Using @cite{gnatkr}
2541
2542
2543The @cite{gnatkr} command has the form:
2544
2545@example
2546$ gnatkr `name` [`length`]
2547@end example
2548
2549@cite{name} is the uncrunched file name, derived from the name of the unit
2550in the standard manner described in the previous section (i.e., in particular
2551all dots are replaced by hyphens). The file name may or may not have an
2552extension (defined as a suffix of the form period followed by arbitrary
2553characters other than period). If an extension is present then it will
2554be preserved in the output. For example, when krunching @code{hellofile.ads}
2555to eight characters, the result will be hellofil.ads.
2556
2557Note: for compatibility with previous versions of @cite{gnatkr} dots may
2558appear in the name instead of hyphens, but the last dot will always be
2559taken as the start of an extension. So if @cite{gnatkr} is given an argument
2560such as @code{Hello.World.adb} it will be treated exactly as if the first
2561period had been a hyphen, and for example krunching to eight characters
2562gives the result @code{hellworl.adb}.
2563
2564Note that the result is always all lower case.
2565Characters of the other case are folded as required.
2566
2567@cite{length} represents the length of the krunched name. The default
2568when no argument is given is 8 characters. A length of zero stands for
2569unlimited, in other words do not chop except for system files where the
2570implied crunching length is always eight characters.
2571
2572The output is the krunched name. The output has an extension only if the
2573original argument was a file name with an extension.
2574
2575@node Krunching Method,Examples of gnatkr Usage,Using gnatkr,File Name Krunching with gnatkr
2576@anchor{gnat_ugn/the_gnat_compilation_model id20}@anchor{6a}@anchor{gnat_ugn/the_gnat_compilation_model krunching-method}@anchor{6b}
2577@subsubsection Krunching Method
2578
2579
2580The initial file name is determined by the name of the unit that the file
2581contains. The name is formed by taking the full expanded name of the
2582unit and replacing the separating dots with hyphens and
2583using lowercase
2584for all letters, except that a hyphen in the second character position is
2585replaced by a tilde if the first character is
2586@code{a}, @code{i}, @code{g}, or @code{s}.
2587The extension is @cite{.ads} for a
2588spec and @cite{.adb} for a body.
2589Krunching does not affect the extension, but the file name is shortened to
2590the specified length by following these rules:
2591
2592
2593@itemize *
2594
2595@item
2596The name is divided into segments separated by hyphens, tildes or
2597underscores and all hyphens, tildes, and underscores are
2598eliminated. If this leaves the name short enough, we are done.
2599
2600@item
2601If the name is too long, the longest segment is located (left-most
2602if there are two of equal length), and shortened by dropping
2603its last character. This is repeated until the name is short enough.
2604
2605As an example, consider the krunching of @code{our-strings-wide_fixed.adb}
2606to fit the name into 8 characters as required by some operating systems:
2607
2608@example
2609our-strings-wide_fixed 22
2610our strings wide fixed 19
2611our string  wide fixed 18
2612our strin   wide fixed 17
2613our stri    wide fixed 16
2614our stri    wide fixe  15
2615our str     wide fixe  14
2616our str     wid  fixe  13
2617our str     wid  fix   12
2618ou  str     wid  fix   11
2619ou  st      wid  fix   10
2620ou  st      wi   fix   9
2621ou  st      wi   fi    8
2622Final file name: oustwifi.adb
2623@end example
2624
2625@item
2626The file names for all predefined units are always krunched to eight
2627characters. The krunching of these predefined units uses the following
2628special prefix replacements:
2629
2630
2631@multitable {xxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx}
2632@item
2633
2634Prefix
2635
2636@tab
2637
2638Replacement
2639
2640@item
2641
2642@code{ada-}
2643
2644@tab
2645
2646@code{a-}
2647
2648@item
2649
2650@code{gnat-}
2651
2652@tab
2653
2654@code{g-}
2655
2656@item
2657
2658@code{interfac es-}
2659
2660@tab
2661
2662@code{i-}
2663
2664@item
2665
2666@code{system-}
2667
2668@tab
2669
2670@code{s-}
2671
2672@end multitable
2673
2674
2675These system files have a hyphen in the second character position. That
2676is why normal user files replace such a character with a
2677tilde, to avoid confusion with system file names.
2678
2679As an example of this special rule, consider
2680@code{ada-strings-wide_fixed.adb}, which gets krunched as follows:
2681
2682@example
2683ada-strings-wide_fixed 22
2684a-  strings wide fixed 18
2685a-  string  wide fixed 17
2686a-  strin   wide fixed 16
2687a-  stri    wide fixed 15
2688a-  stri    wide fixe  14
2689a-  str     wide fixe  13
2690a-  str     wid  fixe  12
2691a-  str     wid  fix   11
2692a-  st      wid  fix   10
2693a-  st      wi   fix   9
2694a-  st      wi   fi    8
2695Final file name: a-stwifi.adb
2696@end example
2697@end itemize
2698
2699Of course no file shortening algorithm can guarantee uniqueness over all
2700possible unit names, and if file name krunching is used then it is your
2701responsibility to ensure that no name clashes occur. The utility
2702program @cite{gnatkr} is supplied for conveniently determining the
2703krunched name of a file.
2704
2705@node Examples of gnatkr Usage,,Krunching Method,File Name Krunching with gnatkr
2706@anchor{gnat_ugn/the_gnat_compilation_model id21}@anchor{6c}@anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatkr-usage}@anchor{6d}
2707@subsubsection Examples of @cite{gnatkr} Usage
2708
2709
2710@example
2711$ gnatkr very_long_unit_name.ads      --> velounna.ads
2712$ gnatkr grandparent-parent-child.ads --> grparchi.ads
2713$ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
2714$ gnatkr grandparent-parent-child     --> grparchi
2715$ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
2716$ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
2717@end example
2718
2719@node Renaming Files with gnatchop,,File Name Krunching with gnatkr,File Naming Topics and Utilities
2720@anchor{gnat_ugn/the_gnat_compilation_model id22}@anchor{6e}@anchor{gnat_ugn/the_gnat_compilation_model renaming-files-with-gnatchop}@anchor{38}
2721@subsection Renaming Files with @cite{gnatchop}
2722
2723
2724@geindex gnatchop
2725
2726This chapter discusses how to handle files with multiple units by using
2727the @cite{gnatchop} utility. This utility is also useful in renaming
2728files to meet the standard GNAT default file naming conventions.
2729
2730@menu
2731* Handling Files with Multiple Units::
2732* Operating gnatchop in Compilation Mode::
2733* Command Line for gnatchop::
2734* Switches for gnatchop::
2735* Examples of gnatchop Usage::
2736
2737@end menu
2738
2739@node Handling Files with Multiple Units,Operating gnatchop in Compilation Mode,,Renaming Files with gnatchop
2740@anchor{gnat_ugn/the_gnat_compilation_model id23}@anchor{6f}@anchor{gnat_ugn/the_gnat_compilation_model handling-files-with-multiple-units}@anchor{70}
2741@subsubsection Handling Files with Multiple Units
2742
2743
2744The basic compilation model of GNAT requires that a file submitted to the
2745compiler have only one unit and there be a strict correspondence
2746between the file name and the unit name.
2747
2748The @cite{gnatchop} utility allows both of these rules to be relaxed,
2749allowing GNAT to process files which contain multiple compilation units
2750and files with arbitrary file names. @cite{gnatchop}
2751reads the specified file and generates one or more output files,
2752containing one unit per file. The unit and the file name correspond,
2753as required by GNAT.
2754
2755If you want to permanently restructure a set of 'foreign' files so that
2756they match the GNAT rules, and do the remaining development using the
2757GNAT structure, you can simply use @emph{gnatchop} once, generate the
2758new set of files and work with them from that point on.
2759
2760Alternatively, if you want to keep your files in the 'foreign' format,
2761perhaps to maintain compatibility with some other Ada compilation
2762system, you can set up a procedure where you use @emph{gnatchop} each
2763time you compile, regarding the source files that it writes as temporary
2764files that you throw away.
2765
2766Note that if your file containing multiple units starts with a byte order
2767mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
2768will each start with a copy of this BOM, meaning that they can be compiled
2769automatically in UTF-8 mode without needing to specify an explicit encoding.
2770
2771@node Operating gnatchop in Compilation Mode,Command Line for gnatchop,Handling Files with Multiple Units,Renaming Files with gnatchop
2772@anchor{gnat_ugn/the_gnat_compilation_model operating-gnatchop-in-compilation-mode}@anchor{71}@anchor{gnat_ugn/the_gnat_compilation_model id24}@anchor{72}
2773@subsubsection Operating gnatchop in Compilation Mode
2774
2775
2776The basic function of @cite{gnatchop} is to take a file with multiple units
2777and split it into separate files. The boundary between files is reasonably
2778clear, except for the issue of comments and pragmas. In default mode, the
2779rule is that any pragmas between units belong to the previous unit, except
2780that configuration pragmas always belong to the following unit. Any comments
2781belong to the following unit. These rules
2782almost always result in the right choice of
2783the split point without needing to mark it explicitly and most users will
2784find this default to be what they want. In this default mode it is incorrect to
2785submit a file containing only configuration pragmas, or one that ends in
2786configuration pragmas, to @cite{gnatchop}.
2787
2788However, using a special option to activate 'compilation mode',
2789@cite{gnatchop}
2790can perform another function, which is to provide exactly the semantics
2791required by the RM for handling of configuration pragmas in a compilation.
2792In the absence of configuration pragmas (at the main file level), this
2793option has no effect, but it causes such configuration pragmas to be handled
2794in a quite different manner.
2795
2796First, in compilation mode, if @cite{gnatchop} is given a file that consists of
2797only configuration pragmas, then this file is appended to the
2798@code{gnat.adc} file in the current directory. This behavior provides
2799the required behavior described in the RM for the actions to be taken
2800on submitting such a file to the compiler, namely that these pragmas
2801should apply to all subsequent compilations in the same compilation
2802environment. Using GNAT, the current directory, possibly containing a
2803@code{gnat.adc} file is the representation
2804of a compilation environment. For more information on the
2805@code{gnat.adc} file, see @ref{58,,Handling of Configuration Pragmas}.
2806
2807Second, in compilation mode, if @cite{gnatchop}
2808is given a file that starts with
2809configuration pragmas, and contains one or more units, then these
2810configuration pragmas are prepended to each of the chopped files. This
2811behavior provides the required behavior described in the RM for the
2812actions to be taken on compiling such a file, namely that the pragmas
2813apply to all units in the compilation, but not to subsequently compiled
2814units.
2815
2816Finally, if configuration pragmas appear between units, they are appended
2817to the previous unit. This results in the previous unit being illegal,
2818since the compiler does not accept configuration pragmas that follow
2819a unit. This provides the required RM behavior that forbids configuration
2820pragmas other than those preceding the first compilation unit of a
2821compilation.
2822
2823For most purposes, @cite{gnatchop} will be used in default mode. The
2824compilation mode described above is used only if you need exactly
2825accurate behavior with respect to compilations, and you have files
2826that contain multiple units and configuration pragmas. In this
2827circumstance the use of @cite{gnatchop} with the compilation mode
2828switch provides the required behavior, and is for example the mode
2829in which GNAT processes the ACVC tests.
2830
2831@node Command Line for gnatchop,Switches for gnatchop,Operating gnatchop in Compilation Mode,Renaming Files with gnatchop
2832@anchor{gnat_ugn/the_gnat_compilation_model id25}@anchor{73}@anchor{gnat_ugn/the_gnat_compilation_model command-line-for-gnatchop}@anchor{74}
2833@subsubsection Command Line for @cite{gnatchop}
2834
2835
2836The @cite{gnatchop} command has the form:
2837
2838@example
2839$ gnatchop switches file_name [file_name ...]
2840      [directory]
2841@end example
2842
2843The only required argument is the file name of the file to be chopped.
2844There are no restrictions on the form of this file name. The file itself
2845contains one or more Ada units, in normal GNAT format, concatenated
2846together. As shown, more than one file may be presented to be chopped.
2847
2848When run in default mode, @cite{gnatchop} generates one output file in
2849the current directory for each unit in each of the files.
2850
2851@cite{directory}, if specified, gives the name of the directory to which
2852the output files will be written. If it is not specified, all files are
2853written to the current directory.
2854
2855For example, given a
2856file called @code{hellofiles} containing
2857
2858@example
2859procedure Hello;
2860
2861with Ada.Text_IO; use Ada.Text_IO;
2862procedure Hello is
2863begin
2864   Put_Line ("Hello");
2865end Hello;
2866@end example
2867
2868the command
2869
2870@example
2871$ gnatchop hellofiles
2872@end example
2873
2874generates two files in the current directory, one called
2875@code{hello.ads} containing the single line that is the procedure spec,
2876and the other called @code{hello.adb} containing the remaining text. The
2877original file is not affected. The generated files can be compiled in
2878the normal manner.
2879
2880When gnatchop is invoked on a file that is empty or that contains only empty
2881lines and/or comments, gnatchop will not fail, but will not produce any
2882new sources.
2883
2884For example, given a
2885file called @code{toto.txt} containing
2886
2887@example
2888--  Just a comment
2889@end example
2890
2891the command
2892
2893@example
2894$ gnatchop toto.txt
2895@end example
2896
2897will not produce any new file and will result in the following warnings:
2898
2899@example
2900toto.txt:1:01: warning: empty file, contains no compilation units
2901no compilation units found
2902no source files written
2903@end example
2904
2905@node Switches for gnatchop,Examples of gnatchop Usage,Command Line for gnatchop,Renaming Files with gnatchop
2906@anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatchop}@anchor{75}@anchor{gnat_ugn/the_gnat_compilation_model id26}@anchor{76}
2907@subsubsection Switches for @cite{gnatchop}
2908
2909
2910@emph{gnatchop} recognizes the following switches:
2911
2912@geindex --version (gnatchop)
2913
2914
2915@table @asis
2916
2917@item @code{--version}
2918
2919Display Copyright and version, then exit disregarding all other options.
2920@end table
2921
2922@geindex --help (gnatchop)
2923
2924
2925@table @asis
2926
2927@item @code{--help}
2928
2929If @emph{--version} was not used, display usage, then exit disregarding
2930all other options.
2931@end table
2932
2933@geindex -c (gnatchop)
2934
2935
2936@table @asis
2937
2938@item @code{-c}
2939
2940Causes @cite{gnatchop} to operate in compilation mode, in which
2941configuration pragmas are handled according to strict RM rules. See
2942previous section for a full description of this mode.
2943
2944@item @code{-gnat@emph{xxx}}
2945
2946This passes the given @emph{-gnat`xxx*` switch to `gnat` which is
2947used to parse the given file. Not all `xxx` options make sense,
2948but for example, the use of *-gnati2} allows @cite{gnatchop} to
2949process a source file that uses Latin-2 coding for identifiers.
2950
2951@item @code{-h}
2952
2953Causes @cite{gnatchop} to generate a brief help summary to the standard
2954output file showing usage information.
2955@end table
2956
2957@geindex -k (gnatchop)
2958
2959
2960@table @asis
2961
2962@item @code{-k@emph{mm}}
2963
2964Limit generated file names to the specified number @cite{mm}
2965of characters.
2966This is useful if the
2967resulting set of files is required to be interoperable with systems
2968which limit the length of file names.
2969No space is allowed between the @emph{-k} and the numeric value. The numeric
2970value may be omitted in which case a default of @emph{-k8},
2971suitable for use
2972with DOS-like file systems, is used. If no @emph{-k} switch
2973is present then
2974there is no limit on the length of file names.
2975@end table
2976
2977@geindex -p (gnatchop)
2978
2979
2980@table @asis
2981
2982@item @code{-p}
2983
2984Causes the file modification time stamp of the input file to be
2985preserved and used for the time stamp of the output file(s). This may be
2986useful for preserving coherency of time stamps in an environment where
2987@cite{gnatchop} is used as part of a standard build process.
2988@end table
2989
2990@geindex -q (gnatchop)
2991
2992
2993@table @asis
2994
2995@item @code{-q}
2996
2997Causes output of informational messages indicating the set of generated
2998files to be suppressed. Warnings and error messages are unaffected.
2999@end table
3000
3001@geindex -r (gnatchop)
3002
3003@geindex Source_Reference pragmas
3004
3005
3006@table @asis
3007
3008@item @code{-r}
3009
3010Generate @cite{Source_Reference} pragmas. Use this switch if the output
3011files are regarded as temporary and development is to be done in terms
3012of the original unchopped file. This switch causes
3013@cite{Source_Reference} pragmas to be inserted into each of the
3014generated files to refers back to the original file name and line number.
3015The result is that all error messages refer back to the original
3016unchopped file.
3017In addition, the debugging information placed into the object file (when
3018the @emph{-g} switch of @emph{gcc} or @emph{gnatmake} is
3019specified)
3020also refers back to this original file so that tools like profilers and
3021debuggers will give information in terms of the original unchopped file.
3022
3023If the original file to be chopped itself contains
3024a @cite{Source_Reference}
3025pragma referencing a third file, then gnatchop respects
3026this pragma, and the generated @cite{Source_Reference} pragmas
3027in the chopped file refer to the original file, with appropriate
3028line numbers. This is particularly useful when @cite{gnatchop}
3029is used in conjunction with @cite{gnatprep} to compile files that
3030contain preprocessing statements and multiple units.
3031@end table
3032
3033@geindex -v (gnatchop)
3034
3035
3036@table @asis
3037
3038@item @code{-v}
3039
3040Causes @cite{gnatchop} to operate in verbose mode. The version
3041number and copyright notice are output, as well as exact copies of
3042the gnat1 commands spawned to obtain the chop control information.
3043@end table
3044
3045@geindex -w (gnatchop)
3046
3047
3048@table @asis
3049
3050@item @code{-w}
3051
3052Overwrite existing file names. Normally @cite{gnatchop} regards it as a
3053fatal error if there is already a file with the same name as a
3054file it would otherwise output, in other words if the files to be
3055chopped contain duplicated units. This switch bypasses this
3056check, and causes all but the last instance of such duplicated
3057units to be skipped.
3058@end table
3059
3060@geindex --GCC= (gnatchop)
3061
3062
3063@table @asis
3064
3065@item @code{--GCC=@emph{xxxx}}
3066
3067Specify the path of the GNAT parser to be used. When this switch is used,
3068no attempt is made to add the prefix to the GNAT parser executable.
3069@end table
3070
3071@node Examples of gnatchop Usage,,Switches for gnatchop,Renaming Files with gnatchop
3072@anchor{gnat_ugn/the_gnat_compilation_model id27}@anchor{77}@anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatchop-usage}@anchor{78}
3073@subsubsection Examples of @cite{gnatchop} Usage
3074
3075
3076@example
3077$ gnatchop -w hello_s.ada prerelease/files
3078@end example
3079
3080Chops the source file @code{hello_s.ada}. The output files will be
3081placed in the directory @code{prerelease/files},
3082overwriting any
3083files with matching names in that directory (no files in the current
3084directory are modified).
3085
3086@example
3087$ gnatchop archive
3088@end example
3089
3090Chops the source file @code{archive}
3091into the current directory. One
3092useful application of @cite{gnatchop} is in sending sets of sources
3093around, for example in email messages. The required sources are simply
3094concatenated (for example, using a Unix @cite{cat}
3095command), and then
3096@emph{gnatchop} is used at the other end to reconstitute the original
3097file names.
3098
3099@example
3100$ gnatchop file1 file2 file3 direc
3101@end example
3102
3103Chops all units in files @code{file1}, @code{file2}, @code{file3}, placing
3104the resulting files in the directory @code{direc}. Note that if any units
3105occur more than once anywhere within this set of files, an error message
3106is generated, and no files are written. To override this check, use the
3107@emph{-w} switch,
3108in which case the last occurrence in the last file will
3109be the one that is output, and earlier duplicate occurrences for a given
3110unit will be skipped.
3111
3112@node Configuration Pragmas,Generating Object Files,File Naming Topics and Utilities,The GNAT Compilation Model
3113@anchor{gnat_ugn/the_gnat_compilation_model id28}@anchor{79}@anchor{gnat_ugn/the_gnat_compilation_model configuration-pragmas}@anchor{16}
3114@section Configuration Pragmas
3115
3116
3117@geindex Configuration pragmas
3118
3119@geindex Pragmas
3120@geindex configuration
3121
3122Configuration pragmas include those pragmas described as
3123such in the Ada Reference Manual, as well as
3124implementation-dependent pragmas that are configuration pragmas.
3125See the @cite{Implementation_Defined_Pragmas} chapter in the
3126@cite{GNAT_Reference_Manual} for details on these
3127additional GNAT-specific configuration pragmas.
3128Most notably, the pragma @cite{Source_File_Name}, which allows
3129specifying non-default names for source files, is a configuration
3130pragma. The following is a complete list of configuration pragmas
3131recognized by GNAT:
3132
3133@example
3134Ada_83
3135Ada_95
3136Ada_05
3137Ada_2005
3138Ada_12
3139Ada_2012
3140Allow_Integer_Address
3141Annotate
3142Assertion_Policy
3143Assume_No_Invalid_Values
3144C_Pass_By_Copy
3145Check_Name
3146Check_Policy
3147Compile_Time_Error
3148Compile_Time_Warning
3149Compiler_Unit
3150Component_Alignment
3151Convention_Identifier
3152Debug_Policy
3153Detect_Blocking
3154Default_Storage_Pool
3155Discard_Names
3156Elaboration_Checks
3157Eliminate
3158Extend_System
3159Extensions_Allowed
3160External_Name_Casing
3161Fast_Math
3162Favor_Top_Level
3163Float_Representation
3164Implicit_Packing
3165Initialize_Scalars
3166Interrupt_State
3167License
3168Locking_Policy
3169Long_Float
3170No_Run_Time
3171No_Strict_Aliasing
3172Normalize_Scalars
3173Optimize_Alignment
3174Persistent_BSS
3175Polling
3176Priority_Specific_Dispatching
3177Profile
3178Profile_Warnings
3179Propagate_Exceptions
3180Queuing_Policy
3181Ravenscar
3182Restricted_Run_Time
3183Restrictions
3184Restrictions_Warnings
3185Reviewable
3186Short_Circuit_And_Or
3187Source_File_Name
3188Source_File_Name_Project
3189SPARK_Mode
3190Style_Checks
3191Suppress
3192Suppress_Exception_Locations
3193Task_Dispatching_Policy
3194Universal_Data
3195Unsuppress
3196Use_VADS_Size
3197Validity_Checks
3198Warnings
3199Wide_Character_Encoding
3200@end example
3201
3202@menu
3203* Handling of Configuration Pragmas::
3204* The Configuration Pragmas Files::
3205
3206@end menu
3207
3208@node Handling of Configuration Pragmas,The Configuration Pragmas Files,,Configuration Pragmas
3209@anchor{gnat_ugn/the_gnat_compilation_model id29}@anchor{7a}@anchor{gnat_ugn/the_gnat_compilation_model handling-of-configuration-pragmas}@anchor{58}
3210@subsection Handling of Configuration Pragmas
3211
3212
3213Configuration pragmas may either appear at the start of a compilation
3214unit, or they can appear in a configuration pragma file to apply to
3215all compilations performed in a given compilation environment.
3216
3217GNAT also provides the @cite{gnatchop} utility to provide an automatic
3218way to handle configuration pragmas following the semantics for
3219compilations (that is, files with multiple units), described in the RM.
3220See @ref{71,,Operating gnatchop in Compilation Mode} for details.
3221However, for most purposes, it will be more convenient to edit the
3222@code{gnat.adc} file that contains configuration pragmas directly,
3223as described in the following section.
3224
3225In the case of @cite{Restrictions} pragmas appearing as configuration
3226pragmas in individual compilation units, the exact handling depends on
3227the type of restriction.
3228
3229Restrictions that require partition-wide consistency (like
3230@cite{No_Tasking}) are
3231recognized wherever they appear
3232and can be freely inherited, e.g. from a @emph{with}ed unit to the @emph{with}ing
3233unit. This makes sense since the binder will in any case insist on seeing
3234consistent use, so any unit not conforming to any restrictions that are
3235anywhere in the partition will be rejected, and you might as well find
3236that out at compile time rather than at bind time.
3237
3238For restrictions that do not require partition-wide consistency, e.g.
3239SPARK or No_Implementation_Attributes, in general the restriction applies
3240only to the unit in which the pragma appears, and not to any other units.
3241
3242The exception is No_Elaboration_Code which always applies to the entire
3243object file from a compilation, i.e. to the body, spec, and all subunits.
3244This restriction can be specified in a configuration pragma file, or it
3245can be on the body and/or the spec (in eithe case it applies to all the
3246relevant units). It can appear on a subunit only if it has previously
3247appeared in the body of spec.
3248
3249@node The Configuration Pragmas Files,,Handling of Configuration Pragmas,Configuration Pragmas
3250@anchor{gnat_ugn/the_gnat_compilation_model the-configuration-pragmas-files}@anchor{7b}@anchor{gnat_ugn/the_gnat_compilation_model id30}@anchor{7c}
3251@subsection The Configuration Pragmas Files
3252
3253
3254@geindex gnat.adc
3255
3256In GNAT a compilation environment is defined by the current
3257directory at the time that a compile command is given. This current
3258directory is searched for a file whose name is @code{gnat.adc}. If
3259this file is present, it is expected to contain one or more
3260configuration pragmas that will be applied to the current compilation.
3261However, if the switch @emph{-gnatA} is used, @code{gnat.adc} is not
3262considered. When taken into account, @code{gnat.adc} is added to the
3263dependencies, so that if @code{gnat.adc} is modified later, an invocation of
3264@emph{gnatmake} will recompile the source.
3265
3266Configuration pragmas may be entered into the @code{gnat.adc} file
3267either by running @cite{gnatchop} on a source file that consists only of
3268configuration pragmas, or more conveniently by direct editing of the
3269@code{gnat.adc} file, which is a standard format source file.
3270
3271Besides @code{gnat.adc}, additional files containing configuration
3272pragmas may be applied to the current compilation using the switch
3273@code{-gnatec=@emph{path}} where @cite{path} must designate an existing file that
3274contains only configuration pragmas. These configuration pragmas are
3275in addition to those found in @code{gnat.adc} (provided @code{gnat.adc}
3276is present and switch @emph{-gnatA} is not used).
3277
3278It is allowable to specify several switches @emph{-gnatec=}, all of which
3279will be taken into account.
3280
3281Files containing configuration pragmas specified with switches
3282@emph{-gnatec=} are added to the dependencies, unless they are
3283temporary files. A file is considered temporary if its name ends in
3284@code{.tmp} or @code{.TMP}. Certain tools follow this naming
3285convention because they pass information to @emph{gcc} via
3286temporary files that are immediately deleted; it doesn't make sense to
3287depend on a file that no longer exists. Such tools include
3288@emph{gprbuild}, @emph{gnatmake}, and @emph{gnatcheck}.
3289
3290If you are using project file, a separate mechanism is provided using
3291project attributes, see @ref{7d,,Specifying Configuration Pragmas} for more
3292details.
3293
3294@node Generating Object Files,Source Dependencies,Configuration Pragmas,The GNAT Compilation Model
3295@anchor{gnat_ugn/the_gnat_compilation_model generating-object-files}@anchor{42}@anchor{gnat_ugn/the_gnat_compilation_model id31}@anchor{7e}
3296@section Generating Object Files
3297
3298
3299An Ada program consists of a set of source files, and the first step in
3300compiling the program is to generate the corresponding object files.
3301These are generated by compiling a subset of these source files.
3302The files you need to compile are the following:
3303
3304
3305@itemize *
3306
3307@item
3308If a package spec has no body, compile the package spec to produce the
3309object file for the package.
3310
3311@item
3312If a package has both a spec and a body, compile the body to produce the
3313object file for the package. The source file for the package spec need
3314not be compiled in this case because there is only one object file, which
3315contains the code for both the spec and body of the package.
3316
3317@item
3318For a subprogram, compile the subprogram body to produce the object file
3319for the subprogram. The spec, if one is present, is as usual in a
3320separate file, and need not be compiled.
3321@end itemize
3322
3323@geindex Subunits
3324
3325
3326@itemize *
3327
3328@item
3329In the case of subunits, only compile the parent unit. A single object
3330file is generated for the entire subunit tree, which includes all the
3331subunits.
3332
3333@item
3334Compile child units independently of their parent units
3335(though, of course, the spec of all the ancestor unit must be present in order
3336to compile a child unit).
3337
3338@geindex Generics
3339
3340@item
3341Compile generic units in the same manner as any other units. The object
3342files in this case are small dummy files that contain at most the
3343flag used for elaboration checking. This is because GNAT always handles generic
3344instantiation by means of macro expansion. However, it is still necessary to
3345compile generic units, for dependency checking and elaboration purposes.
3346@end itemize
3347
3348The preceding rules describe the set of files that must be compiled to
3349generate the object files for a program. Each object file has the same
3350name as the corresponding source file, except that the extension is
3351@code{.o} as usual.
3352
3353You may wish to compile other files for the purpose of checking their
3354syntactic and semantic correctness. For example, in the case where a
3355package has a separate spec and body, you would not normally compile the
3356spec. However, it is convenient in practice to compile the spec to make
3357sure it is error-free before compiling clients of this spec, because such
3358compilations will fail if there is an error in the spec.
3359
3360GNAT provides an option for compiling such files purely for the
3361purposes of checking correctness; such compilations are not required as
3362part of the process of building a program. To compile a file in this
3363checking mode, use the @emph{-gnatc} switch.
3364
3365@node Source Dependencies,The Ada Library Information Files,Generating Object Files,The GNAT Compilation Model
3366@anchor{gnat_ugn/the_gnat_compilation_model id32}@anchor{7f}@anchor{gnat_ugn/the_gnat_compilation_model source-dependencies}@anchor{43}
3367@section Source Dependencies
3368
3369
3370A given object file clearly depends on the source file which is compiled
3371to produce it. Here we are using "depends" in the sense of a typical
3372@cite{make} utility; in other words, an object file depends on a source
3373file if changes to the source file require the object file to be
3374recompiled.
3375In addition to this basic dependency, a given object may depend on
3376additional source files as follows:
3377
3378
3379@itemize *
3380
3381@item
3382If a file being compiled @emph{with}s a unit @cite{X}, the object file
3383depends on the file containing the spec of unit @cite{X}. This includes
3384files that are @emph{with}ed implicitly either because they are parents
3385of @emph{with}ed child units or they are run-time units required by the
3386language constructs used in a particular unit.
3387
3388@item
3389If a file being compiled instantiates a library level generic unit, the
3390object file depends on both the spec and body files for this generic
3391unit.
3392
3393@item
3394If a file being compiled instantiates a generic unit defined within a
3395package, the object file depends on the body file for the package as
3396well as the spec file.
3397@end itemize
3398
3399@geindex Inline
3400
3401@geindex -gnatn switch
3402
3403
3404@itemize *
3405
3406@item
3407If a file being compiled contains a call to a subprogram for which
3408pragma @cite{Inline} applies and inlining is activated with the
3409@emph{-gnatn} switch, the object file depends on the file containing the
3410body of this subprogram as well as on the file containing the spec. Note
3411that for inlining to actually occur as a result of the use of this switch,
3412it is necessary to compile in optimizing mode.
3413
3414@geindex -gnatN switch
3415
3416The use of @emph{-gnatN} activates  inlining optimization
3417that is performed by the front end of the compiler. This inlining does
3418not require that the code generation be optimized. Like @emph{-gnatn},
3419the use of this switch generates additional dependencies.
3420
3421When using a gcc-based back end (in practice this means using any version
3422of GNAT other than for the JVM, .NET or GNAAMP platforms), then the use of
3423@emph{-gnatN} is deprecated, and the use of @emph{-gnatn} is preferred.
3424Historically front end inlining was more extensive than the gcc back end
3425inlining, but that is no longer the case.
3426
3427@item
3428If an object file @code{O} depends on the proper body of a subunit through
3429inlining or instantiation, it depends on the parent unit of the subunit.
3430This means that any modification of the parent unit or one of its subunits
3431affects the compilation of @code{O}.
3432
3433@item
3434The object file for a parent unit depends on all its subunit body files.
3435
3436@item
3437The previous two rules meant that for purposes of computing dependencies and
3438recompilation, a body and all its subunits are treated as an indivisible whole.
3439
3440These rules are applied transitively: if unit @cite{A} @emph{with}s
3441unit @cite{B}, whose elaboration calls an inlined procedure in package
3442@cite{C}, the object file for unit @cite{A} will depend on the body of
3443@cite{C}, in file @code{c.adb}.
3444
3445The set of dependent files described by these rules includes all the
3446files on which the unit is semantically dependent, as dictated by the
3447Ada language standard. However, it is a superset of what the
3448standard describes, because it includes generic, inline, and subunit
3449dependencies.
3450
3451An object file must be recreated by recompiling the corresponding source
3452file if any of the source files on which it depends are modified. For
3453example, if the @cite{make} utility is used to control compilation,
3454the rule for an Ada object file must mention all the source files on
3455which the object file depends, according to the above definition.
3456The determination of the necessary
3457recompilations is done automatically when one uses @emph{gnatmake}.
3458@end itemize
3459
3460@node The Ada Library Information Files,Binding an Ada Program,Source Dependencies,The GNAT Compilation Model
3461@anchor{gnat_ugn/the_gnat_compilation_model id33}@anchor{80}@anchor{gnat_ugn/the_gnat_compilation_model the-ada-library-information-files}@anchor{44}
3462@section The Ada Library Information Files
3463
3464
3465@geindex Ada Library Information files
3466
3467@geindex ALI files
3468
3469Each compilation actually generates two output files. The first of these
3470is the normal object file that has a @code{.o} extension. The second is a
3471text file containing full dependency information. It has the same
3472name as the source file, but an @code{.ali} extension.
3473This file is known as the Ada Library Information (@code{ALI}) file.
3474The following information is contained in the @code{ALI} file.
3475
3476
3477@itemize *
3478
3479@item
3480Version information (indicates which version of GNAT was used to compile
3481the unit(s) in question)
3482
3483@item
3484Main program information (including priority and time slice settings,
3485as well as the wide character encoding used during compilation).
3486
3487@item
3488List of arguments used in the @emph{gcc} command for the compilation
3489
3490@item
3491Attributes of the unit, including configuration pragmas used, an indication
3492of whether the compilation was successful, exception model used etc.
3493
3494@item
3495A list of relevant restrictions applying to the unit (used for consistency)
3496checking.
3497
3498@item
3499Categorization information (e.g., use of pragma @cite{Pure}).
3500
3501@item
3502Information on all @emph{with}ed units, including presence of
3503Elaborate` or @cite{Elaborate_All} pragmas.
3504
3505@item
3506Information from any @cite{Linker_Options} pragmas used in the unit
3507
3508@item
3509Information on the use of @cite{Body_Version} or @cite{Version}
3510attributes in the unit.
3511
3512@item
3513Dependency information. This is a list of files, together with
3514time stamp and checksum information. These are files on which
3515the unit depends in the sense that recompilation is required
3516if any of these units are modified.
3517
3518@item
3519Cross-reference data. Contains information on all entities referenced
3520in the unit. Used by tools like @cite{gnatxref} and @cite{gnatfind} to
3521provide cross-reference information.
3522@end itemize
3523
3524For a full detailed description of the format of the @code{ALI} file,
3525see the source of the body of unit @cite{Lib.Writ}, contained in file
3526@code{lib-writ.adb} in the GNAT compiler sources.
3527
3528@node Binding an Ada Program,GNAT and Libraries,The Ada Library Information Files,The GNAT Compilation Model
3529@anchor{gnat_ugn/the_gnat_compilation_model id34}@anchor{81}@anchor{gnat_ugn/the_gnat_compilation_model binding-an-ada-program}@anchor{45}
3530@section Binding an Ada Program
3531
3532
3533When using languages such as C and C++, once the source files have been
3534compiled the only remaining step in building an executable program
3535is linking the object modules together. This means that it is possible to
3536link an inconsistent version of a program, in which two units have
3537included different versions of the same header.
3538
3539The rules of Ada do not permit such an inconsistent program to be built.
3540For example, if two clients have different versions of the same package,
3541it is illegal to build a program containing these two clients.
3542These rules are enforced by the GNAT binder, which also determines an
3543elaboration order consistent with the Ada rules.
3544
3545The GNAT binder is run after all the object files for a program have
3546been created. It is given the name of the main program unit, and from
3547this it determines the set of units required by the program, by reading the
3548corresponding ALI files. It generates error messages if the program is
3549inconsistent or if no valid order of elaboration exists.
3550
3551If no errors are detected, the binder produces a main program, in Ada by
3552default, that contains calls to the elaboration procedures of those
3553compilation unit that require them, followed by
3554a call to the main program. This Ada program is compiled to generate the
3555object file for the main program. The name of
3556the Ada file is @code{b~xxx}.adb` (with the corresponding spec
3557@code{b~xxx}.ads`) where @cite{xxx} is the name of the
3558main program unit.
3559
3560Finally, the linker is used to build the resulting executable program,
3561using the object from the main program from the bind step as well as the
3562object files for the Ada units of the program.
3563
3564@node GNAT and Libraries,Conditional Compilation,Binding an Ada Program,The GNAT Compilation Model
3565@anchor{gnat_ugn/the_gnat_compilation_model gnat-and-libraries}@anchor{17}@anchor{gnat_ugn/the_gnat_compilation_model id35}@anchor{82}
3566@section GNAT and Libraries
3567
3568
3569@geindex Library building and using
3570
3571This chapter describes how to build and use libraries with GNAT, and also shows
3572how to recompile the GNAT run-time library. You should be familiar with the
3573Project Manager facility (@ref{b,,GNAT Project Manager}) before reading this
3574chapter.
3575
3576@menu
3577* Introduction to Libraries in GNAT::
3578* General Ada Libraries::
3579* Stand-alone Ada Libraries::
3580* Rebuilding the GNAT Run-Time Library::
3581
3582@end menu
3583
3584@node Introduction to Libraries in GNAT,General Ada Libraries,,GNAT and Libraries
3585@anchor{gnat_ugn/the_gnat_compilation_model introduction-to-libraries-in-gnat}@anchor{83}@anchor{gnat_ugn/the_gnat_compilation_model id36}@anchor{84}
3586@subsection Introduction to Libraries in GNAT
3587
3588
3589A library is, conceptually, a collection of objects which does not have its
3590own main thread of execution, but rather provides certain services to the
3591applications that use it. A library can be either statically linked with the
3592application, in which case its code is directly included in the application,
3593or, on platforms that support it, be dynamically linked, in which case
3594its code is shared by all applications making use of this library.
3595
3596GNAT supports both types of libraries.
3597In the static case, the compiled code can be provided in different ways. The
3598simplest approach is to provide directly the set of objects resulting from
3599compilation of the library source files. Alternatively, you can group the
3600objects into an archive using whatever commands are provided by the operating
3601system. For the latter case, the objects are grouped into a shared library.
3602
3603In the GNAT environment, a library has three types of components:
3604
3605
3606@itemize *
3607
3608@item
3609Source files,
3610
3611@item
3612@code{ALI} files (see @ref{44,,The Ada Library Information Files}), and
3613
3614@item
3615Object files, an archive or a shared library.
3616@end itemize
3617
3618A GNAT library may expose all its source files, which is useful for
3619documentation purposes. Alternatively, it may expose only the units needed by
3620an external user to make use of the library. That is to say, the specs
3621reflecting the library services along with all the units needed to compile
3622those specs, which can include generic bodies or any body implementing an
3623inlined routine. In the case of @emph{stand-alone libraries} those exposed
3624units are called @emph{interface units} (@ref{85,,Stand-alone Ada Libraries}).
3625
3626All compilation units comprising an application, including those in a library,
3627need to be elaborated in an order partially defined by Ada's semantics. GNAT
3628computes the elaboration order from the @code{ALI} files and this is why they
3629constitute a mandatory part of GNAT libraries.
3630@emph{Stand-alone libraries} are the exception to this rule because a specific
3631library elaboration routine is produced independently of the application(s)
3632using the library.
3633
3634@node General Ada Libraries,Stand-alone Ada Libraries,Introduction to Libraries in GNAT,GNAT and Libraries
3635@anchor{gnat_ugn/the_gnat_compilation_model general-ada-libraries}@anchor{86}@anchor{gnat_ugn/the_gnat_compilation_model id37}@anchor{87}
3636@subsection General Ada Libraries
3637
3638
3639@menu
3640* Building a library::
3641* Installing a library::
3642* Using a library::
3643
3644@end menu
3645
3646@node Building a library,Installing a library,,General Ada Libraries
3647@anchor{gnat_ugn/the_gnat_compilation_model building-a-library}@anchor{88}@anchor{gnat_ugn/the_gnat_compilation_model id38}@anchor{89}
3648@subsubsection Building a library
3649
3650
3651The easiest way to build a library is to use the Project Manager,
3652which supports a special type of project called a @emph{Library Project}
3653(see @ref{8a,,Library Projects}).
3654
3655A project is considered a library project, when two project-level attributes
3656are defined in it: @cite{Library_Name} and @cite{Library_Dir}. In order to
3657control different aspects of library configuration, additional optional
3658project-level attributes can be specified:
3659
3660
3661@itemize *
3662
3663@item
3664
3665@table @asis
3666
3667@item @emph{Library_Kind}
3668
3669This attribute controls whether the library is to be static or dynamic
3670@end table
3671
3672@item
3673
3674@table @asis
3675
3676@item @emph{Library_Version}
3677
3678This attribute specifies the library version; this value is used
3679during dynamic linking of shared libraries to determine if the currently
3680installed versions of the binaries are compatible.
3681@end table
3682
3683@item
3684@emph{Library_Options}
3685
3686@item
3687
3688@table @asis
3689
3690@item @emph{Library_GCC}
3691
3692These attributes specify additional low-level options to be used during
3693library generation, and redefine the actual application used to generate
3694library.
3695@end table
3696@end itemize
3697
3698The GNAT Project Manager takes full care of the library maintenance task,
3699including recompilation of the source files for which objects do not exist
3700or are not up to date, assembly of the library archive, and installation of
3701the library (i.e., copying associated source, object and @code{ALI} files
3702to the specified location).
3703
3704Here is a simple library project file:
3705
3706@example
3707project My_Lib is
3708  for Source_Dirs use ("src1", "src2");
3709  for Object_Dir use "obj";
3710  for Library_Name use "mylib";
3711  for Library_Dir use "lib";
3712  for Library_Kind use "dynamic";
3713end My_lib;
3714@end example
3715
3716and the compilation command to build and install the library:
3717
3718@example
3719$ gnatmake -Pmy_lib
3720@end example
3721
3722It is not entirely trivial to perform manually all the steps required to
3723produce a library. We recommend that you use the GNAT Project Manager
3724for this task. In special cases where this is not desired, the necessary
3725steps are discussed below.
3726
3727There are various possibilities for compiling the units that make up the
3728library: for example with a Makefile (@ref{21,,Using the GNU make Utility}) or
3729with a conventional script. For simple libraries, it is also possible to create
3730a dummy main program which depends upon all the packages that comprise the
3731interface of the library. This dummy main program can then be given to
3732@emph{gnatmake}, which will ensure that all necessary objects are built.
3733
3734After this task is accomplished, you should follow the standard procedure
3735of the underlying operating system to produce the static or shared library.
3736
3737Here is an example of such a dummy program:
3738
3739@example
3740with My_Lib.Service1;
3741with My_Lib.Service2;
3742with My_Lib.Service3;
3743procedure My_Lib_Dummy is
3744begin
3745   null;
3746end;
3747@end example
3748
3749Here are the generic commands that will build an archive or a shared library.
3750
3751@example
3752# compiling the library
3753$ gnatmake -c my_lib_dummy.adb
3754
3755# we don't need the dummy object itself
3756$ rm my_lib_dummy.o my_lib_dummy.ali
3757
3758# create an archive with the remaining objects
3759$ ar rc libmy_lib.a *.o
3760# some systems may require "ranlib" to be run as well
3761
3762# or create a shared library
3763$ gcc -shared -o libmy_lib.so *.o
3764# some systems may require the code to have been compiled with -fPIC
3765
3766# remove the object files that are now in the library
3767$ rm *.o
3768
3769# Make the ALI files read-only so that gnatmake will not try to
3770# regenerate the objects that are in the library
3771$ chmod -w *.ali
3772@end example
3773
3774Please note that the library must have a name of the form @code{lib@emph{xxx}.a}
3775or @code{lib@emph{xxx}.so} (or @code{lib@emph{xxx}.dll} on Windows) in order to
3776be accessed by the directive @code{-l@emph{xxx}} at link time.
3777
3778@node Installing a library,Using a library,Building a library,General Ada Libraries
3779@anchor{gnat_ugn/the_gnat_compilation_model installing-a-library}@anchor{8b}@anchor{gnat_ugn/the_gnat_compilation_model id39}@anchor{8c}
3780@subsubsection Installing a library
3781
3782
3783@geindex ADA_PROJECT_PATH
3784
3785@geindex GPR_PROJECT_PATH
3786
3787If you use project files, library installation is part of the library build
3788process (@ref{8d,,Installing a library with project files}).
3789
3790When project files are not an option, it is also possible, but not recommended,
3791to install the library so that the sources needed to use the library are on the
3792Ada source path and the ALI files & libraries be on the Ada Object path (see
3793@ref{8e,,Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
3794administrator can place general-purpose libraries in the default compiler
3795paths, by specifying the libraries' location in the configuration files
3796@code{ada_source_path} and @code{ada_object_path}. These configuration files
3797must be located in the GNAT installation tree at the same place as the gcc spec
3798file. The location of the gcc spec file can be determined as follows:
3799
3800@example
3801$ gcc -v
3802@end example
3803
3804The configuration files mentioned above have a simple format: each line
3805must contain one unique directory name.
3806Those names are added to the corresponding path
3807in their order of appearance in the file. The names can be either absolute
3808or relative; in the latter case, they are relative to where theses files
3809are located.
3810
3811The files @code{ada_source_path} and @code{ada_object_path} might not be
3812present in a
3813GNAT installation, in which case, GNAT will look for its run-time library in
3814the directories @code{adainclude} (for the sources) and @code{adalib} (for the
3815objects and @code{ALI} files). When the files exist, the compiler does not
3816look in @code{adainclude} and @code{adalib}, and thus the
3817@code{ada_source_path} file
3818must contain the location for the GNAT run-time sources (which can simply
3819be @code{adainclude}). In the same way, the @code{ada_object_path} file must
3820contain the location for the GNAT run-time objects (which can simply
3821be @code{adalib}).
3822
3823You can also specify a new default path to the run-time library at compilation
3824time with the switch @emph{--RTS=rts-path}. You can thus choose / change
3825the run-time library you want your program to be compiled with. This switch is
3826recognized by @emph{gcc}, @emph{gnatmake}, @emph{gnatbind},
3827@emph{gnatls}, @emph{gnatfind} and @emph{gnatxref}.
3828
3829It is possible to install a library before or after the standard GNAT
3830library, by reordering the lines in the configuration files. In general, a
3831library must be installed before the GNAT library if it redefines
3832any part of it.
3833
3834@node Using a library,,Installing a library,General Ada Libraries
3835@anchor{gnat_ugn/the_gnat_compilation_model using-a-library}@anchor{8f}@anchor{gnat_ugn/the_gnat_compilation_model id40}@anchor{90}
3836@subsubsection Using a library
3837
3838
3839Once again, the project facility greatly simplifies the use of
3840libraries. In this context, using a library is just a matter of adding a
3841@emph{with} clause in the user project. For instance, to make use of the
3842library @cite{My_Lib} shown in examples in earlier sections, you can
3843write:
3844
3845@example
3846with "my_lib";
3847project My_Proj is
3848  ...
3849end My_Proj;
3850@end example
3851
3852Even if you have a third-party, non-Ada library, you can still use GNAT's
3853Project Manager facility to provide a wrapper for it. For example, the
3854following project, when @emph{with}ed by your main project, will link with the
3855third-party library @code{liba.a}:
3856
3857@example
3858project Liba is
3859   for Externally_Built use "true";
3860   for Source_Files use ();
3861   for Library_Dir use "lib";
3862   for Library_Name use "a";
3863   for Library_Kind use "static";
3864end Liba;
3865@end example
3866
3867This is an alternative to the use of @cite{pragma Linker_Options}. It is
3868especially interesting in the context of systems with several interdependent
3869static libraries where finding a proper linker order is not easy and best be
3870left to the tools having visibility over project dependence information.
3871
3872In order to use an Ada library manually, you need to make sure that this
3873library is on both your source and object path
3874(see @ref{8e,,Search Paths and the Run-Time Library (RTL)}
3875and @ref{91,,Search Paths for gnatbind}). Furthermore, when the objects are grouped
3876in an archive or a shared library, you need to specify the desired
3877library at link time.
3878
3879For example, you can use the library @code{mylib} installed in
3880@code{/dir/my_lib_src} and @code{/dir/my_lib_obj} with the following commands:
3881
3882@example
3883$ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \\
3884  -largs -lmy_lib
3885@end example
3886
3887This can be expressed more simply:
3888
3889@example
3890$ gnatmake my_appl
3891@end example
3892
3893when the following conditions are met:
3894
3895
3896@itemize *
3897
3898@item
3899@code{/dir/my_lib_src} has been added by the user to the environment
3900variable
3901@geindex ADA_INCLUDE_PATH
3902@geindex environment variable; ADA_INCLUDE_PATH
3903@code{ADA_INCLUDE_PATH}, or by the administrator to the file
3904@code{ada_source_path}
3905
3906@item
3907@code{/dir/my_lib_obj} has been added by the user to the environment
3908variable
3909@geindex ADA_OBJECTS_PATH
3910@geindex environment variable; ADA_OBJECTS_PATH
3911@code{ADA_OBJECTS_PATH}, or by the administrator to the file
3912@code{ada_object_path}
3913
3914@item
3915a pragma @cite{Linker_Options} has been added to one of the sources.
3916For example:
3917
3918@example
3919pragma Linker_Options ("-lmy_lib");
3920@end example
3921@end itemize
3922
3923Note that you may also load a library dynamically at
3924run time given its filename, as illustrated in the GNAT @code{plugins} example
3925in the directory @code{share/examples/gnat/plugins} within the GNAT
3926install area.
3927
3928@node Stand-alone Ada Libraries,Rebuilding the GNAT Run-Time Library,General Ada Libraries,GNAT and Libraries
3929@anchor{gnat_ugn/the_gnat_compilation_model stand-alone-ada-libraries}@anchor{85}@anchor{gnat_ugn/the_gnat_compilation_model id41}@anchor{92}
3930@subsection Stand-alone Ada Libraries
3931
3932
3933@geindex Stand-alone libraries
3934
3935@menu
3936* Introduction to Stand-alone Libraries::
3937* Building a Stand-alone Library::
3938* Creating a Stand-alone Library to be used in a non-Ada context::
3939* Restrictions in Stand-alone Libraries::
3940
3941@end menu
3942
3943@node Introduction to Stand-alone Libraries,Building a Stand-alone Library,,Stand-alone Ada Libraries
3944@anchor{gnat_ugn/the_gnat_compilation_model introduction-to-stand-alone-libraries}@anchor{93}@anchor{gnat_ugn/the_gnat_compilation_model id42}@anchor{94}
3945@subsubsection Introduction to Stand-alone Libraries
3946
3947
3948A Stand-alone Library (abbreviated 'SAL') is a library that contains the
3949necessary code to
3950elaborate the Ada units that are included in the library. In contrast with
3951an ordinary library, which consists of all sources, objects and @code{ALI}
3952files of the
3953library, a SAL may specify a restricted subset of compilation units
3954to serve as a library interface. In this case, the fully
3955self-sufficient set of files will normally consist of an objects
3956archive, the sources of interface units' specs, and the @code{ALI}
3957files of interface units.
3958If an interface spec contains a generic unit or an inlined subprogram,
3959the body's
3960source must also be provided; if the units that must be provided in the source
3961form depend on other units, the source and @code{ALI} files of those must
3962also be provided.
3963
3964The main purpose of a SAL is to minimize the recompilation overhead of client
3965applications when a new version of the library is installed. Specifically,
3966if the interface sources have not changed, client applications do not need to
3967be recompiled. If, furthermore, a SAL is provided in the shared form and its
3968version, controlled by @cite{Library_Version} attribute, is not changed,
3969then the clients do not need to be relinked.
3970
3971SALs also allow the library providers to minimize the amount of library source
3972text exposed to the clients.  Such 'information hiding' might be useful or
3973necessary for various reasons.
3974
3975Stand-alone libraries are also well suited to be used in an executable whose
3976main routine is not written in Ada.
3977
3978@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
3979@anchor{gnat_ugn/the_gnat_compilation_model id43}@anchor{95}@anchor{gnat_ugn/the_gnat_compilation_model building-a-stand-alone-library}@anchor{96}
3980@subsubsection Building a Stand-alone Library
3981
3982
3983GNAT's Project facility provides a simple way of building and installing
3984stand-alone libraries; see @ref{97,,Stand-alone Library Projects}.
3985To be a Stand-alone Library Project, in addition to the two attributes
3986that make a project a Library Project (@cite{Library_Name} and
3987@cite{Library_Dir}; see @ref{8a,,Library Projects}), the attribute
3988@cite{Library_Interface} must be defined.  For example:
3989
3990@example
3991for Library_Dir use "lib_dir";
3992for Library_Name use "dummy";
3993for Library_Interface use ("int1", "int1.child");
3994@end example
3995
3996Attribute @cite{Library_Interface} has a non-empty string list value,
3997each string in the list designating a unit contained in an immediate source
3998of the project file.
3999
4000When a Stand-alone Library is built, first the binder is invoked to build
4001a package whose name depends on the library name
4002(@code{b~dummy.ads/b} in the example above).
4003This binder-generated package includes initialization and
4004finalization procedures whose
4005names depend on the library name (@cite{dummyinit} and @cite{dummyfinal}
4006in the example
4007above). The object corresponding to this package is included in the library.
4008
4009You must ensure timely (e.g., prior to any use of interfaces in the SAL)
4010calling of these procedures if a static SAL is built, or if a shared SAL
4011is built
4012with the project-level attribute @cite{Library_Auto_Init} set to
4013@cite{"false"}.
4014
4015For a Stand-Alone Library, only the @code{ALI} files of the Interface Units
4016(those that are listed in attribute @cite{Library_Interface}) are copied to
4017the Library Directory. As a consequence, only the Interface Units may be
4018imported from Ada units outside of the library. If other units are imported,
4019the binding phase will fail.
4020
4021It is also possible to build an encapsulated library where not only
4022the code to elaborate and finalize the library is embedded but also
4023ensuring that the library is linked only against static
4024libraries. So an encapsulated library only depends on system
4025libraries, all other code, including the GNAT runtime, is embedded. To
4026build an encapsulated library the attribute
4027@cite{Library_Standalone} must be set to @cite{encapsulated}:
4028
4029@example
4030for Library_Dir use "lib_dir";
4031for Library_Name use "dummy";
4032for Library_Kind use "dynamic";
4033for Library_Interface use ("int1", "int1.child");
4034for Library_Standalone use "encapsulated";
4035@end example
4036
4037The default value for this attribute is @cite{standard} in which case
4038a stand-alone library is built.
4039
4040The attribute @cite{Library_Src_Dir} may be specified for a
4041Stand-Alone Library. @cite{Library_Src_Dir} is a simple attribute that has a
4042single string value. Its value must be the path (absolute or relative to the
4043project directory) of an existing directory. This directory cannot be the
4044object directory or one of the source directories, but it can be the same as
4045the library directory. The sources of the Interface
4046Units of the library that are needed by an Ada client of the library will be
4047copied to the designated directory, called the Interface Copy directory.
4048These sources include the specs of the Interface Units, but they may also
4049include bodies and subunits, when pragmas @cite{Inline} or @cite{Inline_Always}
4050are used, or when there is a generic unit in the spec. Before the sources
4051are copied to the Interface Copy directory, an attempt is made to delete all
4052files in the Interface Copy directory.
4053
4054Building stand-alone libraries by hand is somewhat tedious, but for those
4055occasions when it is necessary here are the steps that you need to perform:
4056
4057
4058@itemize *
4059
4060@item
4061Compile all library sources.
4062
4063@item
4064Invoke the binder with the switch @emph{-n} (No Ada main program),
4065with all the @code{ALI} files of the interfaces, and
4066with the switch @emph{-L} to give specific names to the @cite{init}
4067and @cite{final} procedures.  For example:
4068
4069@example
4070$ gnatbind -n int1.ali int2.ali -Lsal1
4071@end example
4072
4073@item
4074Compile the binder generated file:
4075
4076@example
4077$ gcc -c b~int2.adb
4078@end example
4079
4080@item
4081Link the dynamic library with all the necessary object files,
4082indicating to the linker the names of the @cite{init} (and possibly
4083@cite{final}) procedures for automatic initialization (and finalization).
4084The built library should be placed in a directory different from
4085the object directory.
4086
4087@item
4088Copy the @cite{ALI} files of the interface to the library directory,
4089add in this copy an indication that it is an interface to a SAL
4090(i.e., add a word @emph{SL} on the line in the @code{ALI} file that starts
4091with letter 'P') and make the modified copy of the @code{ALI} file
4092read-only.
4093@end itemize
4094
4095Using SALs is not different from using other libraries
4096(see @ref{8f,,Using a library}).
4097
4098@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
4099@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}
4100@subsubsection Creating a Stand-alone Library to be used in a non-Ada context
4101
4102
4103It is easy to adapt the SAL build procedure discussed above for use of a SAL in
4104a non-Ada context.
4105
4106The only extra step required is to ensure that library interface subprograms
4107are compatible with the main program, by means of @cite{pragma Export}
4108or @cite{pragma Convention}.
4109
4110Here is an example of simple library interface for use with C main program:
4111
4112@example
4113package My_Package is
4114
4115   procedure Do_Something;
4116   pragma Export (C, Do_Something, "do_something");
4117
4118   procedure Do_Something_Else;
4119   pragma Export (C, Do_Something_Else, "do_something_else");
4120
4121end My_Package;
4122@end example
4123
4124On the foreign language side, you must provide a 'foreign' view of the
4125library interface; remember that it should contain elaboration routines in
4126addition to interface subprograms.
4127
4128The example below shows the content of @cite{mylib_interface.h} (note
4129that there is no rule for the naming of this file, any name can be used)
4130
4131@example
4132/* the library elaboration procedure */
4133extern void mylibinit (void);
4134
4135/* the library finalization procedure */
4136extern void mylibfinal (void);
4137
4138/* the interface exported by the library */
4139extern void do_something (void);
4140extern void do_something_else (void);
4141@end example
4142
4143Libraries built as explained above can be used from any program, provided
4144that the elaboration procedures (named @cite{mylibinit} in the previous
4145example) are called before the library services are used. Any number of
4146libraries can be used simultaneously, as long as the elaboration
4147procedure of each library is called.
4148
4149Below is an example of a C program that uses the @cite{mylib} library.
4150
4151@example
4152#include "mylib_interface.h"
4153
4154int
4155main (void)
4156@{
4157   /* First, elaborate the library before using it */
4158   mylibinit ();
4159
4160   /* Main program, using the library exported entities */
4161   do_something ();
4162   do_something_else ();
4163
4164   /* Library finalization at the end of the program */
4165   mylibfinal ();
4166   return 0;
4167@}
4168@end example
4169
4170Note that invoking any library finalization procedure generated by
4171@cite{gnatbind} shuts down the Ada run-time environment.
4172Consequently, the
4173finalization of all Ada libraries must be performed at the end of the program.
4174No call to these libraries or to the Ada run-time library should be made
4175after the finalization phase.
4176
4177Note also that special care must be taken with multi-tasks
4178applications. The initialization and finalization routines are not
4179protected against concurrent access. If such requirement is needed it
4180must be ensured at the application level using a specific operating
4181system services like a mutex or a critical-section.
4182
4183@node Restrictions in Stand-alone Libraries,,Creating a Stand-alone Library to be used in a non-Ada context,Stand-alone Ada Libraries
4184@anchor{gnat_ugn/the_gnat_compilation_model id45}@anchor{9a}@anchor{gnat_ugn/the_gnat_compilation_model restrictions-in-stand-alone-libraries}@anchor{9b}
4185@subsubsection Restrictions in Stand-alone Libraries
4186
4187
4188The pragmas listed below should be used with caution inside libraries,
4189as they can create incompatibilities with other Ada libraries:
4190
4191
4192@itemize *
4193
4194@item
4195pragma @cite{Locking_Policy}
4196
4197@item
4198pragma @cite{Partition_Elaboration_Policy}
4199
4200@item
4201pragma @cite{Queuing_Policy}
4202
4203@item
4204pragma @cite{Task_Dispatching_Policy}
4205
4206@item
4207pragma @cite{Unreserve_All_Interrupts}
4208@end itemize
4209
4210When using a library that contains such pragmas, the user must make sure
4211that all libraries use the same pragmas with the same values. Otherwise,
4212@cite{Program_Error} will
4213be raised during the elaboration of the conflicting
4214libraries. The usage of these pragmas and its consequences for the user
4215should therefore be well documented.
4216
4217Similarly, the traceback in the exception occurrence mechanism should be
4218enabled or disabled in a consistent manner across all libraries.
4219Otherwise, Program_Error will be raised during the elaboration of the
4220conflicting libraries.
4221
4222If the @cite{Version} or @cite{Body_Version}
4223attributes are used inside a library, then you need to
4224perform a @cite{gnatbind} step that specifies all @code{ALI} files in all
4225libraries, so that version identifiers can be properly computed.
4226In practice these attributes are rarely used, so this is unlikely
4227to be a consideration.
4228
4229@node Rebuilding the GNAT Run-Time Library,,Stand-alone Ada Libraries,GNAT and Libraries
4230@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}
4231@subsection Rebuilding the GNAT Run-Time Library
4232
4233
4234@geindex GNAT Run-Time Library
4235@geindex rebuilding
4236
4237@geindex Building the GNAT Run-Time Library
4238
4239@geindex Rebuilding the GNAT Run-Time Library
4240
4241@geindex Run-Time Library
4242@geindex rebuilding
4243
4244It may be useful to recompile the GNAT library in various contexts, the
4245most important one being the use of partition-wide configuration pragmas
4246such as @cite{Normalize_Scalars}. A special Makefile called
4247@cite{Makefile.adalib} is provided to that effect and can be found in
4248the directory containing the GNAT library. The location of this
4249directory depends on the way the GNAT environment has been installed and can
4250be determined by means of the command:
4251
4252@example
4253$ gnatls -v
4254@end example
4255
4256The last entry in the object search path usually contains the
4257gnat library. This Makefile contains its own documentation and in
4258particular the set of instructions needed to rebuild a new library and
4259to use it.
4260
4261@geindex Conditional compilation
4262
4263@node Conditional Compilation,Mixed Language Programming,GNAT and Libraries,The GNAT Compilation Model
4264@anchor{gnat_ugn/the_gnat_compilation_model id47}@anchor{9e}@anchor{gnat_ugn/the_gnat_compilation_model conditional-compilation}@anchor{18}
4265@section Conditional Compilation
4266
4267
4268This section presents some guidelines for modeling conditional compilation in Ada and describes the
4269gnatprep preprocessor utility.
4270
4271@geindex Conditional compilation
4272
4273@menu
4274* Modeling Conditional Compilation in Ada::
4275* Preprocessing with gnatprep::
4276* Integrated Preprocessing::
4277
4278@end menu
4279
4280@node Modeling Conditional Compilation in Ada,Preprocessing with gnatprep,,Conditional Compilation
4281@anchor{gnat_ugn/the_gnat_compilation_model modeling-conditional-compilation-in-ada}@anchor{9f}@anchor{gnat_ugn/the_gnat_compilation_model id48}@anchor{a0}
4282@subsection Modeling Conditional Compilation in Ada
4283
4284
4285It is often necessary to arrange for a single source program
4286to serve multiple purposes, where it is compiled in different
4287ways to achieve these different goals. Some examples of the
4288need for this feature are
4289
4290
4291@itemize *
4292
4293@item
4294Adapting a program to a different hardware environment
4295
4296@item
4297Adapting a program to a different target architecture
4298
4299@item
4300Turning debugging features on and off
4301
4302@item
4303Arranging for a program to compile with different compilers
4304@end itemize
4305
4306In C, or C++, the typical approach would be to use the preprocessor
4307that is defined as part of the language. The Ada language does not
4308contain such a feature. This is not an oversight, but rather a very
4309deliberate design decision, based on the experience that overuse of
4310the preprocessing features in C and C++ can result in programs that
4311are extremely difficult to maintain. For example, if we have ten
4312switches that can be on or off, this means that there are a thousand
4313separate programs, any one of which might not even be syntactically
4314correct, and even if syntactically correct, the resulting program
4315might not work correctly. Testing all combinations can quickly become
4316impossible.
4317
4318Nevertheless, the need to tailor programs certainly exists, and in
4319this section we will discuss how this can
4320be achieved using Ada in general, and GNAT in particular.
4321
4322@menu
4323* Use of Boolean Constants::
4324* Debugging - A Special Case::
4325* Conditionalizing Declarations::
4326* Use of Alternative Implementations::
4327* Preprocessing::
4328
4329@end menu
4330
4331@node Use of Boolean Constants,Debugging - A Special Case,,Modeling Conditional Compilation in Ada
4332@anchor{gnat_ugn/the_gnat_compilation_model id49}@anchor{a1}@anchor{gnat_ugn/the_gnat_compilation_model use-of-boolean-constants}@anchor{a2}
4333@subsubsection Use of Boolean Constants
4334
4335
4336In the case where the difference is simply which code
4337sequence is executed, the cleanest solution is to use Boolean
4338constants to control which code is executed.
4339
4340@example
4341FP_Initialize_Required : constant Boolean := True;
4342...
4343if FP_Initialize_Required then
4344...
4345end if;
4346@end example
4347
4348Not only will the code inside the @cite{if} statement not be executed if
4349the constant Boolean is @cite{False}, but it will also be completely
4350deleted from the program.
4351However, the code is only deleted after the @cite{if} statement
4352has been checked for syntactic and semantic correctness.
4353(In contrast, with preprocessors the code is deleted before the
4354compiler ever gets to see it, so it is not checked until the switch
4355is turned on.)
4356
4357@geindex Preprocessors (contrasted with conditional compilation)
4358
4359Typically the Boolean constants will be in a separate package,
4360something like:
4361
4362@example
4363package Config is
4364   FP_Initialize_Required : constant Boolean := True;
4365   Reset_Available        : constant Boolean := False;
4366   ...
4367end Config;
4368@end example
4369
4370The @cite{Config} package exists in multiple forms for the various targets,
4371with an appropriate script selecting the version of @cite{Config} needed.
4372Then any other unit requiring conditional compilation can do a @emph{with}
4373of @cite{Config} to make the constants visible.
4374
4375@node Debugging - A Special Case,Conditionalizing Declarations,Use of Boolean Constants,Modeling Conditional Compilation in Ada
4376@anchor{gnat_ugn/the_gnat_compilation_model debugging-a-special-case}@anchor{a3}@anchor{gnat_ugn/the_gnat_compilation_model id50}@anchor{a4}
4377@subsubsection Debugging - A Special Case
4378
4379
4380A common use of conditional code is to execute statements (for example
4381dynamic checks, or output of intermediate results) under control of a
4382debug switch, so that the debugging behavior can be turned on and off.
4383This can be done using a Boolean constant to control whether the code
4384is active:
4385
4386@example
4387if Debugging then
4388   Put_Line ("got to the first stage!");
4389end if;
4390@end example
4391
4392or
4393
4394@example
4395if Debugging and then Temperature > 999.0 then
4396   raise Temperature_Crazy;
4397end if;
4398@end example
4399
4400@geindex pragma Assert
4401
4402Since this is a common case, there are special features to deal with
4403this in a convenient manner. For the case of tests, Ada 2005 has added
4404a pragma @cite{Assert} that can be used for such tests. This pragma is modeled
4405on the @cite{Assert} pragma that has always been available in GNAT, so this
4406feature may be used with GNAT even if you are not using Ada 2005 features.
4407The use of pragma @cite{Assert} is described in the
4408@cite{GNAT_Reference_Manual}, but as an
4409example, the last test could be written:
4410
4411@example
4412pragma Assert (Temperature <= 999.0, "Temperature Crazy");
4413@end example
4414
4415or simply
4416
4417@example
4418pragma Assert (Temperature <= 999.0);
4419@end example
4420
4421In both cases, if assertions are active and the temperature is excessive,
4422the exception @cite{Assert_Failure} will be raised, with the given string in
4423the first case or a string indicating the location of the pragma in the second
4424case used as the exception message.
4425
4426@geindex pragma Assertion_Policy
4427
4428You can turn assertions on and off by using the @cite{Assertion_Policy}
4429pragma.
4430
4431@geindex -gnata switch
4432
4433This is an Ada 2005 pragma which is implemented in all modes by
4434GNAT. Alternatively, you can use the @emph{-gnata} switch
4435to enable assertions from the command line, which applies to
4436all versions of Ada.
4437
4438@geindex pragma Debug
4439
4440For the example above with the @cite{Put_Line}, the GNAT-specific pragma
4441@cite{Debug} can be used:
4442
4443@example
4444pragma Debug (Put_Line ("got to the first stage!"));
4445@end example
4446
4447If debug pragmas are enabled, the argument, which must be of the form of
4448a procedure call, is executed (in this case, @cite{Put_Line} will be called).
4449Only one call can be present, but of course a special debugging procedure
4450containing any code you like can be included in the program and then
4451called in a pragma @cite{Debug} argument as needed.
4452
4453One advantage of pragma @cite{Debug} over the @cite{if Debugging then}
4454construct is that pragma @cite{Debug} can appear in declarative contexts,
4455such as at the very beginning of a procedure, before local declarations have
4456been elaborated.
4457
4458@geindex pragma Debug_Policy
4459
4460Debug pragmas are enabled using either the @emph{-gnata} switch that also
4461controls assertions, or with a separate Debug_Policy pragma.
4462
4463The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
4464in Ada 95 and Ada 83 programs as well), and is analogous to
4465pragma @cite{Assertion_Policy} to control assertions.
4466
4467@cite{Assertion_Policy} and @cite{Debug_Policy} are configuration pragmas,
4468and thus they can appear in @code{gnat.adc} if you are not using a
4469project file, or in the file designated to contain configuration pragmas
4470in a project file.
4471They then apply to all subsequent compilations. In practice the use of
4472the @emph{-gnata} switch is often the most convenient method of controlling
4473the status of these pragmas.
4474
4475Note that a pragma is not a statement, so in contexts where a statement
4476sequence is required, you can't just write a pragma on its own. You have
4477to add a @cite{null} statement.
4478
4479@example
4480if ... then
4481   ... -- some statements
4482else
4483   pragma Assert (Num_Cases < 10);
4484   null;
4485end if;
4486@end example
4487
4488@node Conditionalizing Declarations,Use of Alternative Implementations,Debugging - A Special Case,Modeling Conditional Compilation in Ada
4489@anchor{gnat_ugn/the_gnat_compilation_model conditionalizing-declarations}@anchor{a5}@anchor{gnat_ugn/the_gnat_compilation_model id51}@anchor{a6}
4490@subsubsection Conditionalizing Declarations
4491
4492
4493In some cases it may be necessary to conditionalize declarations to meet
4494different requirements. For example we might want a bit string whose length
4495is set to meet some hardware message requirement.
4496
4497This may be possible using declare blocks controlled
4498by conditional constants:
4499
4500@example
4501if Small_Machine then
4502   declare
4503      X : Bit_String (1 .. 10);
4504   begin
4505      ...
4506   end;
4507else
4508   declare
4509      X : Large_Bit_String (1 .. 1000);
4510   begin
4511      ...
4512   end;
4513end if;
4514@end example
4515
4516Note that in this approach, both declarations are analyzed by the
4517compiler so this can only be used where both declarations are legal,
4518even though one of them will not be used.
4519
4520Another approach is to define integer constants, e.g., @cite{Bits_Per_Word},
4521or Boolean constants, e.g., @cite{Little_Endian}, and then write declarations
4522that are parameterized by these constants. For example
4523
4524@example
4525for Rec use
4526  Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
4527end record;
4528@end example
4529
4530If @cite{Bits_Per_Word} is set to 32, this generates either
4531
4532@example
4533for Rec use
4534  Field1 at 0 range 0 .. 32;
4535end record;
4536@end example
4537
4538for the big endian case, or
4539
4540@example
4541for Rec use record
4542    Field1 at 0 range 10 .. 32;
4543end record;
4544@end example
4545
4546for the little endian case. Since a powerful subset of Ada expression
4547notation is usable for creating static constants, clever use of this
4548feature can often solve quite difficult problems in conditionalizing
4549compilation (note incidentally that in Ada 95, the little endian
4550constant was introduced as @cite{System.Default_Bit_Order}, so you do not
4551need to define this one yourself).
4552
4553@node Use of Alternative Implementations,Preprocessing,Conditionalizing Declarations,Modeling Conditional Compilation in Ada
4554@anchor{gnat_ugn/the_gnat_compilation_model use-of-alternative-implementations}@anchor{a7}@anchor{gnat_ugn/the_gnat_compilation_model id52}@anchor{a8}
4555@subsubsection Use of Alternative Implementations
4556
4557
4558In some cases, none of the approaches described above are adequate. This
4559can occur for example if the set of declarations required is radically
4560different for two different configurations.
4561
4562In this situation, the official Ada way of dealing with conditionalizing
4563such code is to write separate units for the different cases. As long as
4564this does not result in excessive duplication of code, this can be done
4565without creating maintenance problems. The approach is to share common
4566code as far as possible, and then isolate the code and declarations
4567that are different. Subunits are often a convenient method for breaking
4568out a piece of a unit that is to be conditionalized, with separate files
4569for different versions of the subunit for different targets, where the
4570build script selects the right one to give to the compiler.
4571
4572@geindex Subunits (and conditional compilation)
4573
4574As an example, consider a situation where a new feature in Ada 2005
4575allows something to be done in a really nice way. But your code must be able
4576to compile with an Ada 95 compiler. Conceptually you want to say:
4577
4578@example
4579if Ada_2005 then
4580   ... neat Ada 2005 code
4581else
4582   ... not quite as neat Ada 95 code
4583end if;
4584@end example
4585
4586where @cite{Ada_2005} is a Boolean constant.
4587
4588But this won't work when @cite{Ada_2005} is set to @cite{False},
4589since the @cite{then} clause will be illegal for an Ada 95 compiler.
4590(Recall that although such unreachable code would eventually be deleted
4591by the compiler, it still needs to be legal.  If it uses features
4592introduced in Ada 2005, it will be illegal in Ada 95.)
4593
4594So instead we write
4595
4596@example
4597procedure Insert is separate;
4598@end example
4599
4600Then we have two files for the subunit @cite{Insert}, with the two sets of
4601code.
4602If the package containing this is called @cite{File_Queries}, then we might
4603have two files
4604
4605
4606@itemize *
4607
4608@item
4609@code{file_queries-insert-2005.adb}
4610
4611@item
4612@code{file_queries-insert-95.adb}
4613@end itemize
4614
4615and the build script renames the appropriate file to @code{file_queries-insert.adb} and then carries out the compilation.
4616
4617This can also be done with project files' naming schemes. For example:
4618
4619@example
4620for body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
4621@end example
4622
4623Note also that with project files it is desirable to use a different extension
4624than @code{ads} / @code{adb} for alternative versions. Otherwise a naming
4625conflict may arise through another commonly used feature: to declare as part
4626of the project a set of directories containing all the sources obeying the
4627default naming scheme.
4628
4629The use of alternative units is certainly feasible in all situations,
4630and for example the Ada part of the GNAT run-time is conditionalized
4631based on the target architecture using this approach. As a specific example,
4632consider the implementation of the AST feature in VMS. There is one
4633spec: @code{s-asthan.ads} which is the same for all architectures, and three
4634bodies:
4635
4636
4637@itemize *
4638
4639@item
4640
4641@table @asis
4642
4643@item @code{s-asthan.adb}
4644
4645used for all non-VMS operating systems
4646@end table
4647
4648@item
4649
4650@table @asis
4651
4652@item @code{s-asthan-vms-alpha.adb}
4653
4654used for VMS on the Alpha
4655@end table
4656
4657@item
4658
4659@table @asis
4660
4661@item @code{s-asthan-vms-ia64.adb}
4662
4663used for VMS on the ia64
4664@end table
4665@end itemize
4666
4667The dummy version @code{s-asthan.adb} simply raises exceptions noting that
4668this operating system feature is not available, and the two remaining
4669versions interface with the corresponding versions of VMS to provide
4670VMS-compatible AST handling. The GNAT build script knows the architecture
4671and operating system, and automatically selects the right version,
4672renaming it if necessary to @code{s-asthan.adb} before the run-time build.
4673
4674Another style for arranging alternative implementations is through Ada's
4675access-to-subprogram facility.
4676In case some functionality is to be conditionally included,
4677you can declare an access-to-procedure variable @cite{Ref} that is initialized
4678to designate a 'do nothing' procedure, and then invoke @cite{Ref.all}
4679when appropriate.
4680In some library package, set @cite{Ref} to @cite{Proc'Access} for some
4681procedure @cite{Proc} that performs the relevant processing.
4682The initialization only occurs if the library package is included in the
4683program.
4684The same idea can also be implemented using tagged types and dispatching
4685calls.
4686
4687@node Preprocessing,,Use of Alternative Implementations,Modeling Conditional Compilation in Ada
4688@anchor{gnat_ugn/the_gnat_compilation_model preprocessing}@anchor{a9}@anchor{gnat_ugn/the_gnat_compilation_model id53}@anchor{aa}
4689@subsubsection Preprocessing
4690
4691
4692@geindex Preprocessing
4693
4694Although it is quite possible to conditionalize code without the use of
4695C-style preprocessing, as described earlier in this section, it is
4696nevertheless convenient in some cases to use the C approach. Moreover,
4697older Ada compilers have often provided some preprocessing capability,
4698so legacy code may depend on this approach, even though it is not
4699standard.
4700
4701To accommodate such use, GNAT provides a preprocessor (modeled to a large
4702extent on the various preprocessors that have been used
4703with legacy code on other compilers, to enable easier transition).
4704
4705@geindex gnatprep
4706
4707The preprocessor may be used in two separate modes. It can be used quite
4708separately from the compiler, to generate a separate output source file
4709that is then fed to the compiler as a separate step. This is the
4710@cite{gnatprep} utility, whose use is fully described in
4711@ref{19,,Preprocessing with gnatprep}.
4712
4713The preprocessing language allows such constructs as
4714
4715@example
4716#if DEBUG or else (PRIORITY > 4) then
4717   bunch of declarations
4718#else
4719   completely different bunch of declarations
4720#end if;
4721@end example
4722
4723The values of the symbols @cite{DEBUG} and @cite{PRIORITY} can be
4724defined either on the command line or in a separate file.
4725
4726The other way of running the preprocessor is even closer to the C style and
4727often more convenient. In this approach the preprocessing is integrated into
4728the compilation process. The compiler is fed the preprocessor input which
4729includes @cite{#if} lines etc, and then the compiler carries out the
4730preprocessing internally and processes the resulting output.
4731For more details on this approach, see @ref{1a,,Integrated Preprocessing}.
4732
4733@node Preprocessing with gnatprep,Integrated Preprocessing,Modeling Conditional Compilation in Ada,Conditional Compilation
4734@anchor{gnat_ugn/the_gnat_compilation_model id54}@anchor{ab}@anchor{gnat_ugn/the_gnat_compilation_model preprocessing-with-gnatprep}@anchor{19}
4735@subsection Preprocessing with @cite{gnatprep}
4736
4737
4738@geindex gnatprep
4739
4740@geindex Preprocessing (gnatprep)
4741
4742This section discusses how to use GNAT's @cite{gnatprep} utility for simple
4743preprocessing.
4744Although designed for use with GNAT, @cite{gnatprep} does not depend on any
4745special GNAT features.
4746For further discussion of conditional compilation in general, see
4747@ref{18,,Conditional Compilation}.
4748
4749@menu
4750* Preprocessing Symbols::
4751* Using gnatprep::
4752* Switches for gnatprep::
4753* Form of Definitions File::
4754* Form of Input Text for gnatprep::
4755
4756@end menu
4757
4758@node Preprocessing Symbols,Using gnatprep,,Preprocessing with gnatprep
4759@anchor{gnat_ugn/the_gnat_compilation_model id55}@anchor{ac}@anchor{gnat_ugn/the_gnat_compilation_model preprocessing-symbols}@anchor{ad}
4760@subsubsection Preprocessing Symbols
4761
4762
4763Preprocessing symbols are defined in definition files and referred to in
4764sources to be preprocessed. A Preprocessing symbol is an identifier, following
4765normal Ada (case-insensitive) rules for its syntax, with the restriction that
4766all characters need to be in the ASCII set (no accented letters).
4767
4768@node Using gnatprep,Switches for gnatprep,Preprocessing Symbols,Preprocessing with gnatprep
4769@anchor{gnat_ugn/the_gnat_compilation_model using-gnatprep}@anchor{ae}@anchor{gnat_ugn/the_gnat_compilation_model id56}@anchor{af}
4770@subsubsection Using @cite{gnatprep}
4771
4772
4773To call @cite{gnatprep} use:
4774
4775@example
4776$ gnatprep [`switches`] `infile` `outfile` [`deffile`]
4777@end example
4778
4779where
4780
4781
4782@itemize *
4783
4784@item
4785
4786@table @asis
4787
4788@item @emph{switches}
4789
4790is an optional sequence of switches as described in the next section.
4791@end table
4792
4793@item
4794
4795@table @asis
4796
4797@item @emph{infile}
4798
4799is the full name of the input file, which is an Ada source
4800file containing preprocessor directives.
4801@end table
4802
4803@item
4804
4805@table @asis
4806
4807@item @emph{outfile}
4808
4809is the full name of the output file, which is an Ada source
4810in standard Ada form. When used with GNAT, this file name will
4811normally have an ads or adb suffix.
4812@end table
4813
4814@item
4815
4816@table @asis
4817
4818@item @emph{deffile}
4819
4820is the full name of a text file containing definitions of
4821preprocessing symbols to be referenced by the preprocessor. This argument is
4822optional, and can be replaced by the use of the @emph{-D} switch.
4823@end table
4824@end itemize
4825
4826@node Switches for gnatprep,Form of Definitions File,Using gnatprep,Preprocessing with gnatprep
4827@anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatprep}@anchor{b0}@anchor{gnat_ugn/the_gnat_compilation_model id57}@anchor{b1}
4828@subsubsection Switches for @cite{gnatprep}
4829
4830
4831@geindex -b (gnatprep)
4832
4833
4834@table @asis
4835
4836@item @code{-b}
4837
4838Causes both preprocessor lines and the lines deleted by
4839preprocessing to be replaced by blank lines in the output source file,
4840preserving line numbers in the output file.
4841@end table
4842
4843@geindex -c (gnatprep)
4844
4845
4846@table @asis
4847
4848@item @code{-c}
4849
4850Causes both preprocessor lines and the lines deleted
4851by preprocessing to be retained in the output source as comments marked
4852with the special string @cite{"--! "}. This option will result in line numbers
4853being preserved in the output file.
4854@end table
4855
4856@geindex -C (gnatprep)
4857
4858
4859@table @asis
4860
4861@item @code{-C}
4862
4863Causes comments to be scanned. Normally comments are ignored by gnatprep.
4864If this option is specified, then comments are scanned and any $symbol
4865substitutions performed as in program text. This is particularly useful
4866when structured comments are used (e.g., when writing programs in the
4867SPARK dialect of Ada). Note that this switch is not available when
4868doing integrated preprocessing (it would be useless in this context
4869since comments are ignored by the compiler in any case).
4870@end table
4871
4872@geindex -D (gnatprep)
4873
4874
4875@table @asis
4876
4877@item @code{-D@emph{symbol}=@emph{value}}
4878
4879Defines a new preprocessing symbol, associated with value. If no value is given
4880on the command line, then symbol is considered to be @cite{True}. This switch
4881can be used in place of a definition file.
4882@end table
4883
4884@geindex -r (gnatprep)
4885
4886
4887@table @asis
4888
4889@item @code{-r}
4890
4891Causes a @cite{Source_Reference} pragma to be generated that
4892references the original input file, so that error messages will use
4893the file name of this original file. The use of this switch implies
4894that preprocessor lines are not to be removed from the file, so its
4895use will force @emph{-b} mode if @emph{-c}
4896has not been specified explicitly.
4897
4898Note that if the file to be preprocessed contains multiple units, then
4899it will be necessary to @cite{gnatchop} the output file from
4900@cite{gnatprep}. If a @cite{Source_Reference} pragma is present
4901in the preprocessed file, it will be respected by
4902@cite{gnatchop -r}
4903so that the final chopped files will correctly refer to the original
4904input source file for @cite{gnatprep}.
4905@end table
4906
4907@geindex -s (gnatprep)
4908
4909
4910@table @asis
4911
4912@item @code{-s}
4913
4914Causes a sorted list of symbol names and values to be
4915listed on the standard output file.
4916@end table
4917
4918@geindex -u (gnatprep)
4919
4920
4921@table @asis
4922
4923@item @code{-u}
4924
4925Causes undefined symbols to be treated as having the value FALSE in the context
4926of a preprocessor test. In the absence of this option, an undefined symbol in
4927a @cite{#if} or @cite{#elsif} test will be treated as an error.
4928@end table
4929
4930Note: if neither @emph{-b} nor @emph{-c} is present,
4931then preprocessor lines and
4932deleted lines are completely removed from the output, unless -r is
4933specified, in which case -b is assumed.
4934
4935@node Form of Definitions File,Form of Input Text for gnatprep,Switches for gnatprep,Preprocessing with gnatprep
4936@anchor{gnat_ugn/the_gnat_compilation_model form-of-definitions-file}@anchor{b2}@anchor{gnat_ugn/the_gnat_compilation_model id58}@anchor{b3}
4937@subsubsection Form of Definitions File
4938
4939
4940The definitions file contains lines of the form:
4941
4942@example
4943symbol := value
4944@end example
4945
4946where @cite{symbol} is a preprocessing symbol, and @cite{value} is one of the following:
4947
4948
4949@itemize *
4950
4951@item
4952Empty, corresponding to a null substitution,
4953
4954@item
4955A string literal using normal Ada syntax, or
4956
4957@item
4958Any sequence of characters from the set @{letters, digits, period, underline@}.
4959@end itemize
4960
4961Comment lines may also appear in the definitions file, starting with
4962the usual @code{--},
4963and comments may be added to the definitions lines.
4964
4965@node Form of Input Text for gnatprep,,Form of Definitions File,Preprocessing with gnatprep
4966@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}
4967@subsubsection Form of Input Text for @cite{gnatprep}
4968
4969
4970The input text may contain preprocessor conditional inclusion lines,
4971as well as general symbol substitution sequences.
4972
4973The preprocessor conditional inclusion commands have the form:
4974
4975@example
4976#if <expression> [then]
4977   lines
4978#elsif <expression> [then]
4979   lines
4980#elsif <expression> [then]
4981   lines
4982...
4983#else
4984   lines
4985#end if;
4986@end example
4987
4988In this example, <expression> is defined by the following grammar:
4989
4990@example
4991<expression> ::=  <symbol>
4992<expression> ::=  <symbol> = "<value>"
4993<expression> ::=  <symbol> = <symbol>
4994<expression> ::=  <symbol> = <integer>
4995<expression> ::=  <symbol> > <integer>
4996<expression> ::=  <symbol> >= <integer>
4997<expression> ::=  <symbol> < <integer>
4998<expression> ::=  <symbol> <= <integer>
4999<expression> ::=  <symbol> 'Defined
5000<expression> ::=  not <expression>
5001<expression> ::=  <expression> and <expression>
5002<expression> ::=  <expression> or <expression>
5003<expression> ::=  <expression> and then <expression>
5004<expression> ::=  <expression> or else <expression>
5005<expression> ::=  ( <expression> )
5006@end example
5007
5008Note the following restriction: it is not allowed to have "and" or "or"
5009following "not" in the same expression without parentheses. For example, this
5010is not allowed:
5011
5012@example
5013not X or Y
5014@end example
5015
5016This can be expressed instead as one of the following forms:
5017
5018@example
5019(not X) or Y
5020not (X or Y)
5021@end example
5022
5023For the first test (<expression> ::= <symbol>) the symbol must have
5024either the value true or false, that is to say the right-hand of the
5025symbol definition must be one of the (case-insensitive) literals
5026@cite{True} or @cite{False}. If the value is true, then the
5027corresponding lines are included, and if the value is false, they are
5028excluded.
5029
5030When comparing a symbol to an integer, the integer is any non negative
5031literal integer as defined in the Ada Reference Manual, such as 3, 16#FF# or
50322#11#. The symbol value must also be a non negative integer. Integer values
5033in the range 0 .. 2**31-1 are supported.
5034
5035The test (<expression> ::= <symbol>'Defined) is true only if
5036the symbol has been defined in the definition file or by a @emph{-D}
5037switch on the command line. Otherwise, the test is false.
5038
5039The equality tests are case insensitive, as are all the preprocessor lines.
5040
5041If the symbol referenced is not defined in the symbol definitions file,
5042then the effect depends on whether or not switch @emph{-u}
5043is specified. If so, then the symbol is treated as if it had the value
5044false and the test fails. If this switch is not specified, then
5045it is an error to reference an undefined symbol. It is also an error to
5046reference a symbol that is defined with a value other than @cite{True}
5047or @cite{False}.
5048
5049The use of the @cite{not} operator inverts the sense of this logical test.
5050The @cite{not} operator cannot be combined with the @cite{or} or @cite{and}
5051operators, without parentheses. For example, "if not X or Y then" is not
5052allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
5053
5054The @cite{then} keyword is optional as shown
5055
5056The @cite{#} must be the first non-blank character on a line, but
5057otherwise the format is free form. Spaces or tabs may appear between
5058the @cite{#} and the keyword. The keywords and the symbols are case
5059insensitive as in normal Ada code. Comments may be used on a
5060preprocessor line, but other than that, no other tokens may appear on a
5061preprocessor line. Any number of @cite{elsif} clauses can be present,
5062including none at all. The @cite{else} is optional, as in Ada.
5063
5064The @cite{#} marking the start of a preprocessor line must be the first
5065non-blank character on the line, i.e., it must be preceded only by
5066spaces or horizontal tabs.
5067
5068Symbol substitution outside of preprocessor lines is obtained by using
5069the sequence:
5070
5071@example
5072$symbol
5073@end example
5074
5075anywhere within a source line, except in a comment or within a
5076string literal. The identifier
5077following the @cite{$} must match one of the symbols defined in the symbol
5078definition file, and the result is to substitute the value of the
5079symbol in place of @cite{$symbol} in the output file.
5080
5081Note that although the substitution of strings within a string literal
5082is not possible, it is possible to have a symbol whose defined value is
5083a string literal. So instead of setting XYZ to @cite{hello} and writing:
5084
5085@example
5086Header : String := "$XYZ";
5087@end example
5088
5089you should set XYZ to @cite{"hello"} and write:
5090
5091@example
5092Header : String := $XYZ;
5093@end example
5094
5095and then the substitution will occur as desired.
5096
5097@node Integrated Preprocessing,,Preprocessing with gnatprep,Conditional Compilation
5098@anchor{gnat_ugn/the_gnat_compilation_model id60}@anchor{b6}@anchor{gnat_ugn/the_gnat_compilation_model integrated-preprocessing}@anchor{1a}
5099@subsection Integrated Preprocessing
5100
5101
5102GNAT sources may be preprocessed immediately before compilation.
5103In this case, the actual
5104text of the source is not the text of the source file, but is derived from it
5105through a process called preprocessing. Integrated preprocessing is specified
5106through switches @emph{-gnatep} and/or @emph{-gnateD}. @emph{-gnatep}
5107indicates, through a text file, the preprocessing data to be used.
5108@code{-gnateD} specifies or modifies the values of preprocessing symbol.
5109Note that integrated preprocessing applies only to Ada source files, it is
5110not available for configuration pragma files.
5111
5112Note that when integrated preprocessing is used, the output from the
5113preprocessor is not written to any external file. Instead it is passed
5114internally to the compiler. If you need to preserve the result of
5115preprocessing in a file, then you should use @emph{gnatprep}
5116to perform the desired preprocessing in stand-alone mode.
5117
5118It is recommended that @emph{gnatmake} switch -s should be
5119used when Integrated Preprocessing is used. The reason is that preprocessing
5120with another Preprocessing Data file without changing the sources will
5121not trigger recompilation without this switch.
5122
5123Note that @emph{gnatmake} switch -m will almost
5124always trigger recompilation for sources that are preprocessed,
5125because @emph{gnatmake} cannot compute the checksum of the source after
5126preprocessing.
5127
5128The actual preprocessing function is described in detail in section
5129@ref{19,,Preprocessing with gnatprep}. This section only describes how integrated
5130preprocessing is triggered and parameterized.
5131
5132@geindex -gnatep (gcc)
5133
5134
5135@table @asis
5136
5137@item @code{-gnatep=@emph{file}}
5138
5139This switch indicates to the compiler the file name (without directory
5140information) of the preprocessor data file to use. The preprocessor data file
5141should be found in the source directories. Note that when the compiler is
5142called by a builder such as (@emph{gnatmake} with a project
5143file, if the object directory is not also a source directory, the builder needs
5144to be called with @emph{-x}.
5145
5146A preprocessing data file is a text file with significant lines indicating
5147how should be preprocessed either a specific source or all sources not
5148mentioned in other lines. A significant line is a nonempty, non-comment line.
5149Comments are similar to Ada comments.
5150
5151Each significant line starts with either a literal string or the character '*'.
5152A literal string is the file name (without directory information) of the source
5153to preprocess. A character '*' indicates the preprocessing for all the sources
5154that are not specified explicitly on other lines (order of the lines is not
5155significant). It is an error to have two lines with the same file name or two
5156lines starting with the character '*'.
5157
5158After the file name or the character '*', another optional literal string
5159indicating the file name of the definition file to be used for preprocessing
5160(@ref{b2,,Form of Definitions File}). The definition files are found by the
5161compiler in one of the source directories. In some cases, when compiling
5162a source in a directory other than the current directory, if the definition
5163file is in the current directory, it may be necessary to add the current
5164directory as a source directory through switch -I., otherwise
5165the compiler would not find the definition file.
5166
5167Then, optionally, switches similar to those of @cite{gnatprep} may
5168be found. Those switches are:
5169
5170
5171@table @asis
5172
5173@item @code{-b}
5174
5175Causes both preprocessor lines and the lines deleted by
5176preprocessing to be replaced by blank lines, preserving the line number.
5177This switch is always implied; however, if specified after @emph{-c}
5178it cancels the effect of @emph{-c}.
5179
5180@item @code{-c}
5181
5182Causes both preprocessor lines and the lines deleted
5183by preprocessing to be retained as comments marked
5184with the special string '@cite{--!}'.
5185
5186@item @code{-Dsymbol=@emph{value}}
5187
5188Define or redefine a symbol, associated with value. A symbol is an Ada
5189identifier, or an Ada reserved word, with the exception of @cite{if},
5190@cite{else}, @cite{elsif}, @cite{end}, @cite{and}, @cite{or} and @cite{then}.
5191@cite{value} is either a literal string, an Ada identifier or any Ada reserved
5192word. A symbol declared with this switch replaces a symbol with the
5193same name defined in a definition file.
5194
5195@item @code{-s}
5196
5197Causes a sorted list of symbol names and values to be
5198listed on the standard output file.
5199
5200@item @code{-u}
5201
5202Causes undefined symbols to be treated as having the value @cite{FALSE}
5203in the context
5204of a preprocessor test. In the absence of this option, an undefined symbol in
5205a @cite{#if} or @cite{#elsif} test will be treated as an error.
5206@end table
5207
5208Examples of valid lines in a preprocessor data file:
5209
5210@example
5211"toto.adb"  "prep.def" -u
5212--  preprocess "toto.adb", using definition file "prep.def",
5213--  undefined symbol are False.
5214
5215* -c -DVERSION=V101
5216--  preprocess all other sources without a definition file;
5217--  suppressed lined are commented; symbol VERSION has the value V101.
5218
5219"titi.adb" "prep2.def" -s
5220--  preprocess "titi.adb", using definition file "prep2.def";
5221--  list all symbols with their values.
5222@end example
5223@end table
5224
5225@geindex -gnateD (gcc)
5226
5227
5228@table @asis
5229
5230@item @code{-gnateDsymbol[=value]}
5231
5232Define or redefine a preprocessing symbol, associated with value. If no value
5233is given on the command line, then the value of the symbol is @cite{True}.
5234A symbol is an identifier, following normal Ada (case-insensitive)
5235rules for its syntax, and value is either an arbitrary string between double
5236quotes or any sequence (including an empty sequence) of characters from the
5237set (letters, digits, period, underline).
5238Ada reserved words may be used as symbols, with the exceptions of @cite{if},
5239@cite{else}, @cite{elsif}, @cite{end}, @cite{and}, @cite{or} and @cite{then}.
5240
5241Examples:
5242
5243@example
5244-gnateDToto=Titi
5245-gnateDFoo
5246-gnateDFoo=\"Foo-Bar\"
5247@end example
5248
5249A symbol declared with this switch on the command line replaces a
5250symbol with the same name either in a definition file or specified with a
5251switch -D in the preprocessor data file.
5252
5253This switch is similar to switch @emph{-D} of @cite{gnatprep}.
5254
5255@item @code{-gnateG}
5256
5257When integrated preprocessing is performed and the preprocessor modifies
5258the source text, write the result of this preprocessing into a file
5259<source>.prep.
5260@end table
5261
5262@node Mixed Language Programming,GNAT and Other Compilation Models,Conditional Compilation,The GNAT Compilation Model
5263@anchor{gnat_ugn/the_gnat_compilation_model mixed-language-programming}@anchor{46}@anchor{gnat_ugn/the_gnat_compilation_model id61}@anchor{b7}
5264@section Mixed Language Programming
5265
5266
5267@geindex Mixed Language Programming
5268
5269This section describes how to develop a mixed-language program,
5270with a focus on combining Ada with C or C++.
5271
5272@menu
5273* Interfacing to C::
5274* Calling Conventions::
5275* Building Mixed Ada and C++ Programs::
5276* Generating Ada Bindings for C and C++ headers::
5277* Generating C Headers for Ada Specifications::
5278
5279@end menu
5280
5281@node Interfacing to C,Calling Conventions,,Mixed Language Programming
5282@anchor{gnat_ugn/the_gnat_compilation_model interfacing-to-c}@anchor{b8}@anchor{gnat_ugn/the_gnat_compilation_model id62}@anchor{b9}
5283@subsection Interfacing to C
5284
5285
5286Interfacing Ada with a foreign language such as C involves using
5287compiler directives to import and/or export entity definitions in each
5288language -- using @cite{extern} statements in C, for instance, and the
5289@cite{Import}, @cite{Export}, and @cite{Convention} pragmas in Ada.
5290A full treatment of these topics is provided in Appendix B, section 1
5291of the Ada Reference Manual.
5292
5293There are two ways to build a program using GNAT that contains some Ada
5294sources and some foreign language sources, depending on whether or not
5295the main subprogram is written in Ada.  Here is a source example with
5296the main subprogram in Ada:
5297
5298@example
5299/* file1.c */
5300#include <stdio.h>
5301
5302void print_num (int num)
5303@{
5304  printf ("num is %d.\\n", num);
5305  return;
5306@}
5307@end example
5308
5309@example
5310/* file2.c */
5311
5312/* num_from_Ada is declared in my_main.adb */
5313extern int num_from_Ada;
5314
5315int get_num (void)
5316@{
5317  return num_from_Ada;
5318@}
5319@end example
5320
5321@example
5322--  my_main.adb
5323procedure My_Main is
5324
5325   --  Declare then export an Integer entity called num_from_Ada
5326   My_Num : Integer := 10;
5327   pragma Export (C, My_Num, "num_from_Ada");
5328
5329   --  Declare an Ada function spec for Get_Num, then use
5330   --  C function get_num for the implementation.
5331   function Get_Num return Integer;
5332   pragma Import (C, Get_Num, "get_num");
5333
5334   --  Declare an Ada procedure spec for Print_Num, then use
5335   --  C function print_num for the implementation.
5336   procedure Print_Num (Num : Integer);
5337   pragma Import (C, Print_Num, "print_num";
5338
5339begin
5340   Print_Num (Get_Num);
5341end My_Main;
5342@end example
5343
5344To build this example:
5345
5346
5347@itemize *
5348
5349@item
5350First compile the foreign language files to
5351generate object files:
5352
5353@example
5354$ gcc -c file1.c
5355$ gcc -c file2.c
5356@end example
5357
5358@item
5359Then, compile the Ada units to produce a set of object files and ALI
5360files:
5361
5362@example
5363$ gnatmake -c my_main.adb
5364@end example
5365
5366@item
5367Run the Ada binder on the Ada main program:
5368
5369@example
5370$ gnatbind my_main.ali
5371@end example
5372
5373@item
5374Link the Ada main program, the Ada objects and the other language
5375objects:
5376
5377@example
5378$ gnatlink my_main.ali file1.o file2.o
5379@end example
5380@end itemize
5381
5382The last three steps can be grouped in a single command:
5383
5384@example
5385$ gnatmake my_main.adb -largs file1.o file2.o
5386@end example
5387
5388@geindex Binder output file
5389
5390If the main program is in a language other than Ada, then you may have
5391more than one entry point into the Ada subsystem. You must use a special
5392binder option to generate callable routines that initialize and
5393finalize the Ada units (@ref{ba,,Binding with Non-Ada Main Programs}).
5394Calls to the initialization and finalization routines must be inserted
5395in the main program, or some other appropriate point in the code. The
5396call to initialize the Ada units must occur before the first Ada
5397subprogram is called, and the call to finalize the Ada units must occur
5398after the last Ada subprogram returns. The binder will place the
5399initialization and finalization subprograms into the
5400@code{b~xxx.adb} file where they can be accessed by your C
5401sources.  To illustrate, we have the following example:
5402
5403@example
5404/* main.c */
5405extern void adainit (void);
5406extern void adafinal (void);
5407extern int add (int, int);
5408extern int sub (int, int);
5409
5410int main (int argc, char *argv[])
5411@{
5412   int a = 21, b = 7;
5413
5414   adainit();
5415
5416   /* Should print "21 + 7 = 28" */
5417   printf ("%d + %d = %d\\n", a, b, add (a, b));
5418
5419   /* Should print "21 - 7 = 14" */
5420   printf ("%d - %d = %d\\n", a, b, sub (a, b));
5421
5422   adafinal();
5423@}
5424@end example
5425
5426@example
5427--  unit1.ads
5428package Unit1 is
5429   function Add (A, B : Integer) return Integer;
5430   pragma Export (C, Add, "add");
5431end Unit1;
5432@end example
5433
5434@example
5435--  unit1.adb
5436package body Unit1 is
5437   function Add (A, B : Integer) return Integer is
5438   begin
5439      return A + B;
5440   end Add;
5441end Unit1;
5442@end example
5443
5444@example
5445--  unit2.ads
5446package Unit2 is
5447   function Sub (A, B : Integer) return Integer;
5448   pragma Export (C, Sub, "sub");
5449end Unit2;
5450@end example
5451
5452@example
5453--  unit2.adb
5454package body Unit2 is
5455   function Sub (A, B : Integer) return Integer is
5456   begin
5457      return A - B;
5458   end Sub;
5459end Unit2;
5460@end example
5461
5462The build procedure for this application is similar to the last
5463example's:
5464
5465
5466@itemize *
5467
5468@item
5469First, compile the foreign language files to generate object files:
5470
5471@example
5472$ gcc -c main.c
5473@end example
5474
5475@item
5476Next, compile the Ada units to produce a set of object files and ALI
5477files:
5478
5479@example
5480$ gnatmake -c unit1.adb
5481$ gnatmake -c unit2.adb
5482@end example
5483
5484@item
5485Run the Ada binder on every generated ALI file.  Make sure to use the
5486@code{-n} option to specify a foreign main program:
5487
5488@example
5489$ gnatbind -n unit1.ali unit2.ali
5490@end example
5491
5492@item
5493Link the Ada main program, the Ada objects and the foreign language
5494objects. You need only list the last ALI file here:
5495
5496@example
5497$ gnatlink unit2.ali main.o -o exec_file
5498@end example
5499
5500This procedure yields a binary executable called @code{exec_file}.
5501@end itemize
5502
5503Depending on the circumstances (for example when your non-Ada main object
5504does not provide symbol @cite{main}), you may also need to instruct the
5505GNAT linker not to include the standard startup objects by passing the
5506@code{-nostartfiles} switch to @cite{gnatlink}.
5507
5508@node Calling Conventions,Building Mixed Ada and C++ Programs,Interfacing to C,Mixed Language Programming
5509@anchor{gnat_ugn/the_gnat_compilation_model calling-conventions}@anchor{bb}@anchor{gnat_ugn/the_gnat_compilation_model id63}@anchor{bc}
5510@subsection Calling Conventions
5511
5512
5513@geindex Foreign Languages
5514
5515@geindex Calling Conventions
5516
5517GNAT follows standard calling sequence conventions and will thus interface
5518to any other language that also follows these conventions. The following
5519Convention identifiers are recognized by GNAT:
5520
5521@geindex Interfacing to Ada
5522
5523@geindex Other Ada compilers
5524
5525@geindex Convention Ada
5526
5527
5528@table @asis
5529
5530@item @emph{Ada}
5531
5532This indicates that the standard Ada calling sequence will be
5533used and all Ada data items may be passed without any limitations in the
5534case where GNAT is used to generate both the caller and callee. It is also
5535possible to mix GNAT generated code and code generated by another Ada
5536compiler. In this case, the data types should be restricted to simple
5537cases, including primitive types. Whether complex data types can be passed
5538depends on the situation. Probably it is safe to pass simple arrays, such
5539as arrays of integers or floats. Records may or may not work, depending
5540on whether both compilers lay them out identically. Complex structures
5541involving variant records, access parameters, tasks, or protected types,
5542are unlikely to be able to be passed.
5543
5544Note that in the case of GNAT running
5545on a platform that supports HP Ada 83, a higher degree of compatibility
5546can be guaranteed, and in particular records are laid out in an identical
5547manner in the two compilers. Note also that if output from two different
5548compilers is mixed, the program is responsible for dealing with elaboration
5549issues. Probably the safest approach is to write the main program in the
5550version of Ada other than GNAT, so that it takes care of its own elaboration
5551requirements, and then call the GNAT-generated adainit procedure to ensure
5552elaboration of the GNAT components. Consult the documentation of the other
5553Ada compiler for further details on elaboration.
5554
5555However, it is not possible to mix the tasking run time of GNAT and
5556HP Ada 83, All the tasking operations must either be entirely within
5557GNAT compiled sections of the program, or entirely within HP Ada 83
5558compiled sections of the program.
5559@end table
5560
5561@geindex Interfacing to Assembly
5562
5563@geindex Convention Assembler
5564
5565
5566@table @asis
5567
5568@item @emph{Assembler}
5569
5570Specifies assembler as the convention. In practice this has the
5571same effect as convention Ada (but is not equivalent in the sense of being
5572considered the same convention).
5573@end table
5574
5575@geindex Convention Asm
5576
5577@geindex Asm
5578
5579
5580@table @asis
5581
5582@item @emph{Asm}
5583
5584Equivalent to Assembler.
5585
5586@geindex Interfacing to COBOL
5587
5588@geindex Convention COBOL
5589@end table
5590
5591@geindex COBOL
5592
5593
5594@table @asis
5595
5596@item @emph{COBOL}
5597
5598Data will be passed according to the conventions described
5599in section B.4 of the Ada Reference Manual.
5600@end table
5601
5602@geindex C
5603
5604@geindex Interfacing to C
5605
5606@geindex Convention C
5607
5608
5609@table @asis
5610
5611@item @emph{C}
5612
5613Data will be passed according to the conventions described
5614in section B.3 of the Ada Reference Manual.
5615
5616A note on interfacing to a C 'varargs' function:
5617
5618@quotation
5619
5620@geindex C varargs function
5621
5622@geindex Interfacing to C varargs function
5623
5624@geindex varargs function interfaces
5625
5626In C, @cite{varargs} allows a function to take a variable number of
5627arguments. There is no direct equivalent in this to Ada. One
5628approach that can be used is to create a C wrapper for each
5629different profile and then interface to this C wrapper. For
5630example, to print an @cite{int} value using @cite{printf},
5631create a C function @cite{printfi} that takes two arguments, a
5632pointer to a string and an int, and calls @cite{printf}.
5633Then in the Ada program, use pragma @cite{Import} to
5634interface to @cite{printfi}.
5635
5636It may work on some platforms to directly interface to
5637a @cite{varargs} function by providing a specific Ada profile
5638for a particular call. However, this does not work on
5639all platforms, since there is no guarantee that the
5640calling sequence for a two argument normal C function
5641is the same as for calling a @cite{varargs} C function with
5642the same two arguments.
5643@end quotation
5644@end table
5645
5646@geindex Convention Default
5647
5648@geindex Default
5649
5650
5651@table @asis
5652
5653@item @emph{Default}
5654
5655Equivalent to C.
5656@end table
5657
5658@geindex Convention External
5659
5660@geindex External
5661
5662
5663@table @asis
5664
5665@item @emph{External}
5666
5667Equivalent to C.
5668@end table
5669
5670@geindex C++
5671
5672@geindex Interfacing to C++
5673
5674@geindex Convention C++
5675
5676
5677@table @asis
5678
5679@item @emph{C_Plus_Plus (or CPP)}
5680
5681This stands for C++. For most purposes this is identical to C.
5682See the separate description of the specialized GNAT pragmas relating to
5683C++ interfacing for further details.
5684@end table
5685
5686@geindex Fortran
5687
5688@geindex Interfacing to Fortran
5689
5690@geindex Convention Fortran
5691
5692
5693@table @asis
5694
5695@item @emph{Fortran}
5696
5697Data will be passed according to the conventions described
5698in section B.5 of the Ada Reference Manual.
5699
5700@item @emph{Intrinsic}
5701
5702This applies to an intrinsic operation, as defined in the Ada
5703Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
5704this means that the body of the subprogram is provided by the compiler itself,
5705usually by means of an efficient code sequence, and that the user does not
5706supply an explicit body for it. In an application program, the pragma may
5707be applied to the following sets of names:
5708
5709
5710@itemize *
5711
5712@item
5713Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_Arithmetic.
5714The corresponding subprogram declaration must have
5715two formal parameters. The
5716first one must be a signed integer type or a modular type with a binary
5717modulus, and the second parameter must be of type Natural.
5718The return type must be the same as the type of the first argument. The size
5719of this type can only be 8, 16, 32, or 64.
5720
5721@item
5722Binary arithmetic operators: '+', '-', '*', '/'.
5723The corresponding operator declaration must have parameters and result type
5724that have the same root numeric type (for example, all three are long_float
5725types). This simplifies the definition of operations that use type checking
5726to perform dimensional checks:
5727@end itemize
5728
5729@example
5730  type Distance is new Long_Float;
5731  type Time     is new Long_Float;
5732  type Velocity is new Long_Float;
5733  function "/" (D : Distance; T : Time)
5734    return Velocity;
5735  pragma Import (Intrinsic, "/");
5736
5737This common idiom is often programmed with a generic definition and an
5738explicit body. The pragma makes it simpler to introduce such declarations.
5739It incurs no overhead in compilation time or code size, because it is
5740implemented as a single machine instruction.
5741@end example
5742
5743
5744@itemize *
5745
5746@item
5747General subprogram entities. This is used  to bind an Ada subprogram
5748declaration to
5749a compiler builtin by name with back-ends where such interfaces are
5750available. A typical example is the set of @cite{__builtin} functions
5751exposed by the GCC back-end, as in the following example:
5752
5753@example
5754function builtin_sqrt (F : Float) return Float;
5755pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
5756@end example
5757
5758Most of the GCC builtins are accessible this way, and as for other
5759import conventions (e.g. C), it is the user's responsibility to ensure
5760that the Ada subprogram profile matches the underlying builtin
5761expectations.
5762@end itemize
5763@end table
5764
5765@geindex Stdcall
5766
5767@geindex Convention Stdcall
5768
5769
5770@table @asis
5771
5772@item @emph{Stdcall}
5773
5774This is relevant only to Windows implementations of GNAT,
5775and specifies that the @cite{Stdcall} calling sequence will be used,
5776as defined by the NT API. Nevertheless, to ease building
5777cross-platform bindings this convention will be handled as a @cite{C} calling
5778convention on non-Windows platforms.
5779@end table
5780
5781@geindex DLL
5782
5783@geindex Convention DLL
5784
5785
5786@table @asis
5787
5788@item @emph{DLL}
5789
5790This is equivalent to @cite{Stdcall}.
5791@end table
5792
5793@geindex Win32
5794
5795@geindex Convention Win32
5796
5797
5798@table @asis
5799
5800@item @emph{Win32}
5801
5802This is equivalent to @cite{Stdcall}.
5803@end table
5804
5805@geindex Stubbed
5806
5807@geindex Convention Stubbed
5808
5809
5810@table @asis
5811
5812@item @emph{Stubbed}
5813
5814This is a special convention that indicates that the compiler
5815should provide a stub body that raises @cite{Program_Error}.
5816@end table
5817
5818GNAT additionally provides a useful pragma @cite{Convention_Identifier}
5819that can be used to parameterize conventions and allow additional synonyms
5820to be specified. For example if you have legacy code in which the convention
5821identifier Fortran77 was used for Fortran, you can use the configuration
5822pragma:
5823
5824@example
5825pragma Convention_Identifier (Fortran77, Fortran);
5826@end example
5827
5828And from now on the identifier Fortran77 may be used as a convention
5829identifier (for example in an @cite{Import} pragma) with the same
5830meaning as Fortran.
5831
5832@node Building Mixed Ada and C++ Programs,Generating Ada Bindings for C and C++ headers,Calling Conventions,Mixed Language Programming
5833@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}
5834@subsection Building Mixed Ada and C++ Programs
5835
5836
5837A programmer inexperienced with mixed-language development may find that
5838building an application containing both Ada and C++ code can be a
5839challenge.  This section gives a few hints that should make this task easier.
5840
5841@menu
5842* Interfacing to C++::
5843* Linking a Mixed C++ & Ada Program::
5844* A Simple Example::
5845* Interfacing with C++ constructors::
5846* Interfacing with C++ at the Class Level::
5847
5848@end menu
5849
5850@node Interfacing to C++,Linking a Mixed C++ & Ada Program,,Building Mixed Ada and C++ Programs
5851@anchor{gnat_ugn/the_gnat_compilation_model id65}@anchor{bf}@anchor{gnat_ugn/the_gnat_compilation_model id66}@anchor{c0}
5852@subsubsection Interfacing to C++
5853
5854
5855GNAT supports interfacing with the G++ compiler (or any C++ compiler
5856generating code that is compatible with the G++ Application Binary
5857Interface ---see @indicateurl{http://www.codesourcery.com/archives/cxx-abi}).
5858
5859Interfacing can be done at 3 levels: simple data, subprograms, and
5860classes. In the first two cases, GNAT offers a specific @cite{Convention C_Plus_Plus}
5861(or @cite{CPP}) that behaves exactly like @cite{Convention C}.
5862Usually, C++ mangles the names of subprograms. To generate proper mangled
5863names automatically, see @ref{1b,,Generating Ada Bindings for C and C++ headers}).
5864This problem can also be addressed manually in two ways:
5865
5866
5867@itemize *
5868
5869@item
5870by modifying the C++ code in order to force a C convention using
5871the @cite{extern "C"} syntax.
5872
5873@item
5874by figuring out the mangled name (using e.g. @emph{nm}) and using it as the
5875Link_Name argument of the pragma import.
5876@end itemize
5877
5878Interfacing at the class level can be achieved by using the GNAT specific
5879pragmas such as @cite{CPP_Constructor}.  See the @cite{GNAT_Reference_Manual} for additional information.
5880
5881@node Linking a Mixed C++ & Ada Program,A Simple Example,Interfacing to C++,Building Mixed Ada and C++ Programs
5882@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}
5883@subsubsection Linking a Mixed C++ & Ada Program
5884
5885
5886Usually the linker of the C++ development system must be used to link
5887mixed applications because most C++ systems will resolve elaboration
5888issues (such as calling constructors on global class instances)
5889transparently during the link phase. GNAT has been adapted to ease the
5890use of a foreign linker for the last phase. Three cases can be
5891considered:
5892
5893
5894@itemize *
5895
5896@item
5897Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
5898The C++ linker can simply be called by using the C++ specific driver
5899called @cite{g++}.
5900
5901Note that if the C++ code uses inline functions, you will need to
5902compile your C++ code with the @cite{-fkeep-inline-functions} switch in
5903order to provide an existing function implementation that the Ada code can
5904link with.
5905
5906@example
5907$ g++ -c -fkeep-inline-functions file1.C
5908$ g++ -c -fkeep-inline-functions file2.C
5909$ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
5910@end example
5911
5912@item
5913Using GNAT and G++ from two different GCC installations: If both
5914compilers are on the :envvar`PATH`, the previous method may be used. It is
5915important to note that environment variables such as
5916@geindex C_INCLUDE_PATH
5917@geindex environment variable; C_INCLUDE_PATH
5918@code{C_INCLUDE_PATH},
5919@geindex GCC_EXEC_PREFIX
5920@geindex environment variable; GCC_EXEC_PREFIX
5921@code{GCC_EXEC_PREFIX},
5922@geindex BINUTILS_ROOT
5923@geindex environment variable; BINUTILS_ROOT
5924@code{BINUTILS_ROOT}, and
5925@geindex GCC_ROOT
5926@geindex environment variable; GCC_ROOT
5927@code{GCC_ROOT} will affect both compilers
5928at the same time and may make one of the two compilers operate
5929improperly if set during invocation of the wrong compiler.  It is also
5930very important that the linker uses the proper @code{libgcc.a} GCC
5931library -- that is, the one from the C++ compiler installation. The
5932implicit link command as suggested in the @cite{gnatmake} command
5933from the former example can be replaced by an explicit link command with
5934the full-verbosity option in order to verify which library is used:
5935
5936@example
5937$ gnatbind ada_unit
5938$ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
5939@end example
5940
5941If there is a problem due to interfering environment variables, it can
5942be worked around by using an intermediate script. The following example
5943shows the proper script to use when GNAT has not been installed at its
5944default location and g++ has been installed at its default location:
5945
5946@example
5947$ cat ./my_script
5948#!/bin/sh
5949unset BINUTILS_ROOT
5950unset GCC_ROOT
5951c++ $*
5952$ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
5953@end example
5954
5955@item
5956Using a non-GNU C++ compiler: The commands previously described can be
5957used to insure that the C++ linker is used. Nonetheless, you need to add
5958a few more parameters to the link command line, depending on the exception
5959mechanism used.
5960
5961If the @cite{setjmp/longjmp} exception mechanism is used, only the paths
5962to the libgcc libraries are required:
5963
5964@example
5965$ cat ./my_script
5966#!/bin/sh
5967CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
5968$ gnatlink ada_unit file1.o file2.o --LINK=./my_script
5969@end example
5970
5971where CC is the name of the non-GNU C++ compiler.
5972
5973If the @cite{zero cost} exception mechanism is used, and the platform
5974supports automatic registration of exception tables (e.g., Solaris),
5975paths to more objects are required:
5976
5977@example
5978$ cat ./my_script
5979#!/bin/sh
5980CC `gcc -print-file-name=crtbegin.o` $* \\
5981`gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \\
5982`gcc -print-file-name=crtend.o`
5983$ gnatlink ada_unit file1.o file2.o --LINK=./my_script
5984@end example
5985
5986If the "zero cost exception" mechanism is used, and the platform
5987doesn't support automatic registration of exception tables (e.g., HP-UX
5988or AIX), the simple approach described above will not work and
5989a pre-linking phase using GNAT will be necessary.
5990@end itemize
5991
5992Another alternative is to use the @code{gprbuild} multi-language builder
5993which has a large knowledge base and knows how to link Ada and C++ code
5994together automatically in most cases.
5995
5996@node A Simple Example,Interfacing with C++ constructors,Linking a Mixed C++ & Ada Program,Building Mixed Ada and C++ Programs
5997@anchor{gnat_ugn/the_gnat_compilation_model id67}@anchor{c3}@anchor{gnat_ugn/the_gnat_compilation_model a-simple-example}@anchor{c4}
5998@subsubsection A Simple Example
5999
6000
6001The following example, provided as part of the GNAT examples, shows how
6002to achieve procedural interfacing between Ada and C++ in both
6003directions. The C++ class A has two methods. The first method is exported
6004to Ada by the means of an extern C wrapper function. The second method
6005calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
6006a limited record with a layout comparable to the C++ class. The Ada
6007subprogram, in turn, calls the C++ method. So, starting from the C++
6008main program, the process passes back and forth between the two
6009languages.
6010
6011Here are the compilation commands:
6012
6013@example
6014$ gnatmake -c simple_cpp_interface
6015$ g++ -c cpp_main.C
6016$ g++ -c ex7.C
6017$ gnatbind -n simple_cpp_interface
6018$ gnatlink simple_cpp_interface -o cpp_main --LINK=g++ -lstdc++ ex7.o cpp_main.o
6019@end example
6020
6021Here are the corresponding sources:
6022
6023@example
6024//cpp_main.C
6025
6026#include "ex7.h"
6027
6028extern "C" @{
6029  void adainit (void);
6030  void adafinal (void);
6031  void method1 (A *t);
6032@}
6033
6034void method1 (A *t)
6035@{
6036  t->method1 ();
6037@}
6038
6039int main ()
6040@{
6041  A obj;
6042  adainit ();
6043  obj.method2 (3030);
6044  adafinal ();
6045@}
6046@end example
6047
6048@example
6049//ex7.h
6050
6051class Origin @{
6052 public:
6053  int o_value;
6054@};
6055class A : public Origin @{
6056 public:
6057  void method1 (void);
6058  void method2 (int v);
6059  A();
6060  int   a_value;
6061@};
6062@end example
6063
6064@example
6065//ex7.C
6066
6067#include "ex7.h"
6068#include <stdio.h>
6069
6070extern "C" @{ void ada_method2 (A *t, int v);@}
6071
6072void A::method1 (void)
6073@{
6074  a_value = 2020;
6075  printf ("in A::method1, a_value = %d \\n",a_value);
6076@}
6077
6078void A::method2 (int v)
6079@{
6080   ada_method2 (this, v);
6081   printf ("in A::method2, a_value = %d \\n",a_value);
6082@}
6083
6084A::A(void)
6085@{
6086   a_value = 1010;
6087  printf ("in A::A, a_value = %d \\n",a_value);
6088@}
6089@end example
6090
6091@example
6092-- simple_cpp_interface.ads
6093with System;
6094package Simple_Cpp_Interface is
6095   type A is limited
6096      record
6097         Vptr    : System.Address;
6098         O_Value : Integer;
6099         A_Value : Integer;
6100      end record;
6101   pragma Convention (C, A);
6102
6103   procedure Method1 (This : in out A);
6104   pragma Import (C, Method1);
6105
6106   procedure Ada_Method2 (This : in out A; V : Integer);
6107   pragma Export (C, Ada_Method2);
6108
6109end Simple_Cpp_Interface;
6110@end example
6111
6112@example
6113-- simple_cpp_interface.adb
6114package body Simple_Cpp_Interface is
6115
6116   procedure Ada_Method2 (This : in out A; V : Integer) is
6117   begin
6118      Method1 (This);
6119      This.A_Value := V;
6120   end Ada_Method2;
6121
6122end Simple_Cpp_Interface;
6123@end example
6124
6125@node Interfacing with C++ constructors,Interfacing with C++ at the Class Level,A Simple Example,Building Mixed Ada and C++ Programs
6126@anchor{gnat_ugn/the_gnat_compilation_model id68}@anchor{c5}@anchor{gnat_ugn/the_gnat_compilation_model interfacing-with-c-constructors}@anchor{c6}
6127@subsubsection Interfacing with C++ constructors
6128
6129
6130In order to interface with C++ constructors GNAT provides the
6131@cite{pragma CPP_Constructor} (see the @cite{GNAT_Reference_Manual}
6132for additional information).
6133In this section we present some common uses of C++ constructors
6134in mixed-languages programs in GNAT.
6135
6136Let us assume that we need to interface with the following
6137C++ class:
6138
6139@example
6140class Root @{
6141public:
6142  int  a_value;
6143  int  b_value;
6144  virtual int Get_Value ();
6145  Root();              // Default constructor
6146  Root(int v);         // 1st non-default constructor
6147  Root(int v, int w);  // 2nd non-default constructor
6148@};
6149@end example
6150
6151For this purpose we can write the following package spec (further
6152information on how to build this spec is available in
6153@ref{c7,,Interfacing with C++ at the Class Level} and
6154@ref{1b,,Generating Ada Bindings for C and C++ headers}).
6155
6156@example
6157with Interfaces.C; use Interfaces.C;
6158package Pkg_Root is
6159  type Root is tagged limited record
6160     A_Value : int;
6161     B_Value : int;
6162  end record;
6163  pragma Import (CPP, Root);
6164
6165  function Get_Value (Obj : Root) return int;
6166  pragma Import (CPP, Get_Value);
6167
6168  function Constructor return Root;
6169  pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
6170
6171  function Constructor (v : Integer) return Root;
6172  pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
6173
6174  function Constructor (v, w : Integer) return Root;
6175  pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
6176end Pkg_Root;
6177@end example
6178
6179On the Ada side the constructor is represented by a function (whose
6180name is arbitrary) that returns the classwide type corresponding to
6181the imported C++ class. Although the constructor is described as a
6182function, it is typically a procedure with an extra implicit argument
6183(the object being initialized) at the implementation level. GNAT
6184issues the appropriate call, whatever it is, to get the object
6185properly initialized.
6186
6187Constructors can only appear in the following contexts:
6188
6189
6190@itemize *
6191
6192@item
6193On the right side of an initialization of an object of type @cite{T}.
6194
6195@item
6196On the right side of an initialization of a record component of type @cite{T}.
6197
6198@item
6199In an Ada 2005 limited aggregate.
6200
6201@item
6202In an Ada 2005 nested limited aggregate.
6203
6204@item
6205In an Ada 2005 limited aggregate that initializes an object built in
6206place by an extended return statement.
6207@end itemize
6208
6209In a declaration of an object whose type is a class imported from C++,
6210either the default C++ constructor is implicitly called by GNAT, or
6211else the required C++ constructor must be explicitly called in the
6212expression that initializes the object. For example:
6213
6214@example
6215Obj1 : Root;
6216Obj2 : Root := Constructor;
6217Obj3 : Root := Constructor (v => 10);
6218Obj4 : Root := Constructor (30, 40);
6219@end example
6220
6221The first two declarations are equivalent: in both cases the default C++
6222constructor is invoked (in the former case the call to the constructor is
6223implicit, and in the latter case the call is explicit in the object
6224declaration). @cite{Obj3} is initialized by the C++ non-default constructor
6225that takes an integer argument, and @cite{Obj4} is initialized by the
6226non-default C++ constructor that takes two integers.
6227
6228Let us derive the imported C++ class in the Ada side. For example:
6229
6230@example
6231type DT is new Root with record
6232   C_Value : Natural := 2009;
6233end record;
6234@end example
6235
6236In this case the components DT inherited from the C++ side must be
6237initialized by a C++ constructor, and the additional Ada components
6238of type DT are initialized by GNAT. The initialization of such an
6239object is done either by default, or by means of a function returning
6240an aggregate of type DT, or by means of an extension aggregate.
6241
6242@example
6243Obj5 : DT;
6244Obj6 : DT := Function_Returning_DT (50);
6245Obj7 : DT := (Constructor (30,40) with C_Value => 50);
6246@end example
6247
6248The declaration of @cite{Obj5} invokes the default constructors: the
6249C++ default constructor of the parent type takes care of the initialization
6250of the components inherited from Root, and GNAT takes care of the default
6251initialization of the additional Ada components of type DT (that is,
6252@cite{C_Value} is initialized to value 2009). The order of invocation of
6253the constructors is consistent with the order of elaboration required by
6254Ada and C++. That is, the constructor of the parent type is always called
6255before the constructor of the derived type.
6256
6257Let us now consider a record that has components whose type is imported
6258from C++. For example:
6259
6260@example
6261type Rec1 is limited record
6262   Data1 : Root := Constructor (10);
6263   Value : Natural := 1000;
6264end record;
6265
6266type Rec2 (D : Integer := 20) is limited record
6267   Rec   : Rec1;
6268   Data2 : Root := Constructor (D, 30);
6269end record;
6270@end example
6271
6272The initialization of an object of type @cite{Rec2} will call the
6273non-default C++ constructors specified for the imported components.
6274For example:
6275
6276@example
6277Obj8 : Rec2 (40);
6278@end example
6279
6280Using Ada 2005 we can use limited aggregates to initialize an object
6281invoking C++ constructors that differ from those specified in the type
6282declarations. For example:
6283
6284@example
6285Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
6286                        others => <>),
6287                others => <>);
6288@end example
6289
6290The above declaration uses an Ada 2005 limited aggregate to
6291initialize @cite{Obj9}, and the C++ constructor that has two integer
6292arguments is invoked to initialize the @cite{Data1} component instead
6293of the constructor specified in the declaration of type @cite{Rec1}. In
6294Ada 2005 the box in the aggregate indicates that unspecified components
6295are initialized using the expression (if any) available in the component
6296declaration. That is, in this case discriminant @cite{D} is initialized
6297to value @cite{20}, @cite{Value} is initialized to value 1000, and the
6298non-default C++ constructor that handles two integers takes care of
6299initializing component @cite{Data2} with values @cite{20@comma{}30}.
6300
6301In Ada 2005 we can use the extended return statement to build the Ada
6302equivalent to C++ non-default constructors. For example:
6303
6304@example
6305function Constructor (V : Integer) return Rec2 is
6306begin
6307   return Obj : Rec2 := (Rec => (Data1  => Constructor (V, 20),
6308                                 others => <>),
6309                         others => <>) do
6310      --  Further actions required for construction of
6311      --  objects of type Rec2
6312      ...
6313   end record;
6314end Constructor;
6315@end example
6316
6317In this example the extended return statement construct is used to
6318build in place the returned object whose components are initialized
6319by means of a limited aggregate. Any further action associated with
6320the constructor can be placed inside the construct.
6321
6322@node Interfacing with C++ at the Class Level,,Interfacing with C++ constructors,Building Mixed Ada and C++ Programs
6323@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}
6324@subsubsection Interfacing with C++ at the Class Level
6325
6326
6327In this section we demonstrate the GNAT features for interfacing with
6328C++ by means of an example making use of Ada 2005 abstract interface
6329types. This example consists of a classification of animals; classes
6330have been used to model our main classification of animals, and
6331interfaces provide support for the management of secondary
6332classifications. We first demonstrate a case in which the types and
6333constructors are defined on the C++ side and imported from the Ada
6334side, and latter the reverse case.
6335
6336The root of our derivation will be the @cite{Animal} class, with a
6337single private attribute (the @cite{Age} of the animal), a constructor,
6338and two public primitives to set and get the value of this attribute.
6339
6340@example
6341class Animal @{
6342 public:
6343   virtual void Set_Age (int New_Age);
6344   virtual int Age ();
6345   Animal() @{Age_Count = 0;@};
6346 private:
6347   int Age_Count;
6348@};
6349@end example
6350
6351Abstract interface types are defined in C++ by means of classes with pure
6352virtual functions and no data members. In our example we will use two
6353interfaces that provide support for the common management of @cite{Carnivore}
6354and @cite{Domestic} animals:
6355
6356@example
6357class Carnivore @{
6358public:
6359   virtual int Number_Of_Teeth () = 0;
6360@};
6361
6362class Domestic @{
6363public:
6364   virtual void Set_Owner (char* Name) = 0;
6365@};
6366@end example
6367
6368Using these declarations, we can now say that a @cite{Dog} is an animal that is
6369both Carnivore and Domestic, that is:
6370
6371@example
6372class Dog : Animal, Carnivore, Domestic @{
6373 public:
6374   virtual int  Number_Of_Teeth ();
6375   virtual void Set_Owner (char* Name);
6376
6377   Dog(); // Constructor
6378 private:
6379   int  Tooth_Count;
6380   char *Owner;
6381@};
6382@end example
6383
6384In the following examples we will assume that the previous declarations are
6385located in a file named @cite{animals.h}. The following package demonstrates
6386how to import these C++ declarations from the Ada side:
6387
6388@example
6389with Interfaces.C.Strings; use Interfaces.C.Strings;
6390package Animals is
6391  type Carnivore is limited interface;
6392  pragma Convention (C_Plus_Plus, Carnivore);
6393  function Number_Of_Teeth (X : Carnivore)
6394     return Natural is abstract;
6395
6396  type Domestic is limited interface;
6397  pragma Convention (C_Plus_Plus, Domestic);
6398  procedure Set_Owner
6399    (X    : in out Domestic;
6400     Name : Chars_Ptr) is abstract;
6401
6402  type Animal is tagged limited record
6403    Age : Natural;
6404  end record;
6405  pragma Import (C_Plus_Plus, Animal);
6406
6407  procedure Set_Age (X : in out Animal; Age : Integer);
6408  pragma Import (C_Plus_Plus, Set_Age);
6409
6410  function Age (X : Animal) return Integer;
6411  pragma Import (C_Plus_Plus, Age);
6412
6413  function New_Animal return Animal;
6414  pragma CPP_Constructor (New_Animal);
6415  pragma Import (CPP, New_Animal, "_ZN6AnimalC1Ev");
6416
6417  type Dog is new Animal and Carnivore and Domestic with record
6418    Tooth_Count : Natural;
6419    Owner       : String (1 .. 30);
6420  end record;
6421  pragma Import (C_Plus_Plus, Dog);
6422
6423  function Number_Of_Teeth (A : Dog) return Natural;
6424  pragma Import (C_Plus_Plus, Number_Of_Teeth);
6425
6426  procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
6427  pragma Import (C_Plus_Plus, Set_Owner);
6428
6429  function New_Dog return Dog;
6430  pragma CPP_Constructor (New_Dog);
6431  pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
6432end Animals;
6433@end example
6434
6435Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
6436interfacing with these C++ classes is easy. The only requirement is that all
6437the primitives and components must be declared exactly in the same order in
6438the two languages.
6439
6440Regarding the abstract interfaces, we must indicate to the GNAT compiler by
6441means of a @cite{pragma Convention (C_Plus_Plus)}, the convention used to pass
6442the arguments to the called primitives will be the same as for C++. For the
6443imported classes we use @cite{pragma Import} with convention @cite{C_Plus_Plus}
6444to indicate that they have been defined on the C++ side; this is required
6445because the dispatch table associated with these tagged types will be built
6446in the C++ side and therefore will not contain the predefined Ada primitives
6447which Ada would otherwise expect.
6448
6449As the reader can see there is no need to indicate the C++ mangled names
6450associated with each subprogram because it is assumed that all the calls to
6451these primitives will be dispatching calls. The only exception is the
6452constructor, which must be registered with the compiler by means of
6453@cite{pragma CPP_Constructor} and needs to provide its associated C++
6454mangled name because the Ada compiler generates direct calls to it.
6455
6456With the above packages we can now declare objects of type Dog on the Ada side
6457and dispatch calls to the corresponding subprograms on the C++ side. We can
6458also extend the tagged type Dog with further fields and primitives, and
6459override some of its C++ primitives on the Ada side. For example, here we have
6460a type derivation defined on the Ada side that inherits all the dispatching
6461primitives of the ancestor from the C++ side.
6462
6463@example
6464with Animals; use Animals;
6465package Vaccinated_Animals is
6466  type Vaccinated_Dog is new Dog with null record;
6467  function Vaccination_Expired (A : Vaccinated_Dog) return Boolean;
6468end Vaccinated_Animals;
6469@end example
6470
6471It is important to note that, because of the ABI compatibility, the programmer
6472does not need to add any further information to indicate either the object
6473layout or the dispatch table entry associated with each dispatching operation.
6474
6475Now let us define all the types and constructors on the Ada side and export
6476them to C++, using the same hierarchy of our previous example:
6477
6478@example
6479with Interfaces.C.Strings;
6480use Interfaces.C.Strings;
6481package Animals is
6482  type Carnivore is limited interface;
6483  pragma Convention (C_Plus_Plus, Carnivore);
6484  function Number_Of_Teeth (X : Carnivore)
6485     return Natural is abstract;
6486
6487  type Domestic is limited interface;
6488  pragma Convention (C_Plus_Plus, Domestic);
6489  procedure Set_Owner
6490    (X    : in out Domestic;
6491     Name : Chars_Ptr) is abstract;
6492
6493  type Animal is tagged record
6494    Age : Natural;
6495  end record;
6496  pragma Convention (C_Plus_Plus, Animal);
6497
6498  procedure Set_Age (X : in out Animal; Age : Integer);
6499  pragma Export (C_Plus_Plus, Set_Age);
6500
6501  function Age (X : Animal) return Integer;
6502  pragma Export (C_Plus_Plus, Age);
6503
6504  function New_Animal return Animal'Class;
6505  pragma Export (C_Plus_Plus, New_Animal);
6506
6507  type Dog is new Animal and Carnivore and Domestic with record
6508    Tooth_Count : Natural;
6509    Owner       : String (1 .. 30);
6510  end record;
6511  pragma Convention (C_Plus_Plus, Dog);
6512
6513  function Number_Of_Teeth (A : Dog) return Natural;
6514  pragma Export (C_Plus_Plus, Number_Of_Teeth);
6515
6516  procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
6517  pragma Export (C_Plus_Plus, Set_Owner);
6518
6519  function New_Dog return Dog'Class;
6520  pragma Export (C_Plus_Plus, New_Dog);
6521end Animals;
6522@end example
6523
6524Compared with our previous example the only differences are the use of
6525@cite{pragma Convention} (instead of @cite{pragma Import}), and the use of
6526@cite{pragma Export} to indicate to the GNAT compiler that the primitives will
6527be available to C++. Thanks to the ABI compatibility, on the C++ side there is
6528nothing else to be done; as explained above, the only requirement is that all
6529the primitives and components are declared in exactly the same order.
6530
6531For completeness, let us see a brief C++ main program that uses the
6532declarations available in @cite{animals.h} (presented in our first example) to
6533import and use the declarations from the Ada side, properly initializing and
6534finalizing the Ada run-time system along the way:
6535
6536@example
6537#include "animals.h"
6538#include <iostream>
6539using namespace std;
6540
6541void Check_Carnivore (Carnivore *obj) @{...@}
6542void Check_Domestic (Domestic *obj)   @{...@}
6543void Check_Animal (Animal *obj)       @{...@}
6544void Check_Dog (Dog *obj)             @{...@}
6545
6546extern "C" @{
6547  void adainit (void);
6548  void adafinal (void);
6549  Dog* new_dog ();
6550@}
6551
6552void test ()
6553@{
6554  Dog *obj = new_dog();  // Ada constructor
6555  Check_Carnivore (obj); // Check secondary DT
6556  Check_Domestic (obj);  // Check secondary DT
6557  Check_Animal (obj);    // Check primary DT
6558  Check_Dog (obj);       // Check primary DT
6559@}
6560
6561int main ()
6562@{
6563  adainit ();  test();  adafinal ();
6564  return 0;
6565@}
6566@end example
6567
6568@node Generating Ada Bindings for C and C++ headers,Generating C Headers for Ada Specifications,Building Mixed Ada and C++ Programs,Mixed Language Programming
6569@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}
6570@subsection Generating Ada Bindings for C and C++ headers
6571
6572
6573@geindex Binding generation (for C and C++ headers)
6574
6575@geindex C headers (binding generation)
6576
6577@geindex C++ headers (binding generation)
6578
6579GNAT includes a binding generator for C and C++ headers which is
6580intended to do 95% of the tedious work of generating Ada specs from C
6581or C++ header files.
6582
6583Note that this capability is not intended to generate 100% correct Ada specs,
6584and will is some cases require manual adjustments, although it can often
6585be used out of the box in practice.
6586
6587Some of the known limitations include:
6588
6589
6590@itemize *
6591
6592@item
6593only very simple character constant macros are translated into Ada
6594constants. Function macros (macros with arguments) are partially translated
6595as comments, to be completed manually if needed.
6596
6597@item
6598some extensions (e.g. vector types) are not supported
6599
6600@item
6601pointers to pointers or complex structures are mapped to System.Address
6602
6603@item
6604identifiers with identical name (except casing) will generate compilation
6605errors (e.g. @cite{shm_get} vs @cite{SHM_GET}).
6606@end itemize
6607
6608The code generated is using the Ada 2005 syntax, which makes it
6609easier to interface with other languages than previous versions of Ada.
6610
6611@menu
6612* Running the Binding Generator::
6613* Generating Bindings for C++ Headers::
6614* Switches::
6615
6616@end menu
6617
6618@node Running the Binding Generator,Generating Bindings for C++ Headers,,Generating Ada Bindings for C and C++ headers
6619@anchor{gnat_ugn/the_gnat_compilation_model id71}@anchor{ca}@anchor{gnat_ugn/the_gnat_compilation_model running-the-binding-generator}@anchor{cb}
6620@subsubsection Running the Binding Generator
6621
6622
6623The binding generator is part of the @emph{gcc} compiler and can be
6624invoked via the @emph{-fdump-ada-spec} switch, which will generate Ada
6625spec files for the header files specified on the command line, and all
6626header files needed by these files transitively. For example:
6627
6628@example
6629$ g++ -c -fdump-ada-spec -C /usr/include/time.h
6630$ gcc -c -gnat05 *.ads
6631@end example
6632
6633will generate, under GNU/Linux, the following files: @code{time_h.ads},
6634@code{bits_time_h.ads}, @code{stddef_h.ads}, @code{bits_types_h.ads} which
6635correspond to the files @code{/usr/include/time.h},
6636@code{/usr/include/bits/time.h}, etc..., and will then compile in Ada 2005
6637mode these Ada specs.
6638
6639The @cite{-C} switch tells @emph{gcc} to extract comments from headers,
6640and will attempt to generate corresponding Ada comments.
6641
6642If you want to generate a single Ada file and not the transitive closure, you
6643can use instead the @emph{-fdump-ada-spec-slim} switch.
6644
6645You can optionally specify a parent unit, of which all generated units will
6646be children, using @cite{-fada-spec-parent=<unit>}.
6647
6648Note that we recommend when possible to use the @emph{g++} driver to
6649generate bindings, even for most C headers, since this will in general
6650generate better Ada specs. For generating bindings for C++ headers, it is
6651mandatory to use the @emph{g++} command, or @emph{gcc -x c++} which
6652is equivalent in this case. If @emph{g++} cannot work on your C headers
6653because of incompatibilities between C and C++, then you can fallback to
6654@emph{gcc} instead.
6655
6656For an example of better bindings generated from the C++ front-end,
6657the name of the parameters (when available) are actually ignored by the C
6658front-end. Consider the following C header:
6659
6660@example
6661extern void foo (int variable);
6662@end example
6663
6664with the C front-end, @cite{variable} is ignored, and the above is handled as:
6665
6666@example
6667extern void foo (int);
6668@end example
6669
6670generating a generic:
6671
6672@example
6673procedure foo (param1 : int);
6674@end example
6675
6676with the C++ front-end, the name is available, and we generate:
6677
6678@example
6679procedure foo (variable : int);
6680@end example
6681
6682In some cases, the generated bindings will be more complete or more meaningful
6683when defining some macros, which you can do via the @emph{-D} switch. This
6684is for example the case with @code{Xlib.h} under GNU/Linux:
6685
6686@example
6687$ g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
6688@end example
6689
6690The above will generate more complete bindings than a straight call without
6691the @emph{-DXLIB_ILLEGAL_ACCESS} switch.
6692
6693In other cases, it is not possible to parse a header file in a stand-alone
6694manner, because other include files need to be included first. In this
6695case, the solution is to create a small header file including the needed
6696@cite{#include} and possible @cite{#define} directives. For example, to
6697generate Ada bindings for @code{readline/readline.h}, you need to first
6698include @code{stdio.h}, so you can create a file with the following two
6699lines in e.g. @code{readline1.h}:
6700
6701@example
6702#include <stdio.h>
6703#include <readline/readline.h>
6704@end example
6705
6706and then generate Ada bindings from this file:
6707
6708@example
6709$ g++ -c -fdump-ada-spec readline1.h
6710@end example
6711
6712@node Generating Bindings for C++ Headers,Switches,Running the Binding Generator,Generating Ada Bindings for C and C++ headers
6713@anchor{gnat_ugn/the_gnat_compilation_model id72}@anchor{cc}@anchor{gnat_ugn/the_gnat_compilation_model generating-bindings-for-c-headers}@anchor{cd}
6714@subsubsection Generating Bindings for C++ Headers
6715
6716
6717Generating bindings for C++ headers is done using the same options, always
6718with the @emph{g++} compiler. Note that generating Ada spec from C++ headers is a
6719much more complex job and support for C++ headers is much more limited that
6720support for C headers. As a result, you will need to modify the resulting
6721bindings by hand more extensively when using C++ headers.
6722
6723In this mode, C++ classes will be mapped to Ada tagged types, constructors
6724will be mapped using the @cite{CPP_Constructor} pragma, and when possible,
6725multiple inheritance of abstract classes will be mapped to Ada interfaces
6726(see the @emph{Interfacing to C++} section in the @cite{GNAT Reference Manual}
6727for additional information on interfacing to C++).
6728
6729For example, given the following C++ header file:
6730
6731@example
6732class Carnivore @{
6733public:
6734   virtual int Number_Of_Teeth () = 0;
6735@};
6736
6737class Domestic @{
6738public:
6739   virtual void Set_Owner (char* Name) = 0;
6740@};
6741
6742class Animal @{
6743public:
6744  int Age_Count;
6745  virtual void Set_Age (int New_Age);
6746@};
6747
6748class Dog : Animal, Carnivore, Domestic @{
6749 public:
6750  int  Tooth_Count;
6751  char *Owner;
6752
6753  virtual int  Number_Of_Teeth ();
6754  virtual void Set_Owner (char* Name);
6755
6756  Dog();
6757@};
6758@end example
6759
6760The corresponding Ada code is generated:
6761
6762@example
6763package Class_Carnivore is
6764  type Carnivore is limited interface;
6765  pragma Import (CPP, Carnivore);
6766
6767  function Number_Of_Teeth (this : access Carnivore) return int is abstract;
6768end;
6769use Class_Carnivore;
6770
6771package Class_Domestic is
6772  type Domestic is limited interface;
6773  pragma Import (CPP, Domestic);
6774
6775  procedure Set_Owner
6776    (this : access Domestic;
6777     Name : Interfaces.C.Strings.chars_ptr) is abstract;
6778end;
6779use Class_Domestic;
6780
6781package Class_Animal is
6782  type Animal is tagged limited record
6783    Age_Count : aliased int;
6784  end record;
6785  pragma Import (CPP, Animal);
6786
6787  procedure Set_Age (this : access Animal; New_Age : int);
6788  pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
6789end;
6790use Class_Animal;
6791
6792package Class_Dog is
6793  type Dog is new Animal and Carnivore and Domestic with record
6794    Tooth_Count : aliased int;
6795    Owner : Interfaces.C.Strings.chars_ptr;
6796  end record;
6797  pragma Import (CPP, Dog);
6798
6799  function Number_Of_Teeth (this : access Dog) return int;
6800  pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
6801
6802  procedure Set_Owner
6803    (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
6804  pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
6805
6806  function New_Dog return Dog;
6807  pragma CPP_Constructor (New_Dog);
6808  pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
6809end;
6810use Class_Dog;
6811@end example
6812
6813@node Switches,,Generating Bindings for C++ Headers,Generating Ada Bindings for C and C++ headers
6814@anchor{gnat_ugn/the_gnat_compilation_model switches}@anchor{ce}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-ada-binding-generation}@anchor{cf}
6815@subsubsection Switches
6816
6817
6818@geindex -fdump-ada-spec (gcc)
6819
6820
6821@table @asis
6822
6823@item @code{-fdump-ada-spec}
6824
6825Generate Ada spec files for the given header files transitively (including
6826all header files that these headers depend upon).
6827@end table
6828
6829@geindex -fdump-ada-spec-slim (gcc)
6830
6831
6832@table @asis
6833
6834@item @code{-fdump-ada-spec-slim}
6835
6836Generate Ada spec files for the header files specified on the command line
6837only.
6838@end table
6839
6840@geindex -fada-spec-parent (gcc)
6841
6842
6843@table @asis
6844
6845@item @code{-fada-spec-parent=@emph{unit}}
6846
6847Specifies that all files generated by @emph{-fdump-ada-spec*} are
6848to be child units of the specified parent unit.
6849@end table
6850
6851@geindex -C (gcc)
6852
6853
6854@table @asis
6855
6856@item @code{-C}
6857
6858Extract comments from headers and generate Ada comments in the Ada spec files.
6859@end table
6860
6861@node Generating C Headers for Ada Specifications,,Generating Ada Bindings for C and C++ headers,Mixed Language Programming
6862@anchor{gnat_ugn/the_gnat_compilation_model generating-c-headers-for-ada-specifications}@anchor{d0}@anchor{gnat_ugn/the_gnat_compilation_model id73}@anchor{d1}
6863@subsection Generating C Headers for Ada Specifications
6864
6865
6866@geindex Binding generation (for Ada specs)
6867
6868@geindex C headers (binding generation)
6869
6870GNAT includes a C header generator for Ada specifications which supports
6871Ada types that have a direct mapping to C types. This includes in particular
6872support for:
6873
6874
6875@itemize *
6876
6877@item
6878Scalar types
6879
6880@item
6881Constrained arrays
6882
6883@item
6884Records (untagged)
6885
6886@item
6887Composition of the above types
6888
6889@item
6890Constant declarations
6891
6892@item
6893Object declarations
6894
6895@item
6896Subprogram declarations
6897@end itemize
6898
6899@menu
6900* Running the C Header Generator::
6901
6902@end menu
6903
6904@node Running the C Header Generator,,,Generating C Headers for Ada Specifications
6905@anchor{gnat_ugn/the_gnat_compilation_model running-the-c-header-generator}@anchor{d2}
6906@subsubsection Running the C Header Generator
6907
6908
6909The C header generator is part of the GNAT compiler and can be invoked via
6910the @emph{-gnatceg} combination of switches, which will generate a @code{.h}
6911file corresponding to the given input file (Ada spec or body). Note that
6912only spec files are processed in any case, so giving a spec or a body file
6913as input is equivalent. For example:
6914
6915@example
6916$ gcc -c -gnatceg pack1.ads
6917@end example
6918
6919will generate a self-contained file called @code{pack1.h} including
6920common definitions from the Ada Standard package, followed by the
6921definitions included in @code{pack1.ads}, as well as all the other units
6922withed by this file.
6923
6924For instance, given the following Ada files:
6925
6926@example
6927package Pack2 is
6928   type Int is range 1 .. 10;
6929end Pack2;
6930@end example
6931
6932@example
6933with Pack2;
6934
6935package Pack1 is
6936   type Rec is record
6937      Field1, Field2 : Pack2.Int;
6938   end record;
6939
6940   Global : Rec := (1, 2);
6941
6942   procedure Proc1 (R : Rec);
6943   procedure Proc2 (R : in out Rec);
6944end Pack1;
6945@end example
6946
6947The above @cite{gcc} command will generate the following @code{pack1.h} file:
6948
6949@example
6950/* Standard definitions skipped */
6951#ifndef PACK2_ADS
6952#define PACK2_ADS
6953typedef short_short_integer pack2__TintB;
6954typedef pack2__TintB pack2__int;
6955#endif /* PACK2_ADS */
6956
6957#ifndef PACK1_ADS
6958#define PACK1_ADS
6959typedef struct _pack1__rec @{
6960  pack2__int field1;
6961  pack2__int field2;
6962@} pack1__rec;
6963extern pack1__rec pack1__global;
6964extern void pack1__proc1(const pack1__rec r);
6965extern void pack1__proc2(pack1__rec *r);
6966#endif /* PACK1_ADS */
6967@end example
6968
6969You can then @cite{include} @code{pack1.h} from a C source file and use the types,
6970call subprograms, reference objects, and constants.
6971
6972@node GNAT and Other Compilation Models,Using GNAT Files with External Tools,Mixed Language Programming,The GNAT Compilation Model
6973@anchor{gnat_ugn/the_gnat_compilation_model id74}@anchor{d3}@anchor{gnat_ugn/the_gnat_compilation_model gnat-and-other-compilation-models}@anchor{47}
6974@section GNAT and Other Compilation Models
6975
6976
6977This section compares the GNAT model with the approaches taken in
6978other environents, first the C/C++ model and then the mechanism that
6979has been used in other Ada systems, in particular those traditionally
6980used for Ada 83.
6981
6982@menu
6983* Comparison between GNAT and C/C++ Compilation Models::
6984* Comparison between GNAT and Conventional Ada Library Models::
6985
6986@end menu
6987
6988@node Comparison between GNAT and C/C++ Compilation Models,Comparison between GNAT and Conventional Ada Library Models,,GNAT and Other Compilation Models
6989@anchor{gnat_ugn/the_gnat_compilation_model comparison-between-gnat-and-c-c-compilation-models}@anchor{d4}@anchor{gnat_ugn/the_gnat_compilation_model id75}@anchor{d5}
6990@subsection Comparison between GNAT and C/C++ Compilation Models
6991
6992
6993The GNAT model of compilation is close to the C and C++ models. You can
6994think of Ada specs as corresponding to header files in C. As in C, you
6995don't need to compile specs; they are compiled when they are used. The
6996Ada @emph{with} is similar in effect to the @cite{#include} of a C
6997header.
6998
6999One notable difference is that, in Ada, you may compile specs separately
7000to check them for semantic and syntactic accuracy. This is not always
7001possible with C headers because they are fragments of programs that have
7002less specific syntactic or semantic rules.
7003
7004The other major difference is the requirement for running the binder,
7005which performs two important functions. First, it checks for
7006consistency. In C or C++, the only defense against assembling
7007inconsistent programs lies outside the compiler, in a makefile, for
7008example. The binder satisfies the Ada requirement that it be impossible
7009to construct an inconsistent program when the compiler is used in normal
7010mode.
7011
7012@geindex Elaboration order control
7013
7014The other important function of the binder is to deal with elaboration
7015issues. There are also elaboration issues in C++ that are handled
7016automatically. This automatic handling has the advantage of being
7017simpler to use, but the C++ programmer has no control over elaboration.
7018Where @cite{gnatbind} might complain there was no valid order of
7019elaboration, a C++ compiler would simply construct a program that
7020malfunctioned at run time.
7021
7022@node Comparison between GNAT and Conventional Ada Library Models,,Comparison between GNAT and C/C++ Compilation Models,GNAT and Other Compilation Models
7023@anchor{gnat_ugn/the_gnat_compilation_model comparison-between-gnat-and-conventional-ada-library-models}@anchor{d6}@anchor{gnat_ugn/the_gnat_compilation_model id76}@anchor{d7}
7024@subsection Comparison between GNAT and Conventional Ada Library Models
7025
7026
7027This section is intended for Ada programmers who have
7028used an Ada compiler implementing the traditional Ada library
7029model, as described in the Ada Reference Manual.
7030
7031@geindex GNAT library
7032
7033In GNAT, there is no 'library' in the normal sense. Instead, the set of
7034source files themselves acts as the library. Compiling Ada programs does
7035not generate any centralized information, but rather an object file and
7036a ALI file, which are of interest only to the binder and linker.
7037In a traditional system, the compiler reads information not only from
7038the source file being compiled, but also from the centralized library.
7039This means that the effect of a compilation depends on what has been
7040previously compiled. In particular:
7041
7042
7043@itemize *
7044
7045@item
7046When a unit is @emph{with}ed, the unit seen by the compiler corresponds
7047to the version of the unit most recently compiled into the library.
7048
7049@item
7050Inlining is effective only if the necessary body has already been
7051compiled into the library.
7052
7053@item
7054Compiling a unit may obsolete other units in the library.
7055@end itemize
7056
7057In GNAT, compiling one unit never affects the compilation of any other
7058units because the compiler reads only source files. Only changes to source
7059files can affect the results of a compilation. In particular:
7060
7061
7062@itemize *
7063
7064@item
7065When a unit is @emph{with}ed, the unit seen by the compiler corresponds
7066to the source version of the unit that is currently accessible to the
7067compiler.
7068
7069@geindex Inlining
7070
7071@item
7072Inlining requires the appropriate source files for the package or
7073subprogram bodies to be available to the compiler. Inlining is always
7074effective, independent of the order in which units are compiled.
7075
7076@item
7077Compiling a unit never affects any other compilations. The editing of
7078sources may cause previous compilations to be out of date if they
7079depended on the source file being modified.
7080@end itemize
7081
7082The most important result of these differences is that order of compilation
7083is never significant in GNAT. There is no situation in which one is
7084required to do one compilation before another. What shows up as order of
7085compilation requirements in the traditional Ada library becomes, in
7086GNAT, simple source dependencies; in other words, there is only a set
7087of rules saying what source files must be present when a file is
7088compiled.
7089
7090@node Using GNAT Files with External Tools,,GNAT and Other Compilation Models,The GNAT Compilation Model
7091@anchor{gnat_ugn/the_gnat_compilation_model using-gnat-files-with-external-tools}@anchor{1c}@anchor{gnat_ugn/the_gnat_compilation_model id77}@anchor{d8}
7092@section Using GNAT Files with External Tools
7093
7094
7095This section explains how files that are produced by GNAT may be
7096used with tools designed for other languages.
7097
7098@menu
7099* Using Other Utility Programs with GNAT::
7100* The External Symbol Naming Scheme of GNAT::
7101
7102@end menu
7103
7104@node Using Other Utility Programs with GNAT,The External Symbol Naming Scheme of GNAT,,Using GNAT Files with External Tools
7105@anchor{gnat_ugn/the_gnat_compilation_model using-other-utility-programs-with-gnat}@anchor{d9}@anchor{gnat_ugn/the_gnat_compilation_model id78}@anchor{da}
7106@subsection Using Other Utility Programs with GNAT
7107
7108
7109The object files generated by GNAT are in standard system format and in
7110particular the debugging information uses this format. This means
7111programs generated by GNAT can be used with existing utilities that
7112depend on these formats.
7113
7114In general, any utility program that works with C will also often work with
7115Ada programs generated by GNAT. This includes software utilities such as
7116gprof (a profiling program), gdb (the FSF debugger), and utilities such
7117as Purify.
7118
7119@node The External Symbol Naming Scheme of GNAT,,Using Other Utility Programs with GNAT,Using GNAT Files with External Tools
7120@anchor{gnat_ugn/the_gnat_compilation_model the-external-symbol-naming-scheme-of-gnat}@anchor{db}@anchor{gnat_ugn/the_gnat_compilation_model id79}@anchor{dc}
7121@subsection The External Symbol Naming Scheme of GNAT
7122
7123
7124In order to interpret the output from GNAT, when using tools that are
7125originally intended for use with other languages, it is useful to
7126understand the conventions used to generate link names from the Ada
7127entity names.
7128
7129All link names are in all lowercase letters. With the exception of library
7130procedure names, the mechanism used is simply to use the full expanded
7131Ada name with dots replaced by double underscores. For example, suppose
7132we have the following package spec:
7133
7134@example
7135package QRS is
7136   MN : Integer;
7137end QRS;
7138@end example
7139
7140@geindex pragma Export
7141
7142The variable @cite{MN} has a full expanded Ada name of @cite{QRS.MN}, so
7143the corresponding link name is @cite{qrs__mn}.
7144Of course if a @cite{pragma Export} is used this may be overridden:
7145
7146@example
7147package Exports is
7148   Var1 : Integer;
7149   pragma Export (Var1, C, External_Name => "var1_name");
7150   Var2 : Integer;
7151   pragma Export (Var2, C, Link_Name => "var2_link_name");
7152end Exports;
7153@end example
7154
7155In this case, the link name for @cite{Var1} is whatever link name the
7156C compiler would assign for the C function @cite{var1_name}. This typically
7157would be either @cite{var1_name} or @cite{_var1_name}, depending on operating
7158system conventions, but other possibilities exist. The link name for
7159@cite{Var2} is @cite{var2_link_name}, and this is not operating system
7160dependent.
7161
7162One exception occurs for library level procedures. A potential ambiguity
7163arises between the required name @cite{_main} for the C main program,
7164and the name we would otherwise assign to an Ada library level procedure
7165called @cite{Main} (which might well not be the main program).
7166
7167To avoid this ambiguity, we attach the prefix @cite{_ada_} to such
7168names. So if we have a library level procedure such as:
7169
7170@example
7171procedure Hello (S : String);
7172@end example
7173
7174the external name of this procedure will be @cite{_ada_hello}.
7175
7176@c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
7177
7178@node Building Executable Programs with GNAT,GNAT Project Manager,The GNAT Compilation Model,Top
7179@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{dd}@anchor{gnat_ugn/building_executable_programs_with_gnat id1}@anchor{de}
7180@chapter Building Executable Programs with GNAT
7181
7182
7183This chapter describes first the gnatmake tool
7184(@ref{1d,,Building with gnatmake}),
7185which automatically determines the set of sources
7186needed by an Ada compilation unit and executes the necessary
7187(re)compilations, binding and linking.
7188It also explains how to use each tool individually: the
7189compiler (gcc, see @ref{1e,,Compiling with gcc}),
7190binder (gnatbind, see @ref{1f,,Binding with gnatbind}),
7191and linker (gnatlink, see @ref{20,,Linking with gnatlink})
7192to build executable programs.
7193Finally, this chapter provides examples of
7194how to make use of the general GNU make mechanism
7195in a GNAT context (see @ref{21,,Using the GNU make Utility}).
7196
7197@menu
7198* Building with gnatmake::
7199* Compiling with gcc::
7200* Compiler Switches::
7201* Binding with gnatbind::
7202* Linking with gnatlink::
7203* Using the GNU make Utility::
7204
7205@end menu
7206
7207@node Building with gnatmake,Compiling with gcc,,Building Executable Programs with GNAT
7208@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{df}
7209@section Building with @emph{gnatmake}
7210
7211
7212@geindex gnatmake
7213
7214A typical development cycle when working on an Ada program consists of
7215the following steps:
7216
7217
7218@enumerate
7219
7220@item
7221Edit some sources to fix bugs;
7222
7223@item
7224Add enhancements;
7225
7226@item
7227Compile all sources affected;
7228
7229@item
7230Rebind and relink; and
7231
7232@item
7233Test.
7234@end enumerate
7235
7236@geindex Dependency rules (compilation)
7237
7238The third step in particular can be tricky, because not only do the modified
7239files have to be compiled, but any files depending on these files must also be
7240recompiled. The dependency rules in Ada can be quite complex, especially
7241in the presence of overloading, @cite{use} clauses, generics and inlined
7242subprograms.
7243
7244@emph{gnatmake} automatically takes care of the third and fourth steps
7245of this process. It determines which sources need to be compiled,
7246compiles them, and binds and links the resulting object files.
7247
7248Unlike some other Ada make programs, the dependencies are always
7249accurately recomputed from the new sources. The source based approach of
7250the GNAT compilation model makes this possible. This means that if
7251changes to the source program cause corresponding changes in
7252dependencies, they will always be tracked exactly correctly by
7253@emph{gnatmake}.
7254
7255Note that for advanced description of project structure, we recommend creating
7256a project file as explained in @ref{b,,GNAT Project Manager} and use the
7257@emph{gprbuild} tool which supports building with project files and works similarly
7258to @emph{gnatmake}.
7259
7260@menu
7261* Running gnatmake::
7262* Switches for gnatmake::
7263* Mode Switches for gnatmake::
7264* Notes on the Command Line::
7265* How gnatmake Works::
7266* Examples of gnatmake Usage::
7267
7268@end menu
7269
7270@node Running gnatmake,Switches for gnatmake,,Building with gnatmake
7271@anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatmake}@anchor{e0}@anchor{gnat_ugn/building_executable_programs_with_gnat id2}@anchor{e1}
7272@subsection Running @emph{gnatmake}
7273
7274
7275The usual form of the @emph{gnatmake} command is
7276
7277@example
7278$ gnatmake [<switches>] <file_name> [<file_names>] [<mode_switches>]
7279@end example
7280
7281The only required argument is one @cite{file_name}, which specifies
7282a compilation unit that is a main program. Several @cite{file_names} can be
7283specified: this will result in several executables being built.
7284If @cite{switches} are present, they can be placed before the first
7285@cite{file_name}, between @cite{file_names} or after the last @cite{file_name}.
7286If @cite{mode_switches} are present, they must always be placed after
7287the last @cite{file_name} and all @cite{switches}.
7288
7289If you are using standard file extensions (@code{.adb} and
7290@code{.ads}), then the
7291extension may be omitted from the @cite{file_name} arguments. However, if
7292you are using non-standard extensions, then it is required that the
7293extension be given. A relative or absolute directory path can be
7294specified in a @cite{file_name}, in which case, the input source file will
7295be searched for in the specified directory only. Otherwise, the input
7296source file will first be searched in the directory where
7297@emph{gnatmake} was invoked and if it is not found, it will be search on
7298the source path of the compiler as described in
7299@ref{8e,,Search Paths and the Run-Time Library (RTL)}.
7300
7301All @emph{gnatmake} output (except when you specify @emph{-M}) is sent to
7302@code{stderr}. The output produced by the
7303@emph{-M} switch is sent to @code{stdout}.
7304
7305@node Switches for gnatmake,Mode Switches for gnatmake,Running gnatmake,Building with gnatmake
7306@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatmake}@anchor{e2}@anchor{gnat_ugn/building_executable_programs_with_gnat id3}@anchor{e3}
7307@subsection Switches for @emph{gnatmake}
7308
7309
7310You may specify any of the following switches to @emph{gnatmake}:
7311
7312@geindex --version (gnatmake)
7313
7314
7315@table @asis
7316
7317@item @code{--version}
7318
7319Display Copyright and version, then exit disregarding all other options.
7320@end table
7321
7322@geindex --help (gnatmake)
7323
7324
7325@table @asis
7326
7327@item @code{--help}
7328
7329If @code{--version} was not used, display usage, then exit disregarding
7330all other options.
7331@end table
7332
7333@geindex --GCC=compiler_name (gnatmake)
7334
7335
7336@table @asis
7337
7338@item @code{--GCC=@emph{compiler_name}}
7339
7340Program used for compiling. The default is @code{gcc}. You need to use
7341quotes around @cite{compiler_name} if @cite{compiler_name} contains
7342spaces or other separator characters.
7343As an example @code{--GCC="foo -x  -y"}
7344will instruct @emph{gnatmake} to use @code{foo -x -y} as your
7345compiler. A limitation of this syntax is that the name and path name of
7346the executable itself must not include any embedded spaces. Note that
7347switch @code{-c} is always inserted after your command name. Thus in the
7348above example the compiler command that will be used by @emph{gnatmake}
7349will be @code{foo -c -x -y}. If several @code{--GCC=compiler_name} are
7350used, only the last @cite{compiler_name} is taken into account. However,
7351all the additional switches are also taken into account. Thus,
7352@code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
7353@code{--GCC="bar -x -y -z -t"}.
7354@end table
7355
7356@geindex --GNATBIND=binder_name (gnatmake)
7357
7358
7359@table @asis
7360
7361@item @code{--GNATBIND=@emph{binder_name}}
7362
7363Program used for binding. The default is @code{gnatbind}. You need to
7364use quotes around @cite{binder_name} if @cite{binder_name} contains spaces
7365or other separator characters.
7366As an example @code{--GNATBIND="bar -x  -y"}
7367will instruct @emph{gnatmake} to use @cite{bar -x -y} as your
7368binder. Binder switches that are normally appended by @emph{gnatmake}
7369to @code{gnatbind} are now appended to the end of @cite{bar -x -y}.
7370A limitation of this syntax is that the name and path name of the executable
7371itself must not include any embedded spaces.
7372@end table
7373
7374@geindex --GNATLINK=linker_name (gnatmake)
7375
7376
7377@table @asis
7378
7379@item @code{--GNATLINK=@emph{linker_name}}
7380
7381Program used for linking. The default is @code{gnatlink}. You need to
7382use quotes around @cite{linker_name} if @cite{linker_name} contains spaces
7383or other separator characters.
7384As an example @code{--GNATLINK="lan -x  -y"}
7385will instruct @emph{gnatmake} to use @code{lan -x -y} as your
7386linker. Linker switches that are normally appended by @code{gnatmake} to
7387@code{gnatlink} are now appended to the end of @code{lan -x -y}.
7388A limitation of this syntax is that the name and path name of the executable
7389itself must not include any embedded spaces.
7390
7391@item @code{--create-map-file}
7392
7393When linking an executable, create a map file. The name of the map file
7394has the same name as the executable with extension ".map".
7395
7396@item @code{--create-map-file=@emph{mapfile}}
7397
7398When linking an executable, create a map file with the specified name.
7399@end table
7400
7401@geindex --create-missing-dirs (gnatmake)
7402
7403
7404@table @asis
7405
7406@item @code{--create-missing-dirs}
7407
7408When using project files (@code{-P@emph{project}}), automatically create
7409missing object directories, library directories and exec
7410directories.
7411
7412@item @code{--single-compile-per-obj-dir}
7413
7414Disallow simultaneous compilations in the same object directory when
7415project files are used.
7416
7417@item @code{--subdirs=@emph{subdir}}
7418
7419Actual object directory of each project file is the subdirectory subdir of the
7420object directory specified or defaulted in the project file.
7421
7422@item @code{--unchecked-shared-lib-imports}
7423
7424By default, shared library projects are not allowed to import static library
7425projects. When this switch is used on the command line, this restriction is
7426relaxed.
7427
7428@item @code{--source-info=@emph{source info file}}
7429
7430Specify a source info file. This switch is active only when project files
7431are used. If the source info file is specified as a relative path, then it is
7432relative to the object directory of the main project. If the source info file
7433does not exist, then after the Project Manager has successfully parsed and
7434processed the project files and found the sources, it creates the source info
7435file. If the source info file already exists and can be read successfully,
7436then the Project Manager will get all the needed information about the sources
7437from the source info file and will not look for them. This reduces the time
7438to process the project files, especially when looking for sources that take a
7439long time. If the source info file exists but cannot be parsed successfully,
7440the Project Manager will attempt to recreate it. If the Project Manager fails
7441to create the source info file, a message is issued, but gnatmake does not
7442fail. @emph{gnatmake} "trusts" the source info file. This means that
7443if the source files have changed (addition, deletion, moving to a different
7444source directory), then the source info file need to be deleted and recreated.
7445@end table
7446
7447@geindex -a (gnatmake)
7448
7449
7450@table @asis
7451
7452@item @code{-a}
7453
7454Consider all files in the make process, even the GNAT internal system
7455files (for example, the predefined Ada library files), as well as any
7456locked files. Locked files are files whose ALI file is write-protected.
7457By default,
7458@emph{gnatmake} does not check these files,
7459because the assumption is that the GNAT internal files are properly up
7460to date, and also that any write protected ALI files have been properly
7461installed. Note that if there is an installation problem, such that one
7462of these files is not up to date, it will be properly caught by the
7463binder.
7464You may have to specify this switch if you are working on GNAT
7465itself. The switch @code{-a} is also useful
7466in conjunction with @code{-f}
7467if you need to recompile an entire application,
7468including run-time files, using special configuration pragmas,
7469such as a @cite{Normalize_Scalars} pragma.
7470
7471By default
7472@code{gnatmake -a} compiles all GNAT
7473internal files with
7474@code{gcc -c -gnatpg} rather than @code{gcc -c}.
7475@end table
7476
7477@geindex -b (gnatmake)
7478
7479
7480@table @asis
7481
7482@item @code{-b}
7483
7484Bind only. Can be combined with @emph{-c} to do
7485compilation and binding, but no link.
7486Can be combined with @emph{-l}
7487to do binding and linking. When not combined with
7488@emph{-c}
7489all the units in the closure of the main program must have been previously
7490compiled and must be up to date. The root unit specified by @cite{file_name}
7491may be given without extension, with the source extension or, if no GNAT
7492Project File is specified, with the ALI file extension.
7493@end table
7494
7495@geindex -c (gnatmake)
7496
7497
7498@table @asis
7499
7500@item @code{-c}
7501
7502Compile only. Do not perform binding, except when @emph{-b}
7503is also specified. Do not perform linking, except if both
7504@emph{-b} and
7505@emph{-l} are also specified.
7506If the root unit specified by @cite{file_name} is not a main unit, this is the
7507default. Otherwise @emph{gnatmake} will attempt binding and linking
7508unless all objects are up to date and the executable is more recent than
7509the objects.
7510@end table
7511
7512@geindex -C (gnatmake)
7513
7514
7515@table @asis
7516
7517@item @code{-C}
7518
7519Use a temporary mapping file. A mapping file is a way to communicate
7520to the compiler two mappings: from unit names to file names (without
7521any directory information) and from file names to path names (with
7522full directory information). A mapping file can make the compiler's
7523file searches faster, especially if there are many source directories,
7524or the sources are read over a slow network connection. If
7525@emph{-P} is used, a mapping file is always used, so
7526@emph{-C} is unnecessary; in this case the mapping file
7527is initially populated based on the project file. If
7528@emph{-C} is used without
7529@emph{-P},
7530the mapping file is initially empty. Each invocation of the compiler
7531will add any newly accessed sources to the mapping file.
7532@end table
7533
7534@geindex -C= (gnatmake)
7535
7536
7537@table @asis
7538
7539@item @code{-C=@emph{file}}
7540
7541Use a specific mapping file. The file, specified as a path name (absolute or
7542relative) by this switch, should already exist, otherwise the switch is
7543ineffective. The specified mapping file will be communicated to the compiler.
7544This switch is not compatible with a project file
7545(-P`file`) or with multiple compiling processes
7546(-jnnn, when nnn is greater than 1).
7547@end table
7548
7549@geindex -d (gnatmake)
7550
7551
7552@table @asis
7553
7554@item @code{-d}
7555
7556Display progress for each source, up to date or not, as a single line:
7557
7558@example
7559completed x out of y (zz%)
7560@end example
7561
7562If the file needs to be compiled this is displayed after the invocation of
7563the compiler. These lines are displayed even in quiet output mode.
7564@end table
7565
7566@geindex -D (gnatmake)
7567
7568
7569@table @asis
7570
7571@item @code{-D @emph{dir}}
7572
7573Put all object files and ALI file in directory @cite{dir}.
7574If the @emph{-D} switch is not used, all object files
7575and ALI files go in the current working directory.
7576
7577This switch cannot be used when using a project file.
7578@end table
7579
7580@geindex -eI (gnatmake)
7581
7582
7583@table @asis
7584
7585@item @code{-eI@emph{nnn}}
7586
7587Indicates that the main source is a multi-unit source and the rank of the unit
7588in the source file is nnn. nnn needs to be a positive number and a valid
7589index in the source. This switch cannot be used when @emph{gnatmake} is
7590invoked for several mains.
7591@end table
7592
7593@geindex -eL (gnatmake)
7594
7595@geindex symbolic links
7596
7597
7598@table @asis
7599
7600@item @code{-eL}
7601
7602Follow all symbolic links when processing project files.
7603This should be used if your project uses symbolic links for files or
7604directories, but is not needed in other cases.
7605
7606@geindex naming scheme
7607
7608This also assumes that no directory matches the naming scheme for files (for
7609instance that you do not have a directory called "sources.ads" when using the
7610default GNAT naming scheme).
7611
7612When you do not have to use this switch (i.e., by default), gnatmake is able to
7613save a lot of system calls (several per source file and object file), which
7614can result in a significant speed up to load and manipulate a project file,
7615especially when using source files from a remote system.
7616@end table
7617
7618@geindex -eS (gnatmake)
7619
7620
7621@table @asis
7622
7623@item @code{-eS}
7624
7625Output the commands for the compiler, the binder and the linker
7626on standard output,
7627instead of standard error.
7628@end table
7629
7630@geindex -f (gnatmake)
7631
7632
7633@table @asis
7634
7635@item @code{-f}
7636
7637Force recompilations. Recompile all sources, even though some object
7638files may be up to date, but don't recompile predefined or GNAT internal
7639files or locked files (files with a write-protected ALI file),
7640unless the @emph{-a} switch is also specified.
7641@end table
7642
7643@geindex -F (gnatmake)
7644
7645
7646@table @asis
7647
7648@item @code{-F}
7649
7650When using project files, if some errors or warnings are detected during
7651parsing and verbose mode is not in effect (no use of switch
7652-v), then error lines start with the full path name of the project
7653file, rather than its simple file name.
7654@end table
7655
7656@geindex -g (gnatmake)
7657
7658
7659@table @asis
7660
7661@item @code{-g}
7662
7663Enable debugging. This switch is simply passed to the compiler and to the
7664linker.
7665@end table
7666
7667@geindex -i (gnatmake)
7668
7669
7670@table @asis
7671
7672@item @code{-i}
7673
7674In normal mode, @emph{gnatmake} compiles all object files and ALI files
7675into the current directory. If the @emph{-i} switch is used,
7676then instead object files and ALI files that already exist are overwritten
7677in place. This means that once a large project is organized into separate
7678directories in the desired manner, then @emph{gnatmake} will automatically
7679maintain and update this organization. If no ALI files are found on the
7680Ada object path (see @ref{8e,,Search Paths and the Run-Time Library (RTL)}),
7681the new object and ALI files are created in the
7682directory containing the source being compiled. If another organization
7683is desired, where objects and sources are kept in different directories,
7684a useful technique is to create dummy ALI files in the desired directories.
7685When detecting such a dummy file, @emph{gnatmake} will be forced to
7686recompile the corresponding source file, and it will be put the resulting
7687object and ALI files in the directory where it found the dummy file.
7688@end table
7689
7690@geindex -j (gnatmake)
7691
7692@geindex Parallel make
7693
7694
7695@table @asis
7696
7697@item @code{-j@emph{n}}
7698
7699Use @cite{n} processes to carry out the (re)compilations. On a multiprocessor
7700machine compilations will occur in parallel. If @cite{n} is 0, then the
7701maximum number of parallel compilations is the number of core processors
7702on the platform. In the event of compilation errors, messages from various
7703compilations might get interspersed (but @emph{gnatmake} will give you the
7704full ordered list of failing compiles at the end). If this is problematic,
7705rerun the make process with n set to 1 to get a clean list of messages.
7706@end table
7707
7708@geindex -k (gnatmake)
7709
7710
7711@table @asis
7712
7713@item @code{-k}
7714
7715Keep going. Continue as much as possible after a compilation error. To
7716ease the programmer's task in case of compilation errors, the list of
7717sources for which the compile fails is given when @emph{gnatmake}
7718terminates.
7719
7720If @emph{gnatmake} is invoked with several @code{file_names} and with this
7721switch, if there are compilation errors when building an executable,
7722@emph{gnatmake} will not attempt to build the following executables.
7723@end table
7724
7725@geindex -l (gnatmake)
7726
7727
7728@table @asis
7729
7730@item @code{-l}
7731
7732Link only. Can be combined with @emph{-b} to binding
7733and linking. Linking will not be performed if combined with
7734@emph{-c}
7735but not with @emph{-b}.
7736When not combined with @emph{-b}
7737all the units in the closure of the main program must have been previously
7738compiled and must be up to date, and the main program needs to have been bound.
7739The root unit specified by @cite{file_name}
7740may be given without extension, with the source extension or, if no GNAT
7741Project File is specified, with the ALI file extension.
7742@end table
7743
7744@geindex -m (gnatmake)
7745
7746
7747@table @asis
7748
7749@item @code{-m}
7750
7751Specify that the minimum necessary amount of recompilations
7752be performed. In this mode @emph{gnatmake} ignores time
7753stamp differences when the only
7754modifications to a source file consist in adding/removing comments,
7755empty lines, spaces or tabs. This means that if you have changed the
7756comments in a source file or have simply reformatted it, using this
7757switch will tell @emph{gnatmake} not to recompile files that depend on it
7758(provided other sources on which these files depend have undergone no
7759semantic modifications). Note that the debugging information may be
7760out of date with respect to the sources if the @emph{-m} switch causes
7761a compilation to be switched, so the use of this switch represents a
7762trade-off between compilation time and accurate debugging information.
7763@end table
7764
7765@geindex Dependencies
7766@geindex producing list
7767
7768@geindex -M (gnatmake)
7769
7770
7771@table @asis
7772
7773@item @code{-M}
7774
7775Check if all objects are up to date. If they are, output the object
7776dependences to @code{stdout} in a form that can be directly exploited in
7777a @code{Makefile}. By default, each source file is prefixed with its
7778(relative or absolute) directory name. This name is whatever you
7779specified in the various @emph{-aI}
7780and @emph{-I} switches. If you use
7781@cite{gnatmake -M}  @emph{-q}
7782(see below), only the source file names,
7783without relative paths, are output. If you just specify the  @emph{-M}
7784switch, dependencies of the GNAT internal system files are omitted. This
7785is typically what you want. If you also specify
7786the @emph{-a} switch,
7787dependencies of the GNAT internal files are also listed. Note that
7788dependencies of the objects in external Ada libraries (see
7789switch  @code{-aL@emph{dir}} in the following list)
7790are never reported.
7791@end table
7792
7793@geindex -n (gnatmake)
7794
7795
7796@table @asis
7797
7798@item @code{-n}
7799
7800Don't compile, bind, or link. Checks if all objects are up to date.
7801If they are not, the full name of the first file that needs to be
7802recompiled is printed.
7803Repeated use of this option, followed by compiling the indicated source
7804file, will eventually result in recompiling all required units.
7805@end table
7806
7807@geindex -o (gnatmake)
7808
7809
7810@table @asis
7811
7812@item @code{-o @emph{exec_name}}
7813
7814Output executable name. The name of the final executable program will be
7815@cite{exec_name}. If the @emph{-o} switch is omitted the default
7816name for the executable will be the name of the input file in appropriate form
7817for an executable file on the host system.
7818
7819This switch cannot be used when invoking @emph{gnatmake} with several
7820@code{file_names}.
7821@end table
7822
7823@geindex -p (gnatmake)
7824
7825
7826@table @asis
7827
7828@item @code{-p}
7829
7830Same as @code{--create-missing-dirs}
7831@end table
7832
7833@geindex -P (gnatmake)
7834
7835
7836@table @asis
7837
7838@item @code{-P@emph{project}}
7839
7840Use project file @cite{project}. Only one such switch can be used.
7841@ref{e4,,gnatmake and Project Files}.
7842@end table
7843
7844@geindex -q (gnatmake)
7845
7846
7847@table @asis
7848
7849@item @code{-q}
7850
7851Quiet. When this flag is not set, the commands carried out by
7852@emph{gnatmake} are displayed.
7853@end table
7854
7855@geindex -s (gnatmake)
7856
7857
7858@table @asis
7859
7860@item @code{-s}
7861
7862Recompile if compiler switches have changed since last compilation.
7863All compiler switches but -I and -o are taken into account in the
7864following way:
7865orders between different 'first letter' switches are ignored, but
7866orders between same switches are taken into account. For example,
7867@emph{-O -O2} is different than @emph{-O2 -O}, but @emph{-g -O}
7868is equivalent to @emph{-O -g}.
7869
7870This switch is recommended when Integrated Preprocessing is used.
7871@end table
7872
7873@geindex -u (gnatmake)
7874
7875
7876@table @asis
7877
7878@item @code{-u}
7879
7880Unique. Recompile at most the main files. It implies -c. Combined with
7881-f, it is equivalent to calling the compiler directly. Note that using
7882-u with a project file and no main has a special meaning
7883(@ref{e5,,Project Files and Main Subprograms}).
7884@end table
7885
7886@geindex -U (gnatmake)
7887
7888
7889@table @asis
7890
7891@item @code{-U}
7892
7893When used without a project file or with one or several mains on the command
7894line, is equivalent to -u. When used with a project file and no main
7895on the command line, all sources of all project files are checked and compiled
7896if not up to date, and libraries are rebuilt, if necessary.
7897@end table
7898
7899@geindex -v (gnatmake)
7900
7901
7902@table @asis
7903
7904@item @code{-v}
7905
7906Verbose. Display the reason for all recompilations @emph{gnatmake}
7907decides are necessary, with the highest verbosity level.
7908@end table
7909
7910@geindex -vl (gnatmake)
7911
7912
7913@table @asis
7914
7915@item @code{-vl}
7916
7917Verbosity level Low. Display fewer lines than in verbosity Medium.
7918@end table
7919
7920@geindex -vm (gnatmake)
7921
7922
7923@table @asis
7924
7925@item @code{-vm}
7926
7927Verbosity level Medium. Potentially display fewer lines than in verbosity High.
7928@end table
7929
7930@geindex -vm (gnatmake)
7931
7932
7933@table @asis
7934
7935@item @code{-vh}
7936
7937Verbosity level High. Equivalent to -v.
7938
7939@item @code{-vP@emph{x}}
7940
7941Indicate the verbosity of the parsing of GNAT project files.
7942See @ref{e6,,Switches Related to Project Files}.
7943@end table
7944
7945@geindex -x (gnatmake)
7946
7947
7948@table @asis
7949
7950@item @code{-x}
7951
7952Indicate that sources that are not part of any Project File may be compiled.
7953Normally, when using Project Files, only sources that are part of a Project
7954File may be compile. When this switch is used, a source outside of all Project
7955Files may be compiled. The ALI file and the object file will be put in the
7956object directory of the main Project. The compilation switches used will only
7957be those specified on the command line. Even when
7958@emph{-x} is used, mains specified on the
7959command line need to be sources of a project file.
7960
7961@item @code{-X@emph{name}=@emph{value}}
7962
7963Indicate that external variable @cite{name} has the value @cite{value}.
7964The Project Manager will use this value for occurrences of
7965@cite{external(name)} when parsing the project file.
7966@ref{e6,,Switches Related to Project Files}.
7967@end table
7968
7969@geindex -z (gnatmake)
7970
7971
7972@table @asis
7973
7974@item @code{-z}
7975
7976No main subprogram. Bind and link the program even if the unit name
7977given on the command line is a package name. The resulting executable
7978will execute the elaboration routines of the package and its closure,
7979then the finalization routines.
7980@end table
7981
7982@subsubheading GCC switches
7983
7984
7985Any uppercase or multi-character switch that is not a @emph{gnatmake} switch
7986is passed to @emph{gcc} (e.g., @emph{-O}, @emph{-gnato,} etc.)
7987
7988@subsubheading Source and library search path switches
7989
7990
7991@geindex -aI (gnatmake)
7992
7993
7994@table @asis
7995
7996@item @code{-aI@emph{dir}}
7997
7998When looking for source files also look in directory @cite{dir}.
7999The order in which source files search is undertaken is
8000described in @ref{8e,,Search Paths and the Run-Time Library (RTL)}.
8001@end table
8002
8003@geindex -aL (gnatmake)
8004
8005
8006@table @asis
8007
8008@item @code{-aL@emph{dir}}
8009
8010Consider @cite{dir} as being an externally provided Ada library.
8011Instructs @emph{gnatmake} to skip compilation units whose @code{.ALI}
8012files have been located in directory @cite{dir}. This allows you to have
8013missing bodies for the units in @cite{dir} and to ignore out of date bodies
8014for the same units. You still need to specify
8015the location of the specs for these units by using the switches
8016@code{-aI@emph{dir}}  or @code{-I@emph{dir}}.
8017Note: this switch is provided for compatibility with previous versions
8018of @emph{gnatmake}. The easier method of causing standard libraries
8019to be excluded from consideration is to write-protect the corresponding
8020ALI files.
8021@end table
8022
8023@geindex -aO (gnatmake)
8024
8025
8026@table @asis
8027
8028@item @code{-aO@emph{dir}}
8029
8030When searching for library and object files, look in directory
8031@cite{dir}. The order in which library files are searched is described in
8032@ref{91,,Search Paths for gnatbind}.
8033@end table
8034
8035@geindex Search paths
8036@geindex for gnatmake
8037
8038@geindex -A (gnatmake)
8039
8040
8041@table @asis
8042
8043@item @code{-A@emph{dir}}
8044
8045Equivalent to @code{-aL@emph{dir}} @code{-aI@emph{dir}}.
8046
8047@geindex -I (gnatmake)
8048
8049@item @code{-I@emph{dir}}
8050
8051Equivalent to @code{-aO@emph{dir} -aI@emph{dir}}.
8052@end table
8053
8054@geindex -I- (gnatmake)
8055
8056@geindex Source files
8057@geindex suppressing search
8058
8059
8060@table @asis
8061
8062@item @code{-I-}
8063
8064Do not look for source files in the directory containing the source
8065file named in the command line.
8066Do not look for ALI or object files in the directory
8067where @emph{gnatmake} was invoked.
8068@end table
8069
8070@geindex -L (gnatmake)
8071
8072@geindex Linker libraries
8073
8074
8075@table @asis
8076
8077@item @code{-L@emph{dir}}
8078
8079Add directory @cite{dir} to the list of directories in which the linker
8080will search for libraries. This is equivalent to
8081@code{-largs} @code{-L@emph{dir}}.
8082Furthermore, under Windows, the sources pointed to by the libraries path
8083set in the registry are not searched for.
8084@end table
8085
8086@geindex -nostdinc (gnatmake)
8087
8088
8089@table @asis
8090
8091@item @code{-nostdinc}
8092
8093Do not look for source files in the system default directory.
8094@end table
8095
8096@geindex -nostdlib (gnatmake)
8097
8098
8099@table @asis
8100
8101@item @code{-nostdlib}
8102
8103Do not look for library files in the system default directory.
8104@end table
8105
8106@geindex --RTS (gnatmake)
8107
8108
8109@table @asis
8110
8111@item @code{--RTS=@emph{rts-path}}
8112
8113Specifies the default location of the runtime library. GNAT looks for the
8114runtime
8115in the following directories, and stops as soon as a valid runtime is found
8116(@code{adainclude} or @code{ada_source_path}, and @code{adalib} or
8117@code{ada_object_path} present):
8118
8119
8120@itemize *
8121
8122@item
8123@emph{<current directory>/$rts_path}
8124
8125@item
8126@emph{<default-search-dir>/$rts_path}
8127
8128@item
8129@emph{<default-search-dir>/rts-$rts_path}
8130
8131@item
8132The selected path is handled like a normal RTS path.
8133@end itemize
8134@end table
8135
8136@node Mode Switches for gnatmake,Notes on the Command Line,Switches for gnatmake,Building with gnatmake
8137@anchor{gnat_ugn/building_executable_programs_with_gnat id4}@anchor{e7}@anchor{gnat_ugn/building_executable_programs_with_gnat mode-switches-for-gnatmake}@anchor{e8}
8138@subsection Mode Switches for @emph{gnatmake}
8139
8140
8141The mode switches (referred to as @cite{mode_switches}) allow the
8142inclusion of switches that are to be passed to the compiler itself, the
8143binder or the linker. The effect of a mode switch is to cause all
8144subsequent switches up to the end of the switch list, or up to the next
8145mode switch, to be interpreted as switches to be passed on to the
8146designated component of GNAT.
8147
8148@geindex -cargs (gnatmake)
8149
8150
8151@table @asis
8152
8153@item @code{-cargs @emph{switches}}
8154
8155Compiler switches. Here @cite{switches} is a list of switches
8156that are valid switches for @emph{gcc}. They will be passed on to
8157all compile steps performed by @emph{gnatmake}.
8158@end table
8159
8160@geindex -bargs (gnatmake)
8161
8162
8163@table @asis
8164
8165@item @code{-bargs @emph{switches}}
8166
8167Binder switches. Here @cite{switches} is a list of switches
8168that are valid switches for @cite{gnatbind}. They will be passed on to
8169all bind steps performed by @emph{gnatmake}.
8170@end table
8171
8172@geindex -largs (gnatmake)
8173
8174
8175@table @asis
8176
8177@item @code{-largs @emph{switches}}
8178
8179Linker switches. Here @cite{switches} is a list of switches
8180that are valid switches for @emph{gnatlink}. They will be passed on to
8181all link steps performed by @emph{gnatmake}.
8182@end table
8183
8184@geindex -margs (gnatmake)
8185
8186
8187@table @asis
8188
8189@item @code{-margs @emph{switches}}
8190
8191Make switches. The switches are directly interpreted by @emph{gnatmake},
8192regardless of any previous occurrence of @emph{-cargs}, @emph{-bargs}
8193or @emph{-largs}.
8194@end table
8195
8196@node Notes on the Command Line,How gnatmake Works,Mode Switches for gnatmake,Building with gnatmake
8197@anchor{gnat_ugn/building_executable_programs_with_gnat id5}@anchor{e9}@anchor{gnat_ugn/building_executable_programs_with_gnat notes-on-the-command-line}@anchor{ea}
8198@subsection Notes on the Command Line
8199
8200
8201This section contains some additional useful notes on the operation
8202of the @emph{gnatmake} command.
8203
8204@geindex Recompilation (by gnatmake)
8205
8206
8207@itemize *
8208
8209@item
8210If @emph{gnatmake} finds no ALI files, it recompiles the main program
8211and all other units required by the main program.
8212This means that @emph{gnatmake}
8213can be used for the initial compile, as well as during subsequent steps of
8214the development cycle.
8215
8216@item
8217If you enter @code{gnatmake foo.adb}, where @code{foo}
8218is a subunit or body of a generic unit, @emph{gnatmake} recompiles
8219@code{foo.adb} (because it finds no ALI) and stops, issuing a
8220warning.
8221
8222@item
8223In @emph{gnatmake} the switch @emph{-I}
8224is used to specify both source and
8225library file paths. Use @emph{-aI}
8226instead if you just want to specify
8227source paths only and @emph{-aO}
8228if you want to specify library paths
8229only.
8230
8231@item
8232@emph{gnatmake} will ignore any files whose ALI file is write-protected.
8233This may conveniently be used to exclude standard libraries from
8234consideration and in particular it means that the use of the
8235@emph{-f} switch will not recompile these files
8236unless @emph{-a} is also specified.
8237
8238@item
8239@emph{gnatmake} has been designed to make the use of Ada libraries
8240particularly convenient. Assume you have an Ada library organized
8241as follows: @emph{obj-dir} contains the objects and ALI files for
8242of your Ada compilation units,
8243whereas @emph{include-dir} contains the
8244specs of these units, but no bodies. Then to compile a unit
8245stored in @cite{main.adb}, which uses this Ada library you would just type:
8246
8247@example
8248$ gnatmake -aI`include-dir`  -aL`obj-dir`  main
8249@end example
8250
8251@item
8252Using @emph{gnatmake} along with the @emph{-m (minimal recompilation)}
8253switch provides a mechanism for avoiding unnecessary recompilations. Using
8254this switch,
8255you can update the comments/format of your
8256source files without having to recompile everything. Note, however, that
8257adding or deleting lines in a source files may render its debugging
8258info obsolete. If the file in question is a spec, the impact is rather
8259limited, as that debugging info will only be useful during the
8260elaboration phase of your program. For bodies the impact can be more
8261significant. In all events, your debugger will warn you if a source file
8262is more recent than the corresponding object, and alert you to the fact
8263that the debugging information may be out of date.
8264@end itemize
8265
8266@node How gnatmake Works,Examples of gnatmake Usage,Notes on the Command Line,Building with gnatmake
8267@anchor{gnat_ugn/building_executable_programs_with_gnat id6}@anchor{eb}@anchor{gnat_ugn/building_executable_programs_with_gnat how-gnatmake-works}@anchor{ec}
8268@subsection How @emph{gnatmake} Works
8269
8270
8271Generally @emph{gnatmake} automatically performs all necessary
8272recompilations and you don't need to worry about how it works. However,
8273it may be useful to have some basic understanding of the @emph{gnatmake}
8274approach and in particular to understand how it uses the results of
8275previous compilations without incorrectly depending on them.
8276
8277First a definition: an object file is considered @emph{up to date} if the
8278corresponding ALI file exists and if all the source files listed in the
8279dependency section of this ALI file have time stamps matching those in
8280the ALI file. This means that neither the source file itself nor any
8281files that it depends on have been modified, and hence there is no need
8282to recompile this file.
8283
8284@emph{gnatmake} works by first checking if the specified main unit is up
8285to date. If so, no compilations are required for the main unit. If not,
8286@emph{gnatmake} compiles the main program to build a new ALI file that
8287reflects the latest sources. Then the ALI file of the main unit is
8288examined to find all the source files on which the main program depends,
8289and @emph{gnatmake} recursively applies the above procedure on all these
8290files.
8291
8292This process ensures that @emph{gnatmake} only trusts the dependencies
8293in an existing ALI file if they are known to be correct. Otherwise it
8294always recompiles to determine a new, guaranteed accurate set of
8295dependencies. As a result the program is compiled 'upside down' from what may
8296be more familiar as the required order of compilation in some other Ada
8297systems. In particular, clients are compiled before the units on which
8298they depend. The ability of GNAT to compile in any order is critical in
8299allowing an order of compilation to be chosen that guarantees that
8300@emph{gnatmake} will recompute a correct set of new dependencies if
8301necessary.
8302
8303When invoking @emph{gnatmake} with several @cite{file_names}, if a unit is
8304imported by several of the executables, it will be recompiled at most once.
8305
8306Note: when using non-standard naming conventions
8307(@ref{37,,Using Other File Names}), changing through a configuration pragmas
8308file the version of a source and invoking @emph{gnatmake} to recompile may
8309have no effect, if the previous version of the source is still accessible
8310by @emph{gnatmake}. It may be necessary to use the switch
8311-f.
8312
8313@node Examples of gnatmake Usage,,How gnatmake Works,Building with gnatmake
8314@anchor{gnat_ugn/building_executable_programs_with_gnat examples-of-gnatmake-usage}@anchor{ed}@anchor{gnat_ugn/building_executable_programs_with_gnat id7}@anchor{ee}
8315@subsection Examples of @emph{gnatmake} Usage
8316
8317
8318
8319@table @asis
8320
8321@item @emph{gnatmake hello.adb}
8322
8323Compile all files necessary to bind and link the main program
8324@code{hello.adb} (containing unit @cite{Hello}) and bind and link the
8325resulting object files to generate an executable file @code{hello}.
8326
8327@item @emph{gnatmake main1 main2 main3}
8328
8329Compile all files necessary to bind and link the main programs
8330@code{main1.adb} (containing unit @cite{Main1}), @code{main2.adb}
8331(containing unit @cite{Main2}) and @code{main3.adb}
8332(containing unit @cite{Main3}) and bind and link the resulting object files
8333to generate three executable files @code{main1},
8334@code{main2}  and @code{main3}.
8335
8336@item @emph{gnatmake -q Main_Unit -cargs -O2 -bargs -l}
8337
8338Compile all files necessary to bind and link the main program unit
8339@cite{Main_Unit} (from file @code{main_unit.adb}). All compilations will
8340be done with optimization level 2 and the order of elaboration will be
8341listed by the binder. @emph{gnatmake} will operate in quiet mode, not
8342displaying commands it is executing.
8343@end table
8344
8345@node Compiling with gcc,Compiler Switches,Building with gnatmake,Building Executable Programs with GNAT
8346@anchor{gnat_ugn/building_executable_programs_with_gnat compiling-with-gcc}@anchor{1e}@anchor{gnat_ugn/building_executable_programs_with_gnat id8}@anchor{ef}
8347@section Compiling with @emph{gcc}
8348
8349
8350This section discusses how to compile Ada programs using the @emph{gcc}
8351command. It also describes the set of switches
8352that can be used to control the behavior of the compiler.
8353
8354@menu
8355* Compiling Programs::
8356* Search Paths and the Run-Time Library (RTL): Search Paths and the Run-Time Library RTL.
8357* Order of Compilation Issues::
8358* Examples::
8359
8360@end menu
8361
8362@node Compiling Programs,Search Paths and the Run-Time Library RTL,,Compiling with gcc
8363@anchor{gnat_ugn/building_executable_programs_with_gnat compiling-programs}@anchor{f0}@anchor{gnat_ugn/building_executable_programs_with_gnat id9}@anchor{f1}
8364@subsection Compiling Programs
8365
8366
8367The first step in creating an executable program is to compile the units
8368of the program using the @emph{gcc} command. You must compile the
8369following files:
8370
8371
8372@itemize *
8373
8374@item
8375the body file (@code{.adb}) for a library level subprogram or generic
8376subprogram
8377
8378@item
8379the spec file (@code{.ads}) for a library level package or generic
8380package that has no body
8381
8382@item
8383the body file (@code{.adb}) for a library level package
8384or generic package that has a body
8385@end itemize
8386
8387You need @emph{not} compile the following files
8388
8389
8390@itemize *
8391
8392@item
8393the spec of a library unit which has a body
8394
8395@item
8396subunits
8397@end itemize
8398
8399because they are compiled as part of compiling related units. GNAT
8400package specs
8401when the corresponding body is compiled, and subunits when the parent is
8402compiled.
8403
8404@geindex cannot generate code
8405
8406If you attempt to compile any of these files, you will get one of the
8407following error messages (where @cite{fff} is the name of the file you
8408compiled):
8409
8410@quotation
8411
8412@example
8413cannot generate code for file `fff` (package spec)
8414to check package spec, use -gnatc
8415
8416cannot generate code for file `fff` (missing subunits)
8417to check parent unit, use -gnatc
8418
8419cannot generate code for file `fff` (subprogram spec)
8420to check subprogram spec, use -gnatc
8421
8422cannot generate code for file `fff` (subunit)
8423to check subunit, use -gnatc
8424@end example
8425@end quotation
8426
8427As indicated by the above error messages, if you want to submit
8428one of these files to the compiler to check for correct semantics
8429without generating code, then use the @emph{-gnatc} switch.
8430
8431The basic command for compiling a file containing an Ada unit is:
8432
8433@example
8434$ gcc -c [switches] <file name>
8435@end example
8436
8437where @cite{file name} is the name of the Ada file (usually
8438having an extension @code{.ads} for a spec or @code{.adb} for a body).
8439You specify the
8440@code{-c} switch to tell @emph{gcc} to compile, but not link, the file.
8441The result of a successful compilation is an object file, which has the
8442same name as the source file but an extension of @code{.o} and an Ada
8443Library Information (ALI) file, which also has the same name as the
8444source file, but with @code{.ali} as the extension. GNAT creates these
8445two output files in the current directory, but you may specify a source
8446file in any directory using an absolute or relative path specification
8447containing the directory information.
8448
8449@geindex gnat1
8450
8451@emph{gcc} is actually a driver program that looks at the extensions of
8452the file arguments and loads the appropriate compiler. For example, the
8453GNU C compiler is @code{cc1}, and the Ada compiler is @code{gnat1}.
8454These programs are in directories known to the driver program (in some
8455configurations via environment variables you set), but need not be in
8456your path. The @emph{gcc} driver also calls the assembler and any other
8457utilities needed to complete the generation of the required object
8458files.
8459
8460It is possible to supply several file names on the same @emph{gcc}
8461command. This causes @emph{gcc} to call the appropriate compiler for
8462each file. For example, the following command lists two separate
8463files to be compiled:
8464
8465@example
8466$ gcc -c x.adb y.adb
8467@end example
8468
8469calls @cite{gnat1} (the Ada compiler) twice to compile @code{x.adb} and
8470@code{y.adb}.
8471The compiler generates two object files @code{x.o} and @code{y.o}
8472and the two ALI files @code{x.ali} and @code{y.ali}.
8473
8474Any switches apply to all the files listed, see @ref{f2,,Compiler Switches} for a
8475list of available @emph{gcc} switches.
8476
8477@node Search Paths and the Run-Time Library RTL,Order of Compilation Issues,Compiling Programs,Compiling with gcc
8478@anchor{gnat_ugn/building_executable_programs_with_gnat id10}@anchor{f3}@anchor{gnat_ugn/building_executable_programs_with_gnat search-paths-and-the-run-time-library-rtl}@anchor{8e}
8479@subsection Search Paths and the Run-Time Library (RTL)
8480
8481
8482With the GNAT source-based library system, the compiler must be able to
8483find source files for units that are needed by the unit being compiled.
8484Search paths are used to guide this process.
8485
8486The compiler compiles one source file whose name must be given
8487explicitly on the command line. In other words, no searching is done
8488for this file. To find all other source files that are needed (the most
8489common being the specs of units), the compiler examines the following
8490directories, in the following order:
8491
8492
8493@itemize *
8494
8495@item
8496The directory containing the source file of the main unit being compiled
8497(the file name on the command line).
8498
8499@item
8500Each directory named by an @emph{-I} switch given on the @emph{gcc}
8501command line, in the order given.
8502
8503@geindex ADA_PRJ_INCLUDE_FILE
8504
8505@item
8506Each of the directories listed in the text file whose name is given
8507by the
8508@geindex ADA_PRJ_INCLUDE_FILE
8509@geindex environment variable; ADA_PRJ_INCLUDE_FILE
8510@code{ADA_PRJ_INCLUDE_FILE} environment variable.
8511@geindex ADA_PRJ_INCLUDE_FILE
8512@geindex environment variable; ADA_PRJ_INCLUDE_FILE
8513@code{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the gnat
8514driver when project files are used. It should not normally be set
8515by other means.
8516
8517@geindex ADA_INCLUDE_PATH
8518
8519@item
8520Each of the directories listed in the value of the
8521@geindex ADA_INCLUDE_PATH
8522@geindex environment variable; ADA_INCLUDE_PATH
8523@code{ADA_INCLUDE_PATH} environment variable.
8524Construct this value
8525exactly as the
8526@geindex PATH
8527@geindex environment variable; PATH
8528@code{PATH} environment variable: a list of directory
8529names separated by colons (semicolons when working with the NT version).
8530
8531@item
8532The content of the @code{ada_source_path} file which is part of the GNAT
8533installation tree and is used to store standard libraries such as the
8534GNAT Run Time Library (RTL) source files.
8535@ref{8b,,Installing a library}
8536@end itemize
8537
8538Specifying the switch @emph{-I-}
8539inhibits the use of the directory
8540containing the source file named in the command line. You can still
8541have this directory on your search path, but in this case it must be
8542explicitly requested with a @emph{-I} switch.
8543
8544Specifying the switch @emph{-nostdinc}
8545inhibits the search of the default location for the GNAT Run Time
8546Library (RTL) source files.
8547
8548The compiler outputs its object files and ALI files in the current
8549working directory.
8550Caution: The object file can be redirected with the @emph{-o} switch;
8551however, @emph{gcc} and @cite{gnat1} have not been coordinated on this
8552so the @code{ALI} file will not go to the right place. Therefore, you should
8553avoid using the @emph{-o} switch.
8554
8555@geindex System.IO
8556
8557The packages @cite{Ada}, @cite{System}, and @cite{Interfaces} and their
8558children make up the GNAT RTL, together with the simple @cite{System.IO}
8559package used in the @cite{"Hello World"} example. The sources for these units
8560are needed by the compiler and are kept together in one directory. Not
8561all of the bodies are needed, but all of the sources are kept together
8562anyway. In a normal installation, you need not specify these directory
8563names when compiling or binding. Either the environment variables or
8564the built-in defaults cause these files to be found.
8565
8566In addition to the language-defined hierarchies (@cite{System}, @cite{Ada} and
8567@cite{Interfaces}), the GNAT distribution provides a fourth hierarchy,
8568consisting of child units of @cite{GNAT}. This is a collection of generally
8569useful types, subprograms, etc. See the @cite{GNAT_Reference_Manual}
8570for further details.
8571
8572Besides simplifying access to the RTL, a major use of search paths is
8573in compiling sources from multiple directories. This can make
8574development environments much more flexible.
8575
8576@node Order of Compilation Issues,Examples,Search Paths and the Run-Time Library RTL,Compiling with gcc
8577@anchor{gnat_ugn/building_executable_programs_with_gnat id11}@anchor{f4}@anchor{gnat_ugn/building_executable_programs_with_gnat order-of-compilation-issues}@anchor{f5}
8578@subsection Order of Compilation Issues
8579
8580
8581If, in our earlier example, there was a spec for the @cite{hello}
8582procedure, it would be contained in the file @code{hello.ads}; yet this
8583file would not have to be explicitly compiled. This is the result of the
8584model we chose to implement library management. Some of the consequences
8585of this model are as follows:
8586
8587
8588@itemize *
8589
8590@item
8591There is no point in compiling specs (except for package
8592specs with no bodies) because these are compiled as needed by clients. If
8593you attempt a useless compilation, you will receive an error message.
8594It is also useless to compile subunits because they are compiled as needed
8595by the parent.
8596
8597@item
8598There are no order of compilation requirements: performing a
8599compilation never obsoletes anything. The only way you can obsolete
8600something and require recompilations is to modify one of the
8601source files on which it depends.
8602
8603@item
8604There is no library as such, apart from the ALI files
8605(@ref{44,,The Ada Library Information Files}, for information on the format
8606of these files). For now we find it convenient to create separate ALI files,
8607but eventually the information therein may be incorporated into the object
8608file directly.
8609
8610@item
8611When you compile a unit, the source files for the specs of all units
8612that it @emph{with}s, all its subunits, and the bodies of any generics it
8613instantiates must be available (reachable by the search-paths mechanism
8614described above), or you will receive a fatal error message.
8615@end itemize
8616
8617@node Examples,,Order of Compilation Issues,Compiling with gcc
8618@anchor{gnat_ugn/building_executable_programs_with_gnat id12}@anchor{f6}@anchor{gnat_ugn/building_executable_programs_with_gnat examples}@anchor{f7}
8619@subsection Examples
8620
8621
8622The following are some typical Ada compilation command line examples:
8623
8624@example
8625$ gcc -c xyz.adb
8626@end example
8627
8628Compile body in file @code{xyz.adb} with all default options.
8629
8630@example
8631$ gcc -c -O2 -gnata xyz-def.adb
8632@end example
8633
8634Compile the child unit package in file @code{xyz-def.adb} with extensive
8635optimizations, and pragma @cite{Assert}/@cite{Debug} statements
8636enabled.
8637
8638@example
8639$ gcc -c -gnatc abc-def.adb
8640@end example
8641
8642Compile the subunit in file @code{abc-def.adb} in semantic-checking-only
8643mode.
8644
8645@node Compiler Switches,Binding with gnatbind,Compiling with gcc,Building Executable Programs with GNAT
8646@anchor{gnat_ugn/building_executable_programs_with_gnat compiler-switches}@anchor{f8}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gcc}@anchor{f2}
8647@section Compiler Switches
8648
8649
8650The @emph{gcc} command accepts switches that control the
8651compilation process. These switches are fully described in this section:
8652first an alphabetical listing of all switches with a brief description,
8653and then functionally grouped sets of switches with more detailed
8654information.
8655
8656More switches exist for GCC than those documented here, especially
8657for specific targets. However, their use is not recommended as
8658they may change code generation in ways that are incompatible with
8659the Ada run-time library, or can cause inconsistencies between
8660compilation units.
8661
8662@menu
8663* Alphabetical List of All Switches::
8664* Output and Error Message Control::
8665* Warning Message Control::
8666* Debugging and Assertion Control::
8667* Validity Checking::
8668* Style Checking::
8669* Run-Time Checks::
8670* Using gcc for Syntax Checking::
8671* Using gcc for Semantic Checking::
8672* Compiling Different Versions of Ada::
8673* Character Set Control::
8674* File Naming Control::
8675* Subprogram Inlining Control::
8676* Auxiliary Output Control::
8677* Debugging Control::
8678* Exception Handling Control::
8679* Units to Sources Mapping Files::
8680* Code Generation Control::
8681
8682@end menu
8683
8684@node Alphabetical List of All Switches,Output and Error Message Control,,Compiler Switches
8685@anchor{gnat_ugn/building_executable_programs_with_gnat id13}@anchor{f9}@anchor{gnat_ugn/building_executable_programs_with_gnat alphabetical-list-of-all-switches}@anchor{fa}
8686@subsection Alphabetical List of All Switches
8687
8688
8689@geindex -b (gcc)
8690
8691
8692@table @asis
8693
8694@item @code{-b @emph{target}}
8695
8696Compile your program to run on @cite{target}, which is the name of a
8697system configuration. You must have a GNAT cross-compiler built if
8698@cite{target} is not the same as your host system.
8699@end table
8700
8701@geindex -B (gcc)
8702
8703
8704@table @asis
8705
8706@item @code{-B@emph{dir}}
8707
8708Load compiler executables (for example, @cite{gnat1}, the Ada compiler)
8709from @cite{dir} instead of the default location. Only use this switch
8710when multiple versions of the GNAT compiler are available.
8711See the "Options for Directory Search" section in the
8712@cite{Using the GNU Compiler Collection (GCC)} manual for further details.
8713You would normally use the @emph{-b} or @emph{-V} switch instead.
8714@end table
8715
8716@geindex -c (gcc)
8717
8718
8719@table @asis
8720
8721@item @code{-c}
8722
8723Compile. Always use this switch when compiling Ada programs.
8724
8725Note: for some other languages when using @emph{gcc}, notably in
8726the case of C and C++, it is possible to use
8727use @emph{gcc} without a @emph{-c} switch to
8728compile and link in one step. In the case of GNAT, you
8729cannot use this approach, because the binder must be run
8730and @emph{gcc} cannot be used to run the GNAT binder.
8731@end table
8732
8733@geindex -fcallgraph-info (gcc)
8734
8735
8736@table @asis
8737
8738@item @code{-fcallgraph-info[=su,da]}
8739
8740Makes the compiler output callgraph information for the program, on a
8741per-file basis. The information is generated in the VCG format.  It can
8742be decorated with additional, per-node and/or per-edge information, if a
8743list of comma-separated markers is additionally specified. When the
8744@cite{su} marker is specified, the callgraph is decorated with stack usage
8745information; it is equivalent to @emph{-fstack-usage}. When the @cite{da}
8746marker is specified, the callgraph is decorated with information about
8747dynamically allocated objects.
8748@end table
8749
8750@geindex -fdump-scos (gcc)
8751
8752
8753@table @asis
8754
8755@item @code{-fdump-scos}
8756
8757Generates SCO (Source Coverage Obligation) information in the ALI file.
8758This information is used by advanced coverage tools. See unit @code{SCOs}
8759in the compiler sources for details in files @code{scos.ads} and
8760@code{scos.adb}.
8761@end table
8762
8763@geindex -fdump-xref (gcc)
8764
8765
8766@table @asis
8767
8768@item @code{-fdump-xref}
8769
8770Generates cross reference information in GLI files for C and C++ sources.
8771The GLI files have the same syntax as the ALI files for Ada, and can be used
8772for source navigation in IDEs and on the command line using e.g. gnatxref
8773and the @emph{--ext=gli} switch.
8774@end table
8775
8776@geindex -flto (gcc)
8777
8778
8779@table @asis
8780
8781@item @code{-flto[=@emph{n}]}
8782
8783Enables Link Time Optimization. This switch must be used in conjunction
8784with the traditional @emph{-Ox} switches and instructs the compiler to
8785defer most optimizations until the link stage. The advantage of this
8786approach is that the compiler can do a whole-program analysis and choose
8787the best interprocedural optimization strategy based on a complete view
8788of the program, instead of a fragmentary view with the usual approach.
8789This can also speed up the compilation of big programs and reduce the
8790size of the executable, compared with a traditional per-unit compilation
8791with inlining across modules enabled by the @emph{-gnatn} switch.
8792The drawback of this approach is that it may require more memory and that
8793the debugging information generated by -g with it might be hardly usable.
8794The switch, as well as the accompanying @emph{-Ox} switches, must be
8795specified both for the compilation and the link phases.
8796If the @cite{n} parameter is specified, the optimization and final code
8797generation at link time are executed using @cite{n} parallel jobs by
8798means of an installed @emph{make} program.
8799@end table
8800
8801@geindex -fno-inline (gcc)
8802
8803
8804@table @asis
8805
8806@item @code{-fno-inline}
8807
8808Suppresses all inlining, unless requested with pragma @cite{Inline_Always}. The
8809effect is enforced regardless of other optimization or inlining switches.
8810Note that inlining can also be suppressed on a finer-grained basis with
8811pragma @cite{No_Inline}.
8812@end table
8813
8814@geindex -fno-inline-functions (gcc)
8815
8816
8817@table @asis
8818
8819@item @code{-fno-inline-functions}
8820
8821Suppresses automatic inlining of subprograms, which is enabled
8822if @emph{-O3} is used.
8823@end table
8824
8825@geindex -fno-inline-small-functions (gcc)
8826
8827
8828@table @asis
8829
8830@item @code{-fno-inline-small-functions}
8831
8832Suppresses automatic inlining of small subprograms, which is enabled
8833if @emph{-O2} is used.
8834@end table
8835
8836@geindex -fno-inline-functions-called-once (gcc)
8837
8838
8839@table @asis
8840
8841@item @code{-fno-inline-functions-called-once}
8842
8843Suppresses inlining of subprograms local to the unit and called once
8844from within it, which is enabled if @emph{-O1} is used.
8845@end table
8846
8847@geindex -fno-ivopts (gcc)
8848
8849
8850@table @asis
8851
8852@item @code{-fno-ivopts}
8853
8854Suppresses high-level loop induction variable optimizations, which are
8855enabled if @emph{-O1} is used. These optimizations are generally
8856profitable but, for some specific cases of loops with numerous uses
8857of the iteration variable that follow a common pattern, they may end
8858up destroying the regularity that could be exploited at a lower level
8859and thus producing inferior code.
8860@end table
8861
8862@geindex -fno-strict-aliasing (gcc)
8863
8864
8865@table @asis
8866
8867@item @code{-fno-strict-aliasing}
8868
8869Causes the compiler to avoid assumptions regarding non-aliasing
8870of objects of different types. See
8871@ref{fb,,Optimization and Strict Aliasing} for details.
8872@end table
8873
8874@geindex -fno-strict-overflow (gcc)
8875
8876
8877@table @asis
8878
8879@item @code{-fno-strict-overflow}
8880
8881Causes the compiler to avoid assumptions regarding the rules of signed
8882integer overflow. These rules specify that signed integer overflow will
8883result in a Constraint_Error exception at run time and are enforced in
8884default mode by the compiler, so this switch should not be necessary in
8885normal operating mode. It might be useful in conjunction with @emph{-gnato0}
8886for very peculiar cases of low-level programming.
8887@end table
8888
8889@geindex -fstack-check (gcc)
8890
8891
8892@table @asis
8893
8894@item @code{-fstack-check}
8895
8896Activates stack checking.
8897See @ref{fc,,Stack Overflow Checking} for details.
8898@end table
8899
8900@geindex -fstack-usage (gcc)
8901
8902
8903@table @asis
8904
8905@item @code{-fstack-usage}
8906
8907Makes the compiler output stack usage information for the program, on a
8908per-subprogram basis. See @ref{fd,,Static Stack Usage Analysis} for details.
8909@end table
8910
8911@geindex -g (gcc)
8912
8913
8914@table @asis
8915
8916@item @code{-g}
8917
8918Generate debugging information. This information is stored in the object
8919file and copied from there to the final executable file by the linker,
8920where it can be read by the debugger. You must use the
8921@emph{-g} switch if you plan on using the debugger.
8922@end table
8923
8924@geindex -gnat05 (gcc)
8925
8926
8927@table @asis
8928
8929@item @code{-gnat05}
8930
8931Allow full Ada 2005 features.
8932@end table
8933
8934@geindex -gnat12 (gcc)
8935
8936
8937@table @asis
8938
8939@item @code{-gnat12}
8940
8941Allow full Ada 2012 features.
8942@end table
8943
8944@geindex -gnat83 (gcc)
8945
8946@geindex -gnat2005 (gcc)
8947
8948
8949@table @asis
8950
8951@item @code{-gnat2005}
8952
8953Allow full Ada 2005 features (same as @emph{-gnat05})
8954@end table
8955
8956@geindex -gnat2012 (gcc)
8957
8958
8959@table @asis
8960
8961@item @code{-gnat2012}
8962
8963Allow full Ada 2012 features (same as @emph{-gnat12})
8964
8965@item @code{-gnat83}
8966
8967Enforce Ada 83 restrictions.
8968@end table
8969
8970@geindex -gnat95 (gcc)
8971
8972
8973@table @asis
8974
8975@item @code{-gnat95}
8976
8977Enforce Ada 95 restrictions.
8978
8979Note: for compatibility with some Ada 95 compilers which support only
8980the @cite{overriding} keyword of Ada 2005, the @emph{-gnatd.D} switch can
8981be used along with @emph{-gnat95} to achieve a similar effect with GNAT.
8982
8983@emph{-gnatd.D} instructs GNAT to consider @cite{overriding} as a keyword
8984and handle its associated semantic checks, even in Ada 95 mode.
8985@end table
8986
8987@geindex -gnata (gcc)
8988
8989
8990@table @asis
8991
8992@item @code{-gnata}
8993
8994Assertions enabled. @cite{Pragma Assert} and @cite{pragma Debug} to be
8995activated. Note that these pragmas can also be controlled using the
8996configuration pragmas @cite{Assertion_Policy} and @cite{Debug_Policy}.
8997It also activates pragmas @cite{Check}, @cite{Precondition}, and
8998@cite{Postcondition}. Note that these pragmas can also be controlled
8999using the configuration pragma @cite{Check_Policy}. In Ada 2012, it
9000also activates all assertions defined in the RM as aspects: preconditions,
9001postconditions, type invariants and (sub)type predicates. In all Ada modes,
9002corresponding pragmas for type invariants and (sub)type predicates are
9003also activated. The default is that all these assertions are disabled,
9004and have no effect, other than being checked for syntactic validity, and
9005in the case of subtype predicates, constructions such as membership tests
9006still test predicates even if assertions are turned off.
9007@end table
9008
9009@geindex -gnatA (gcc)
9010
9011
9012@table @asis
9013
9014@item @code{-gnatA}
9015
9016Avoid processing @code{gnat.adc}. If a @code{gnat.adc} file is present,
9017it will be ignored.
9018@end table
9019
9020@geindex -gnatb (gcc)
9021
9022
9023@table @asis
9024
9025@item @code{-gnatb}
9026
9027Generate brief messages to @code{stderr} even if verbose mode set.
9028@end table
9029
9030@geindex -gnatB (gcc)
9031
9032
9033@table @asis
9034
9035@item @code{-gnatB}
9036
9037Assume no invalid (bad) values except for 'Valid attribute use
9038(@ref{fe,,Validity Checking}).
9039@end table
9040
9041@geindex -gnatc (gcc)
9042
9043
9044@table @asis
9045
9046@item @code{-gnatc}
9047
9048Check syntax and semantics only (no code generation attempted). When the
9049compiler is invoked by @emph{gnatmake}, if the switch @emph{-gnatc} is
9050only given to the compiler (after @emph{-cargs} or in package Compiler of
9051the project file, @emph{gnatmake} will fail because it will not find the
9052object file after compilation. If @emph{gnatmake} is called with
9053@emph{-gnatc} as a builder switch (before @emph{-cargs} or in package
9054Builder of the project file) then @emph{gnatmake} will not fail because
9055it will not look for the object files after compilation, and it will not try
9056to build and link. This switch may not be given if a previous @cite{-gnatR}
9057switch has been given, since @cite{-gnatR} requires that the code generator
9058be called to complete determination of representation information.
9059@end table
9060
9061@geindex -gnatC (gcc)
9062
9063
9064@table @asis
9065
9066@item @code{-gnatC}
9067
9068Generate CodePeer intermediate format (no code generation attempted).
9069This switch will generate an intermediate representation suitable for
9070use by CodePeer (@code{.scil} files). This switch is not compatible with
9071code generation (it will, among other things, disable some switches such
9072as -gnatn, and enable others such as -gnata).
9073@end table
9074
9075@geindex -gnatd (gcc)
9076
9077
9078@table @asis
9079
9080@item @code{-gnatd}
9081
9082Specify debug options for the compiler. The string of characters after
9083the @emph{-gnatd} specify the specific debug options. The possible
9084characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
9085compiler source file @code{debug.adb} for details of the implemented
9086debug options. Certain debug options are relevant to applications
9087programmers, and these are documented at appropriate points in this
9088users guide.
9089@end table
9090
9091@geindex -gnatD[nn] (gcc)
9092
9093
9094@table @asis
9095
9096@item @code{-gnatD}
9097
9098Create expanded source files for source level debugging. This switch
9099also suppress generation of cross-reference information
9100(see @emph{-gnatx}). Note that this switch is not allowed if a previous
9101-gnatR switch has been given, since these two switches are not compatible.
9102@end table
9103
9104@geindex -gnateA (gcc)
9105
9106
9107@table @asis
9108
9109@item @code{-gnateA}
9110
9111Check that the actual parameters of a subprogram call are not aliases of one
9112another. To qualify as aliasing, the actuals must denote objects of a composite
9113type, their memory locations must be identical or overlapping, and at least one
9114of the corresponding formal parameters must be of mode OUT or IN OUT.
9115
9116@example
9117type Rec_Typ is record
9118   Data : Integer := 0;
9119end record;
9120
9121function Self (Val : Rec_Typ) return Rec_Typ is
9122begin
9123   return Val;
9124end Self;
9125
9126procedure Detect_Aliasing (Val_1 : in out Rec_Typ; Val_2 : Rec_Typ) is
9127begin
9128   null;
9129end Detect_Aliasing;
9130
9131Obj : Rec_Typ;
9132
9133Detect_Aliasing (Obj, Obj);
9134Detect_Aliasing (Obj, Self (Obj));
9135@end example
9136
9137In the example above, the first call to @cite{Detect_Aliasing} fails with a
9138@cite{Program_Error} at runtime because the actuals for @cite{Val_1} and
9139@cite{Val_2} denote the same object. The second call executes without raising
9140an exception because @cite{Self(Obj)} produces an anonymous object which does
9141not share the memory location of @cite{Obj}.
9142@end table
9143
9144@geindex -gnatec (gcc)
9145
9146
9147@table @asis
9148
9149@item @code{-gnatec=@emph{path}}
9150
9151Specify a configuration pragma file
9152(the equal sign is optional)
9153(@ref{7b,,The Configuration Pragmas Files}).
9154@end table
9155
9156@geindex -gnateC (gcc)
9157
9158
9159@table @asis
9160
9161@item @code{-gnateC}
9162
9163Generate CodePeer messages in a compiler-like format. This switch is only
9164effective if @emph{-gnatcC} is also specified and requires an installation
9165of CodePeer.
9166@end table
9167
9168@geindex -gnated (gcc)
9169
9170
9171@table @asis
9172
9173@item @code{-gnated}
9174
9175Disable atomic synchronization
9176@end table
9177
9178@geindex -gnateD (gcc)
9179
9180
9181@table @asis
9182
9183@item @code{-gnateDsymbol[=@emph{value}]}
9184
9185Defines a symbol, associated with @cite{value}, for preprocessing.
9186(@ref{1a,,Integrated Preprocessing}).
9187@end table
9188
9189@geindex -gnateE (gcc)
9190
9191
9192@table @asis
9193
9194@item @code{-gnateE}
9195
9196Generate extra information in exception messages. In particular, display
9197extra column information and the value and range associated with index and
9198range check failures, and extra column information for access checks.
9199In cases where the compiler is able to determine at compile time that
9200a check will fail, it gives a warning, and the extra information is not
9201produced at run time.
9202@end table
9203
9204@geindex -gnatef (gcc)
9205
9206
9207@table @asis
9208
9209@item @code{-gnatef}
9210
9211Display full source path name in brief error messages.
9212@end table
9213
9214@geindex -gnateF (gcc)
9215
9216
9217@table @asis
9218
9219@item @code{-gnateF}
9220
9221Check for overflow on all floating-point operations, including those
9222for unconstrained predefined types. See description of pragma
9223@cite{Check_Float_Overflow} in GNAT RM.
9224@end table
9225
9226@geindex -gnateg (gcc)
9227
9228@code{-gnateg}
9229@code{-gnatceg}
9230
9231@quotation
9232
9233The @cite{-gnatc} switch must always be specified before this switch, e.g.
9234@cite{-gnatceg}. Generate a C header from the Ada input file. See
9235@ref{d0,,Generating C Headers for Ada Specifications} for more
9236information.
9237@end quotation
9238
9239@geindex -gnateG (gcc)
9240
9241
9242@table @asis
9243
9244@item @code{-gnateG}
9245
9246Save result of preprocessing in a text file.
9247@end table
9248
9249@geindex -gnatei (gcc)
9250
9251
9252@table @asis
9253
9254@item @code{-gnatei@emph{nnn}}
9255
9256Set maximum number of instantiations during compilation of a single unit to
9257@cite{nnn}. This may be useful in increasing the default maximum of 8000 for
9258the rare case when a single unit legitimately exceeds this limit.
9259@end table
9260
9261@geindex -gnateI (gcc)
9262
9263
9264@table @asis
9265
9266@item @code{-gnateI@emph{nnn}}
9267
9268Indicates that the source is a multi-unit source and that the index of the
9269unit to compile is @cite{nnn}. @cite{nnn} needs to be a positive number and need
9270to be a valid index in the multi-unit source.
9271@end table
9272
9273@geindex -gnatel (gcc)
9274
9275
9276@table @asis
9277
9278@item @code{-gnatel}
9279
9280This switch can be used with the static elaboration model to issue info
9281messages showing
9282where implicit @cite{pragma Elaborate} and @cite{pragma Elaborate_All}
9283are generated. This is useful in diagnosing elaboration circularities
9284caused by these implicit pragmas when using the static elaboration
9285model. See See the section in this guide on elaboration checking for
9286further details. These messages are not generated by default, and are
9287intended only for temporary use when debugging circularity problems.
9288@end table
9289
9290@geindex -gnatel (gcc)
9291
9292
9293@table @asis
9294
9295@item @code{-gnateL}
9296
9297This switch turns off the info messages about implicit elaboration pragmas.
9298@end table
9299
9300@geindex -gnatem (gcc)
9301
9302
9303@table @asis
9304
9305@item @code{-gnatem=@emph{path}}
9306
9307Specify a mapping file
9308(the equal sign is optional)
9309(@ref{ff,,Units to Sources Mapping Files}).
9310@end table
9311
9312@geindex -gnatep (gcc)
9313
9314
9315@table @asis
9316
9317@item @code{-gnatep=@emph{file}}
9318
9319Specify a preprocessing data file
9320(the equal sign is optional)
9321(@ref{1a,,Integrated Preprocessing}).
9322@end table
9323
9324@geindex -gnateP (gcc)
9325
9326
9327@table @asis
9328
9329@item @code{-gnateP}
9330
9331Turn categorization dependency errors into warnings.
9332Ada requires that units that WITH one another have compatible categories, for
9333example a Pure unit cannot WITH a Preelaborate unit. If this switch is used,
9334these errors become warnings (which can be ignored, or suppressed in the usual
9335manner). This can be useful in some specialized circumstances such as the
9336temporary use of special test software.
9337@end table
9338
9339@geindex -gnateS (gcc)
9340
9341
9342@table @asis
9343
9344@item @code{-gnateS}
9345
9346Synonym of @emph{-fdump-scos}, kept for backwards compatibility.
9347@end table
9348
9349@geindex -gnatet=file (gcc)
9350
9351
9352@table @asis
9353
9354@item @code{-gnatet=@emph{path}}
9355
9356Generate target dependent information. The format of the output file is
9357described in the section about switch @emph{-gnateT}.
9358@end table
9359
9360@geindex -gnateT (gcc)
9361
9362
9363@table @asis
9364
9365@item @code{-gnateT=@emph{path}}
9366
9367Read target dependent information, such as endianness or sizes and alignments
9368of base type. If this switch is passed, the default target dependent
9369information of the compiler is replaced by the one read from the input file.
9370This is used by tools other than the compiler, e.g. to do
9371semantic analysis of programs that will run on some other target than
9372the machine on which the tool is run.
9373
9374The following target dependent values should be defined,
9375where @cite{Nat} denotes a natural integer value, @cite{Pos} denotes a
9376positive integer value, and fields marked with a question mark are
9377boolean fields, where a value of 0 is False, and a value of 1 is True:
9378
9379@example
9380Bits_BE                    : Nat; -- Bits stored big-endian?
9381Bits_Per_Unit              : Pos; -- Bits in a storage unit
9382Bits_Per_Word              : Pos; -- Bits in a word
9383Bytes_BE                   : Nat; -- Bytes stored big-endian?
9384Char_Size                  : Pos; -- Standard.Character'Size
9385Double_Float_Alignment     : Nat; -- Alignment of double float
9386Double_Scalar_Alignment    : Nat; -- Alignment of double length scalar
9387Double_Size                : Pos; -- Standard.Long_Float'Size
9388Float_Size                 : Pos; -- Standard.Float'Size
9389Float_Words_BE             : Nat; -- Float words stored big-endian?
9390Int_Size                   : Pos; -- Standard.Integer'Size
9391Long_Double_Size           : Pos; -- Standard.Long_Long_Float'Size
9392Long_Long_Size             : Pos; -- Standard.Long_Long_Integer'Size
9393Long_Size                  : Pos; -- Standard.Long_Integer'Size
9394Maximum_Alignment          : Pos; -- Maximum permitted alignment
9395Max_Unaligned_Field        : Pos; -- Maximum size for unaligned bit field
9396Pointer_Size               : Pos; -- System.Address'Size
9397Short_Enums                : Nat; -- Short foreign convention enums?
9398Short_Size                 : Pos; -- Standard.Short_Integer'Size
9399Strict_Alignment           : Nat; -- Strict alignment?
9400System_Allocator_Alignment : Nat; -- Alignment for malloc calls
9401Wchar_T_Size               : Pos; -- Interfaces.C.wchar_t'Size
9402Words_BE                   : Nat; -- Words stored big-endian?
9403@end example
9404
9405The format of the input file is as follows. First come the values of
9406the variables defined above, with one line per value:
9407
9408@example
9409name  value
9410@end example
9411
9412where @cite{name} is the name of the parameter, spelled out in full,
9413and cased as in the above list, and @cite{value} is an unsigned decimal
9414integer. Two or more blanks separates the name from the value.
9415
9416All the variables must be present, in alphabetical order (i.e. the
9417same order as the list above).
9418
9419Then there is a blank line to separate the two parts of the file. Then
9420come the lines showing the floating-point types to be registered, with
9421one line per registered mode:
9422
9423@example
9424name  digs float_rep size alignment
9425@end example
9426
9427where @cite{name} is the string name of the type (which can have
9428single spaces embedded in the name (e.g. long double), @cite{digs} is
9429the number of digits for the floating-point type, @cite{float_rep} is
9430the float representation (I/V/A for IEEE-754-Binary, Vax_Native,
9431AAMP), @cite{size} is the size in bits, @cite{alignment} is the
9432alignment in bits. The name is followed by at least two blanks, fields
9433are separated by at least one blank, and a LF character immediately
9434follows the alignment field.
9435
9436Here is an example of a target parameterization file:
9437
9438@example
9439Bits_BE                       0
9440Bits_Per_Unit                 8
9441Bits_Per_Word                64
9442Bytes_BE                      0
9443Char_Size                     8
9444Double_Float_Alignment        0
9445Double_Scalar_Alignment       0
9446Double_Size                  64
9447Float_Size                   32
9448Float_Words_BE                0
9449Int_Size                     64
9450Long_Double_Size            128
9451Long_Long_Size               64
9452Long_Size                    64
9453Maximum_Alignment            16
9454Max_Unaligned_Field          64
9455Pointer_Size                 64
9456Short_Size                   16
9457Strict_Alignment              0
9458System_Allocator_Alignment   16
9459Wchar_T_Size                 32
9460Words_BE                      0
9461
9462float         15  I  64  64
9463double        15  I  64  64
9464long double   18  I  80 128
9465TF            33  I 128 128
9466@end example
9467@end table
9468
9469@geindex -gnateu (gcc)
9470
9471
9472@table @asis
9473
9474@item @code{-gnateu}
9475
9476Ignore unrecognized validity, warning, and style switches that
9477appear after this switch is given. This may be useful when
9478compiling sources developed on a later version of the compiler
9479with an earlier version. Of course the earlier version must
9480support this switch.
9481@end table
9482
9483@geindex -gnateV (gcc)
9484
9485
9486@table @asis
9487
9488@item @code{-gnateV}
9489
9490Check that all actual parameters of a subprogram call are valid according to
9491the rules of validity checking (@ref{fe,,Validity Checking}).
9492@end table
9493
9494@geindex -gnateY (gcc)
9495
9496
9497@table @asis
9498
9499@item @code{-gnateY}
9500
9501Ignore all STYLE_CHECKS pragmas. Full legality checks
9502are still carried out, but the pragmas have no effect
9503on what style checks are active. This allows all style
9504checking options to be controlled from the command line.
9505@end table
9506
9507@geindex -gnatE (gcc)
9508
9509
9510@table @asis
9511
9512@item @code{-gnatE}
9513
9514Full dynamic elaboration checks.
9515@end table
9516
9517@geindex -gnatf (gcc)
9518
9519
9520@table @asis
9521
9522@item @code{-gnatf}
9523
9524Full errors. Multiple errors per line, all undefined references, do not
9525attempt to suppress cascaded errors.
9526@end table
9527
9528@geindex -gnatF (gcc)
9529
9530
9531@table @asis
9532
9533@item @code{-gnatF}
9534
9535Externals names are folded to all uppercase.
9536@end table
9537
9538@geindex -gnatg (gcc)
9539
9540
9541@table @asis
9542
9543@item @code{-gnatg}
9544
9545Internal GNAT implementation mode. This should not be used for
9546applications programs, it is intended only for use by the compiler
9547and its run-time library. For documentation, see the GNAT sources.
9548Note that @emph{-gnatg} implies
9549@emph{-gnatw.ge} and
9550@emph{-gnatyg}
9551so that all standard warnings and all standard style options are turned on.
9552All warnings and style messages are treated as errors.
9553@end table
9554
9555@geindex -gnatG[nn] (gcc)
9556
9557
9558@table @asis
9559
9560@item @code{-gnatG=nn}
9561
9562List generated expanded code in source form.
9563@end table
9564
9565@geindex -gnath (gcc)
9566
9567
9568@table @asis
9569
9570@item @code{-gnath}
9571
9572Output usage information. The output is written to @code{stdout}.
9573@end table
9574
9575@geindex -gnati (gcc)
9576
9577
9578@table @asis
9579
9580@item @code{-gnati@emph{c}}
9581
9582Identifier character set (@cite{c} = 1/2/3/4/8/9/p/f/n/w).
9583For details of the possible selections for @cite{c},
9584see @ref{4a,,Character Set Control}.
9585@end table
9586
9587@geindex -gnatI (gcc)
9588
9589
9590@table @asis
9591
9592@item @code{-gnatI}
9593
9594Ignore representation clauses. When this switch is used,
9595representation clauses are treated as comments. This is useful
9596when initially porting code where you want to ignore rep clause
9597problems, and also for compiling foreign code (particularly
9598for use with ASIS). The representation clauses that are ignored
9599are: enumeration_representation_clause, record_representation_clause,
9600and attribute_definition_clause for the following attributes:
9601Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
9602Object_Size, Size, Small, Stream_Size, and Value_Size.
9603Note that this option should be used only for compiling -- the
9604code is likely to malfunction at run time.
9605
9606Note that when @cite{-gnatct} is used to generate trees for input
9607into @cite{ASIS} tools, these representation clauses are removed
9608from the tree and ignored. This means that the tool will not see them.
9609@end table
9610
9611@geindex -gnatjnn (gcc)
9612
9613
9614@table @asis
9615
9616@item @code{-gnatj@emph{nn}}
9617
9618Reformat error messages to fit on @cite{nn} character lines
9619@end table
9620
9621@geindex -gnatk (gcc)
9622
9623
9624@table @asis
9625
9626@item @code{-gnatk=@emph{n}}
9627
9628Limit file names to @cite{n} (1-999) characters (@cite{k} = krunch).
9629@end table
9630
9631@geindex -gnatl (gcc)
9632
9633
9634@table @asis
9635
9636@item @code{-gnatl}
9637
9638Output full source listing with embedded error messages.
9639@end table
9640
9641@geindex -gnatL (gcc)
9642
9643
9644@table @asis
9645
9646@item @code{-gnatL}
9647
9648Used in conjunction with -gnatG or -gnatD to intersperse original
9649source lines (as comment lines with line numbers) in the expanded
9650source output.
9651@end table
9652
9653@geindex -gnatm (gcc)
9654
9655
9656@table @asis
9657
9658@item @code{-gnatm=@emph{n}}
9659
9660Limit number of detected error or warning messages to @cite{n}
9661where @cite{n} is in the range 1..999999. The default setting if
9662no switch is given is 9999. If the number of warnings reaches this
9663limit, then a message is output and further warnings are suppressed,
9664but the compilation is continued. If the number of error messages
9665reaches this limit, then a message is output and the compilation
9666is abandoned. The equal sign here is optional. A value of zero
9667means that no limit applies.
9668@end table
9669
9670@geindex -gnatn (gcc)
9671
9672
9673@table @asis
9674
9675@item @code{-gnatn[12]}
9676
9677Activate inlining for subprograms for which pragma @cite{Inline} is
9678specified. This inlining is performed by the GCC back-end. An optional
9679digit sets the inlining level: 1 for moderate inlining across modules
9680or 2 for full inlining across modules. If no inlining level is specified,
9681the compiler will pick it based on the optimization level.
9682@end table
9683
9684@geindex -gnatN (gcc)
9685
9686
9687@table @asis
9688
9689@item @code{-gnatN}
9690
9691Activate front end inlining for subprograms for which
9692pragma @cite{Inline} is specified. This inlining is performed
9693by the front end and will be visible in the
9694@emph{-gnatG} output.
9695
9696When using a gcc-based back end (in practice this means using any version
9697of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
9698@emph{-gnatN} is deprecated, and the use of @emph{-gnatn} is preferred.
9699Historically front end inlining was more extensive than the gcc back end
9700inlining, but that is no longer the case.
9701@end table
9702
9703@geindex -gnato0 (gcc)
9704
9705
9706@table @asis
9707
9708@item @code{-gnato0}
9709
9710Suppresses overflow checking. This causes the behavior of the compiler to
9711match the default for older versions where overflow checking was suppressed
9712by default. This is equivalent to having
9713@cite{pragma Suppress (Overflow_Mode)} in a configuration pragma file.
9714@end table
9715
9716@geindex -gnato?? (gcc)
9717
9718
9719@table @asis
9720
9721@item @code{-gnato??}
9722
9723Set default mode for handling generation of code to avoid intermediate
9724arithmetic overflow. Here @cite{??} is two digits, a
9725single digit, or nothing. Each digit is one of the digits @cite{1}
9726through @cite{3}:
9727
9728
9729@multitable {xxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
9730@item
9731
9732Digit
9733
9734@tab
9735
9736Interpretation
9737
9738@item
9739
9740@emph{1}
9741
9742@tab
9743
9744All intermediate overflows checked against base type (@cite{STRICT})
9745
9746@item
9747
9748@emph{2}
9749
9750@tab
9751
9752Minimize intermediate overflows (@cite{MINIMIZED})
9753
9754@item
9755
9756@emph{3}
9757
9758@tab
9759
9760Eliminate intermediate overflows (@cite{ELIMINATED})
9761
9762@end multitable
9763
9764
9765If only one digit appears, then it applies to all
9766cases; if two digits are given, then the first applies outside
9767assertions, pre/postconditions, and type invariants, and the second
9768applies within assertions, pre/postconditions, and type invariants.
9769
9770If no digits follow the @emph{-gnato}, then it is equivalent to
9771@emph{-gnato11},
9772causing all intermediate overflows to be handled in strict
9773mode.
9774
9775This switch also causes arithmetic overflow checking to be performed
9776(as though @cite{pragma Unsuppress (Overflow_Mode)} had been specified).
9777
9778The default if no option @emph{-gnato} is given is that overflow handling
9779is in @cite{STRICT} mode (computations done using the base type), and that
9780overflow checking is enabled.
9781
9782Note that division by zero is a separate check that is not
9783controlled by this switch (divide-by-zero checking is on by default).
9784
9785See also @ref{100,,Specifying the Desired Mode}.
9786@end table
9787
9788@geindex -gnatp (gcc)
9789
9790
9791@table @asis
9792
9793@item @code{-gnatp}
9794
9795Suppress all checks. See @ref{101,,Run-Time Checks} for details. This switch
9796has no effect if cancelled by a subsequent @emph{-gnat-p} switch.
9797@end table
9798
9799@geindex -gnat-p (gcc)
9800
9801
9802@table @asis
9803
9804@item @code{-gnat-p}
9805
9806Cancel effect of previous @emph{-gnatp} switch.
9807@end table
9808
9809@geindex -gnatP (gcc)
9810
9811
9812@table @asis
9813
9814@item @code{-gnatP}
9815
9816Enable polling. This is required on some systems (notably Windows NT) to
9817obtain asynchronous abort and asynchronous transfer of control capability.
9818See @cite{Pragma_Polling} in the @cite{GNAT_Reference_Manual} for full
9819details.
9820@end table
9821
9822@geindex -gnatq (gcc)
9823
9824
9825@table @asis
9826
9827@item @code{-gnatq}
9828
9829Don't quit. Try semantics, even if parse errors.
9830@end table
9831
9832@geindex -gnatQ (gcc)
9833
9834
9835@table @asis
9836
9837@item @code{-gnatQ}
9838
9839Don't quit. Generate @code{ALI} and tree files even if illegalities.
9840Note that code generation is still suppressed in the presence of any
9841errors, so even with @emph{-gnatQ} no object file is generated.
9842@end table
9843
9844@geindex -gnatr (gcc)
9845
9846
9847@table @asis
9848
9849@item @code{-gnatr}
9850
9851Treat pragma Restrictions as Restriction_Warnings.
9852@end table
9853
9854@geindex -gnatR (gcc)
9855
9856
9857@table @asis
9858
9859@item @code{-gnatR[0/1/2/3[s]]}
9860
9861Output representation information for declared types and objects.
9862Note that this switch is not allowed if a previous @cite{-gnatD} switch has
9863been given, since these two switches are not compatible.
9864
9865@item @code{-gnatRm[s]}
9866
9867Output convention and parameter passing mechanisms for all subprograms.
9868@end table
9869
9870@geindex -gnats (gcc)
9871
9872
9873@table @asis
9874
9875@item @code{-gnats}
9876
9877Syntax check only.
9878@end table
9879
9880@geindex -gnatS (gcc)
9881
9882
9883@table @asis
9884
9885@item @code{-gnatS}
9886
9887Print package Standard.
9888@end table
9889
9890@geindex -gnatt (gcc)
9891
9892
9893@table @asis
9894
9895@item @code{-gnatt}
9896
9897Generate tree output file.
9898@end table
9899
9900@geindex -gnatT (gcc)
9901
9902
9903@table @asis
9904
9905@item @code{-gnatT@emph{nnn}}
9906
9907All compiler tables start at @cite{nnn} times usual starting size.
9908@end table
9909
9910@geindex -gnatu (gcc)
9911
9912
9913@table @asis
9914
9915@item @code{-gnatu}
9916
9917List units for this compilation.
9918@end table
9919
9920@geindex -gnatU (gcc)
9921
9922
9923@table @asis
9924
9925@item @code{-gnatU}
9926
9927Tag all error messages with the unique string 'error:'
9928@end table
9929
9930@geindex -gnatv (gcc)
9931
9932
9933@table @asis
9934
9935@item @code{-gnatv}
9936
9937Verbose mode. Full error output with source lines to @code{stdout}.
9938@end table
9939
9940@geindex -gnatV (gcc)
9941
9942
9943@table @asis
9944
9945@item @code{-gnatV}
9946
9947Control level of validity checking (@ref{fe,,Validity Checking}).
9948@end table
9949
9950@geindex -gnatw (gcc)
9951
9952
9953@table @asis
9954
9955@item @code{-gnatw@emph{xxx}}
9956
9957Warning mode where
9958@cite{xxx} is a string of option letters that denotes
9959the exact warnings that
9960are enabled or disabled (@ref{102,,Warning Message Control}).
9961@end table
9962
9963@geindex -gnatW (gcc)
9964
9965
9966@table @asis
9967
9968@item @code{-gnatW@emph{e}}
9969
9970Wide character encoding method
9971(@cite{e}=n/h/u/s/e/8).
9972@end table
9973
9974@geindex -gnatx (gcc)
9975
9976
9977@table @asis
9978
9979@item @code{-gnatx}
9980
9981Suppress generation of cross-reference information.
9982@end table
9983
9984@geindex -gnatX (gcc)
9985
9986
9987@table @asis
9988
9989@item @code{-gnatX}
9990
9991Enable GNAT implementation extensions and latest Ada version.
9992@end table
9993
9994@geindex -gnaty (gcc)
9995
9996
9997@table @asis
9998
9999@item @code{-gnaty}
10000
10001Enable built-in style checks (@ref{103,,Style Checking}).
10002@end table
10003
10004@geindex -gnatz (gcc)
10005
10006
10007@table @asis
10008
10009@item @code{-gnatz@emph{m}}
10010
10011Distribution stub generation and compilation
10012(@cite{m}=r/c for receiver/caller stubs).
10013@end table
10014
10015@geindex -I (gcc)
10016
10017
10018@table @asis
10019
10020@item @code{-I@emph{dir}}
10021
10022@geindex RTL
10023
10024Direct GNAT to search the @cite{dir} directory for source files needed by
10025the current compilation
10026(see @ref{8e,,Search Paths and the Run-Time Library (RTL)}).
10027@end table
10028
10029@geindex -I- (gcc)
10030
10031
10032@table @asis
10033
10034@item @code{-I-}
10035
10036@geindex RTL
10037
10038Except for the source file named in the command line, do not look for source
10039files in the directory containing the source file named in the command line
10040(see @ref{8e,,Search Paths and the Run-Time Library (RTL)}).
10041@end table
10042
10043@geindex -o (gcc)
10044
10045
10046@table @asis
10047
10048@item @code{-o @emph{file}}
10049
10050This switch is used in @emph{gcc} to redirect the generated object file
10051and its associated ALI file. Beware of this switch with GNAT, because it may
10052cause the object file and ALI file to have different names which in turn
10053may confuse the binder and the linker.
10054@end table
10055
10056@geindex -nostdinc (gcc)
10057
10058
10059@table @asis
10060
10061@item @code{-nostdinc}
10062
10063Inhibit the search of the default location for the GNAT Run Time
10064Library (RTL) source files.
10065@end table
10066
10067@geindex -nostdlib (gcc)
10068
10069
10070@table @asis
10071
10072@item @code{-nostdlib}
10073
10074Inhibit the search of the default location for the GNAT Run Time
10075Library (RTL) ALI files.
10076@end table
10077
10078@geindex -O (gcc)
10079
10080
10081@table @asis
10082
10083@item @code{-O[@emph{n}]}
10084
10085@cite{n} controls the optimization level:
10086
10087
10088@multitable {xxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
10089@item
10090
10091@emph{n}
10092
10093@tab
10094
10095Effect
10096
10097@item
10098
10099@emph{0}
10100
10101@tab
10102
10103No optimization, the default setting if no @emph{-O} appears
10104
10105@item
10106
10107@emph{1}
10108
10109@tab
10110
10111Normal optimization, the default if you specify @emph{-O} without an
10112operand. A good compromise between code quality and compilation
10113time.
10114
10115@item
10116
10117@emph{2}
10118
10119@tab
10120
10121Extensive optimization, may improve execution time, possibly at
10122the cost of substantially increased compilation time.
10123
10124@item
10125
10126@emph{3}
10127
10128@tab
10129
10130Same as @emph{-O2}, and also includes inline expansion for small
10131subprograms in the same unit.
10132
10133@item
10134
10135@emph{s}
10136
10137@tab
10138
10139Optimize space usage
10140
10141@end multitable
10142
10143
10144See also @ref{104,,Optimization Levels}.
10145@end table
10146
10147@geindex -pass-exit-codes (gcc)
10148
10149
10150@table @asis
10151
10152@item @code{-pass-exit-codes}
10153
10154Catch exit codes from the compiler and use the most meaningful as
10155exit status.
10156@end table
10157
10158@geindex --RTS (gcc)
10159
10160
10161@table @asis
10162
10163@item @code{--RTS=@emph{rts-path}}
10164
10165Specifies the default location of the runtime library. Same meaning as the
10166equivalent @emph{gnatmake} flag (@ref{e2,,Switches for gnatmake}).
10167@end table
10168
10169@geindex -S (gcc)
10170
10171
10172@table @asis
10173
10174@item @code{-S}
10175
10176Used in place of @emph{-c} to
10177cause the assembler source file to be
10178generated, using @code{.s} as the extension,
10179instead of the object file.
10180This may be useful if you need to examine the generated assembly code.
10181@end table
10182
10183@geindex -fverbose-asm (gcc)
10184
10185
10186@table @asis
10187
10188@item @code{-fverbose-asm}
10189
10190Used in conjunction with @emph{-S}
10191to cause the generated assembly code file to be annotated with variable
10192names, making it significantly easier to follow.
10193@end table
10194
10195@geindex -v (gcc)
10196
10197
10198@table @asis
10199
10200@item @code{-v}
10201
10202Show commands generated by the @emph{gcc} driver. Normally used only for
10203debugging purposes or if you need to be sure what version of the
10204compiler you are executing.
10205@end table
10206
10207@geindex -V (gcc)
10208
10209
10210@table @asis
10211
10212@item @code{-V @emph{ver}}
10213
10214Execute @cite{ver} version of the compiler. This is the @emph{gcc}
10215version, not the GNAT version.
10216@end table
10217
10218@geindex -w (gcc)
10219
10220
10221@table @asis
10222
10223@item @code{-w}
10224
10225Turn off warnings generated by the back end of the compiler. Use of
10226this switch also causes the default for front end warnings to be set
10227to suppress (as though @emph{-gnatws} had appeared at the start of
10228the options).
10229@end table
10230
10231@geindex Combining GNAT switches
10232
10233You may combine a sequence of GNAT switches into a single switch. For
10234example, the combined switch
10235
10236@quotation
10237
10238@example
10239-gnatofi3
10240@end example
10241@end quotation
10242
10243is equivalent to specifying the following sequence of switches:
10244
10245@quotation
10246
10247@example
10248-gnato -gnatf -gnati3
10249@end example
10250@end quotation
10251
10252The following restrictions apply to the combination of switches
10253in this manner:
10254
10255
10256@itemize *
10257
10258@item
10259The switch @emph{-gnatc} if combined with other switches must come
10260first in the string.
10261
10262@item
10263The switch @emph{-gnats} if combined with other switches must come
10264first in the string.
10265
10266@item
10267The switches
10268@emph{-gnatzc} and @emph{-gnatzr} may not be combined with any other
10269switches, and only one of them may appear in the command line.
10270
10271@item
10272The switch @emph{-gnat-p} may not be combined with any other switch.
10273
10274@item
10275Once a 'y' appears in the string (that is a use of the @emph{-gnaty}
10276switch), then all further characters in the switch are interpreted
10277as style modifiers (see description of @emph{-gnaty}).
10278
10279@item
10280Once a 'd' appears in the string (that is a use of the @emph{-gnatd}
10281switch), then all further characters in the switch are interpreted
10282as debug flags (see description of @emph{-gnatd}).
10283
10284@item
10285Once a 'w' appears in the string (that is a use of the @emph{-gnatw}
10286switch), then all further characters in the switch are interpreted
10287as warning mode modifiers (see description of @emph{-gnatw}).
10288
10289@item
10290Once a 'V' appears in the string (that is a use of the @emph{-gnatV}
10291switch), then all further characters in the switch are interpreted
10292as validity checking options (@ref{fe,,Validity Checking}).
10293
10294@item
10295Option 'em', 'ec', 'ep', 'l=' and 'R' must be the last options in
10296a combined list of options.
10297@end itemize
10298
10299@node Output and Error Message Control,Warning Message Control,Alphabetical List of All Switches,Compiler Switches
10300@anchor{gnat_ugn/building_executable_programs_with_gnat id14}@anchor{105}@anchor{gnat_ugn/building_executable_programs_with_gnat output-and-error-message-control}@anchor{106}
10301@subsection Output and Error Message Control
10302
10303
10304@geindex stderr
10305
10306The standard default format for error messages is called 'brief format'.
10307Brief format messages are written to @code{stderr} (the standard error
10308file) and have the following form:
10309
10310@example
10311e.adb:3:04: Incorrect spelling of keyword "function"
10312e.adb:4:20: ";" should be "is"
10313@end example
10314
10315The first integer after the file name is the line number in the file,
10316and the second integer is the column number within the line.
10317@cite{GPS} can parse the error messages
10318and point to the referenced character.
10319The following switches provide control over the error message
10320format:
10321
10322@geindex -gnatv (gcc)
10323
10324
10325@table @asis
10326
10327@item @code{-gnatv}
10328
10329The @cite{v} stands for verbose.
10330The effect of this setting is to write long-format error
10331messages to @code{stdout} (the standard output file.
10332The same program compiled with the
10333@emph{-gnatv} switch would generate:
10334
10335@example
103363. funcion X (Q : Integer)
10337   |
10338>>> Incorrect spelling of keyword "function"
103394. return Integer;
10340                 |
10341>>> ";" should be "is"
10342@end example
10343
10344The vertical bar indicates the location of the error, and the @code{>>>}
10345prefix can be used to search for error messages. When this switch is
10346used the only source lines output are those with errors.
10347@end table
10348
10349@geindex -gnatl (gcc)
10350
10351
10352@table @asis
10353
10354@item @code{-gnatl}
10355
10356The @cite{l} stands for list.
10357This switch causes a full listing of
10358the file to be generated. In the case where a body is
10359compiled, the corresponding spec is also listed, along
10360with any subunits. Typical output from compiling a package
10361body @code{p.adb} might look like:
10362
10363@example
10364Compiling: p.adb
10365
10366     1. package body p is
10367     2.    procedure a;
10368     3.    procedure a is separate;
10369     4. begin
10370     5.    null
10371               |
10372        >>> missing ";"
10373
10374     6. end;
10375
10376Compiling: p.ads
10377
10378     1. package p is
10379     2.    pragma Elaborate_Body
10380                                |
10381        >>> missing ";"
10382
10383     3. end p;
10384
10385Compiling: p-a.adb
10386
10387     1. separate p
10388                |
10389        >>> missing "("
10390
10391     2. procedure a is
10392     3. begin
10393     4.    null
10394               |
10395        >>> missing ";"
10396
10397     5. end;
10398@end example
10399
10400When you specify the @emph{-gnatv} or @emph{-gnatl} switches and
10401standard output is redirected, a brief summary is written to
10402@code{stderr} (standard error) giving the number of error messages and
10403warning messages generated.
10404@end table
10405
10406@geindex -gnatl=fname (gcc)
10407
10408
10409@table @asis
10410
10411@item @code{-gnatl=@emph{fname}}
10412
10413This has the same effect as @emph{-gnatl} except that the output is
10414written to a file instead of to standard output. If the given name
10415@code{fname} does not start with a period, then it is the full name
10416of the file to be written. If @code{fname} is an extension, it is
10417appended to the name of the file being compiled. For example, if
10418file @code{xyz.adb} is compiled with @emph{-gnatl=.lst},
10419then the output is written to file xyz.adb.lst.
10420@end table
10421
10422@geindex -gnatU (gcc)
10423
10424
10425@table @asis
10426
10427@item @code{-gnatU}
10428
10429This switch forces all error messages to be preceded by the unique
10430string 'error:'. This means that error messages take a few more
10431characters in space, but allows easy searching for and identification
10432of error messages.
10433@end table
10434
10435@geindex -gnatb (gcc)
10436
10437
10438@table @asis
10439
10440@item @code{-gnatb}
10441
10442The @cite{b} stands for brief.
10443This switch causes GNAT to generate the
10444brief format error messages to @code{stderr} (the standard error
10445file) as well as the verbose
10446format message or full listing (which as usual is written to
10447@code{stdout} (the standard output file).
10448@end table
10449
10450@geindex -gnatm (gcc)
10451
10452
10453@table @asis
10454
10455@item @code{-gnatm=@emph{n}}
10456
10457The @cite{m} stands for maximum.
10458@cite{n} is a decimal integer in the
10459range of 1 to 999999 and limits the number of error or warning
10460messages to be generated. For example, using
10461@emph{-gnatm2} might yield
10462
10463@example
10464e.adb:3:04: Incorrect spelling of keyword "function"
10465e.adb:5:35: missing ".."
10466fatal error: maximum number of errors detected
10467compilation abandoned
10468@end example
10469
10470The default setting if
10471no switch is given is 9999. If the number of warnings reaches this
10472limit, then a message is output and further warnings are suppressed,
10473but the compilation is continued. If the number of error messages
10474reaches this limit, then a message is output and the compilation
10475is abandoned. A value of zero means that no limit applies.
10476
10477Note that the equal sign is optional, so the switches
10478@emph{-gnatm2} and @emph{-gnatm=2} are equivalent.
10479@end table
10480
10481@geindex -gnatf (gcc)
10482
10483
10484@table @asis
10485
10486@item @code{-gnatf}
10487
10488@geindex Error messages
10489@geindex suppressing
10490
10491The @cite{f} stands for full.
10492Normally, the compiler suppresses error messages that are likely to be
10493redundant. This switch causes all error
10494messages to be generated. In particular, in the case of
10495references to undefined variables. If a given variable is referenced
10496several times, the normal format of messages is
10497
10498@example
10499e.adb:7:07: "V" is undefined (more references follow)
10500@end example
10501
10502where the parenthetical comment warns that there are additional
10503references to the variable @cite{V}. Compiling the same program with the
10504@emph{-gnatf} switch yields
10505
10506@example
10507e.adb:7:07: "V" is undefined
10508e.adb:8:07: "V" is undefined
10509e.adb:8:12: "V" is undefined
10510e.adb:8:16: "V" is undefined
10511e.adb:9:07: "V" is undefined
10512e.adb:9:12: "V" is undefined
10513@end example
10514
10515The @emph{-gnatf} switch also generates additional information for
10516some error messages.  Some examples are:
10517
10518
10519@itemize *
10520
10521@item
10522Details on possibly non-portable unchecked conversion
10523
10524@item
10525List possible interpretations for ambiguous calls
10526
10527@item
10528Additional details on incorrect parameters
10529@end itemize
10530@end table
10531
10532@geindex -gnatjnn (gcc)
10533
10534
10535@table @asis
10536
10537@item @code{-gnatjnn}
10538
10539In normal operation mode (or if @emph{-gnatj0} is used), then error messages
10540with continuation lines are treated as though the continuation lines were
10541separate messages (and so a warning with two continuation lines counts as
10542three warnings, and is listed as three separate messages).
10543
10544If the @emph{-gnatjnn} switch is used with a positive value for nn, then
10545messages are output in a different manner. A message and all its continuation
10546lines are treated as a unit, and count as only one warning or message in the
10547statistics totals. Furthermore, the message is reformatted so that no line
10548is longer than nn characters.
10549@end table
10550
10551@geindex -gnatq (gcc)
10552
10553
10554@table @asis
10555
10556@item @code{-gnatq}
10557
10558The @cite{q} stands for quit (really 'don't quit').
10559In normal operation mode, the compiler first parses the program and
10560determines if there are any syntax errors. If there are, appropriate
10561error messages are generated and compilation is immediately terminated.
10562This switch tells
10563GNAT to continue with semantic analysis even if syntax errors have been
10564found. This may enable the detection of more errors in a single run. On
10565the other hand, the semantic analyzer is more likely to encounter some
10566internal fatal error when given a syntactically invalid tree.
10567@end table
10568
10569@geindex -gnatQ (gcc)
10570
10571
10572@table @asis
10573
10574@item @code{-gnatQ}
10575
10576In normal operation mode, the @code{ALI} file is not generated if any
10577illegalities are detected in the program. The use of @emph{-gnatQ} forces
10578generation of the @code{ALI} file. This file is marked as being in
10579error, so it cannot be used for binding purposes, but it does contain
10580reasonably complete cross-reference information, and thus may be useful
10581for use by tools (e.g., semantic browsing tools or integrated development
10582environments) that are driven from the @code{ALI} file. This switch
10583implies @emph{-gnatq}, since the semantic phase must be run to get a
10584meaningful ALI file.
10585
10586In addition, if @emph{-gnatt} is also specified, then the tree file is
10587generated even if there are illegalities. It may be useful in this case
10588to also specify @emph{-gnatq} to ensure that full semantic processing
10589occurs. The resulting tree file can be processed by ASIS, for the purpose
10590of providing partial information about illegal units, but if the error
10591causes the tree to be badly malformed, then ASIS may crash during the
10592analysis.
10593
10594When @emph{-gnatQ} is used and the generated @code{ALI} file is marked as
10595being in error, @emph{gnatmake} will attempt to recompile the source when it
10596finds such an @code{ALI} file, including with switch @emph{-gnatc}.
10597
10598Note that @emph{-gnatQ} has no effect if @emph{-gnats} is specified,
10599since ALI files are never generated if @emph{-gnats} is set.
10600@end table
10601
10602@node Warning Message Control,Debugging and Assertion Control,Output and Error Message Control,Compiler Switches
10603@anchor{gnat_ugn/building_executable_programs_with_gnat warning-message-control}@anchor{102}@anchor{gnat_ugn/building_executable_programs_with_gnat id15}@anchor{107}
10604@subsection Warning Message Control
10605
10606
10607@geindex Warning messages
10608
10609In addition to error messages, which correspond to illegalities as defined
10610in the Ada Reference Manual, the compiler detects two kinds of warning
10611situations.
10612
10613First, the compiler considers some constructs suspicious and generates a
10614warning message to alert you to a possible error. Second, if the
10615compiler detects a situation that is sure to raise an exception at
10616run time, it generates a warning message. The following shows an example
10617of warning messages:
10618
10619@example
10620e.adb:4:24: warning: creation of object may raise Storage_Error
10621e.adb:10:17: warning: static value out of range
10622e.adb:10:17: warning: "Constraint_Error" will be raised at run time
10623@end example
10624
10625GNAT considers a large number of situations as appropriate
10626for the generation of warning messages. As always, warnings are not
10627definite indications of errors. For example, if you do an out-of-range
10628assignment with the deliberate intention of raising a
10629@cite{Constraint_Error} exception, then the warning that may be
10630issued does not indicate an error. Some of the situations for which GNAT
10631issues warnings (at least some of the time) are given in the following
10632list. This list is not complete, and new warnings are often added to
10633subsequent versions of GNAT. The list is intended to give a general idea
10634of the kinds of warnings that are generated.
10635
10636
10637@itemize *
10638
10639@item
10640Possible infinitely recursive calls
10641
10642@item
10643Out-of-range values being assigned
10644
10645@item
10646Possible order of elaboration problems
10647
10648@item
10649Size not a multiple of alignment for a record type
10650
10651@item
10652Assertions (pragma Assert) that are sure to fail
10653
10654@item
10655Unreachable code
10656
10657@item
10658Address clauses with possibly unaligned values, or where an attempt is
10659made to overlay a smaller variable with a larger one.
10660
10661@item
10662Fixed-point type declarations with a null range
10663
10664@item
10665Direct_IO or Sequential_IO instantiated with a type that has access values
10666
10667@item
10668Variables that are never assigned a value
10669
10670@item
10671Variables that are referenced before being initialized
10672
10673@item
10674Task entries with no corresponding @cite{accept} statement
10675
10676@item
10677Duplicate accepts for the same task entry in a @cite{select}
10678
10679@item
10680Objects that take too much storage
10681
10682@item
10683Unchecked conversion between types of differing sizes
10684
10685@item
10686Missing @cite{return} statement along some execution path in a function
10687
10688@item
10689Incorrect (unrecognized) pragmas
10690
10691@item
10692Incorrect external names
10693
10694@item
10695Allocation from empty storage pool
10696
10697@item
10698Potentially blocking operation in protected type
10699
10700@item
10701Suspicious parenthesization of expressions
10702
10703@item
10704Mismatching bounds in an aggregate
10705
10706@item
10707Attempt to return local value by reference
10708
10709@item
10710Premature instantiation of a generic body
10711
10712@item
10713Attempt to pack aliased components
10714
10715@item
10716Out of bounds array subscripts
10717
10718@item
10719Wrong length on string assignment
10720
10721@item
10722Violations of style rules if style checking is enabled
10723
10724@item
10725Unused @emph{with} clauses
10726
10727@item
10728@cite{Bit_Order} usage that does not have any effect
10729
10730@item
10731@cite{Standard.Duration} used to resolve universal fixed expression
10732
10733@item
10734Dereference of possibly null value
10735
10736@item
10737Declaration that is likely to cause storage error
10738
10739@item
10740Internal GNAT unit @emph{with}ed by application unit
10741
10742@item
10743Values known to be out of range at compile time
10744
10745@item
10746Unreferenced or unmodified variables. Note that a special
10747exemption applies to variables which contain any of the substrings
10748@cite{DISCARD@comma{} DUMMY@comma{} IGNORE@comma{} JUNK@comma{} UNUSED}, in any casing. Such variables
10749are considered likely to be intentionally used in a situation where
10750otherwise a warning would be given, so warnings of this kind are
10751always suppressed for such variables.
10752
10753@item
10754Address overlays that could clobber memory
10755
10756@item
10757Unexpected initialization when address clause present
10758
10759@item
10760Bad alignment for address clause
10761
10762@item
10763Useless type conversions
10764
10765@item
10766Redundant assignment statements and other redundant constructs
10767
10768@item
10769Useless exception handlers
10770
10771@item
10772Accidental hiding of name by child unit
10773
10774@item
10775Access before elaboration detected at compile time
10776
10777@item
10778A range in a @cite{for} loop that is known to be null or might be null
10779@end itemize
10780
10781The following section lists compiler switches that are available
10782to control the handling of warning messages. It is also possible
10783to exercise much finer control over what warnings are issued and
10784suppressed using the GNAT pragma Warnings (see the description
10785of the pragma in the @cite{GNAT_Reference_manual}).
10786
10787@geindex -gnatwa (gcc)
10788
10789
10790@table @asis
10791
10792@item @code{-gnatwa}
10793
10794@emph{Activate most optional warnings.}
10795
10796This switch activates most optional warning messages.  See the remaining list
10797in this section for details on optional warning messages that can be
10798individually controlled.  The warnings that are not turned on by this
10799switch are:
10800
10801
10802@itemize *
10803
10804@item
10805@code{-gnatwd} (implicit dereferencing)
10806
10807@item
10808@code{-gnatw.d} (tag warnings with -gnatw switch)
10809
10810@item
10811@code{-gnatwh} (hiding)
10812
10813@item
10814@code{-gnatw.h} (holes in record layouts)
10815
10816@item
10817@code{-gnatw.k} (redefinition of names in standard)
10818
10819@item
10820@code{-gnatwl} (elaboration warnings)
10821
10822@item
10823@code{-gnatw.l} (inherited aspects)
10824
10825@item
10826@code{-gnatw.n} (atomic synchronization)
10827
10828@item
10829@code{-gnatwo} (address clause overlay)
10830
10831@item
10832@code{-gnatw.o} (values set by out parameters ignored)
10833
10834@item
10835@code{-gnatw.s} (overridden size clause)
10836
10837@item
10838@code{-gnatwt} (tracking of deleted conditional code)
10839
10840@item
10841@code{-gnatw.u} (unordered enumeration)
10842
10843@item
10844@code{-gnatw.w} (use of Warnings Off)
10845
10846@item
10847@code{-gnatw.y} (reasons for package needing body)
10848@end itemize
10849
10850All other optional warnings are turned on.
10851@end table
10852
10853@geindex -gnatwA (gcc)
10854
10855
10856@table @asis
10857
10858@item @code{-gnatwA}
10859
10860@emph{Suppress all optional errors.}
10861
10862This switch suppresses all optional warning messages, see remaining list
10863in this section for details on optional warning messages that can be
10864individually controlled. Note that unlike switch @emph{-gnatws}, the
10865use of switch @emph{-gnatwA} does not suppress warnings that are
10866normally given unconditionally and cannot be individually controlled
10867(for example, the warning about a missing exit path in a function).
10868Also, again unlike switch @emph{-gnatws}, warnings suppressed by
10869the use of switch @emph{-gnatwA} can be individually turned back
10870on. For example the use of switch @emph{-gnatwA} followed by
10871switch @emph{-gnatwd} will suppress all optional warnings except
10872the warnings for implicit dereferencing.
10873@end table
10874
10875@geindex -gnatw.a (gcc)
10876
10877
10878@table @asis
10879
10880@item @code{-gnatw.a}
10881
10882@emph{Activate warnings on failing assertions.}
10883
10884@geindex Assert failures
10885
10886This switch activates warnings for assertions where the compiler can tell at
10887compile time that the assertion will fail. Note that this warning is given
10888even if assertions are disabled. The default is that such warnings are
10889generated.
10890@end table
10891
10892@geindex -gnatw.A (gcc)
10893
10894
10895@table @asis
10896
10897@item @code{-gnatw.A}
10898
10899@emph{Suppress warnings on failing assertions.}
10900
10901@geindex Assert failures
10902
10903This switch suppresses warnings for assertions where the compiler can tell at
10904compile time that the assertion will fail.
10905@end table
10906
10907@geindex -gnatwb (gcc)
10908
10909
10910@table @asis
10911
10912@item @code{-gnatwb}
10913
10914@emph{Activate warnings on bad fixed values.}
10915
10916@geindex Bad fixed values
10917
10918@geindex Fixed-point Small value
10919
10920@geindex Small value
10921
10922This switch activates warnings for static fixed-point expressions whose
10923value is not an exact multiple of Small. Such values are implementation
10924dependent, since an implementation is free to choose either of the multiples
10925that surround the value. GNAT always chooses the closer one, but this is not
10926required behavior, and it is better to specify a value that is an exact
10927multiple, ensuring predictable execution. The default is that such warnings
10928are not generated.
10929@end table
10930
10931@geindex -gnatwB (gcc)
10932
10933
10934@table @asis
10935
10936@item @code{-gnatwB}
10937
10938@emph{Suppress warnings on bad fixed values.}
10939
10940This switch suppresses warnings for static fixed-point expressions whose
10941value is not an exact multiple of Small.
10942@end table
10943
10944@geindex -gnatw.b (gcc)
10945
10946
10947@table @asis
10948
10949@item @code{-gnatw.b}
10950
10951@emph{Activate warnings on biased representation.}
10952
10953@geindex Biased representation
10954
10955This switch activates warnings when a size clause, value size clause, component
10956clause, or component size clause forces the use of biased representation for an
10957integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
10958to represent 10/11). The default is that such warnings are generated.
10959@end table
10960
10961@geindex -gnatwB (gcc)
10962
10963
10964@table @asis
10965
10966@item @code{-gnatw.B}
10967
10968@emph{Suppress warnings on biased representation.}
10969
10970This switch suppresses warnings for representation clauses that force the use
10971of biased representation.
10972@end table
10973
10974@geindex -gnatwc (gcc)
10975
10976
10977@table @asis
10978
10979@item @code{-gnatwc}
10980
10981@emph{Activate warnings on conditionals.}
10982
10983@geindex Conditionals
10984@geindex constant
10985
10986This switch activates warnings for conditional expressions used in
10987tests that are known to be True or False at compile time. The default
10988is that such warnings are not generated.
10989Note that this warning does
10990not get issued for the use of boolean variables or constants whose
10991values are known at compile time, since this is a standard technique
10992for conditional compilation in Ada, and this would generate too many
10993false positive warnings.
10994
10995This warning option also activates a special test for comparisons using
10996the operators '>=' and' <='.
10997If the compiler can tell that only the equality condition is possible,
10998then it will warn that the '>' or '<' part of the test
10999is useless and that the operator could be replaced by '='.
11000An example would be comparing a @cite{Natural} variable <= 0.
11001
11002This warning option also generates warnings if
11003one or both tests is optimized away in a membership test for integer
11004values if the result can be determined at compile time. Range tests on
11005enumeration types are not included, since it is common for such tests
11006to include an end point.
11007
11008This warning can also be turned on using @emph{-gnatwa}.
11009@end table
11010
11011@geindex -gnatwC (gcc)
11012
11013
11014@table @asis
11015
11016@item @code{-gnatwC}
11017
11018@emph{Suppress warnings on conditionals.}
11019
11020This switch suppresses warnings for conditional expressions used in
11021tests that are known to be True or False at compile time.
11022@end table
11023
11024@geindex -gnatw.c (gcc)
11025
11026
11027@table @asis
11028
11029@item @code{-gnatw.c}
11030
11031@emph{Activate warnings on missing component clauses.}
11032
11033@geindex Component clause
11034@geindex missing
11035
11036This switch activates warnings for record components where a record
11037representation clause is present and has component clauses for the
11038majority, but not all, of the components. A warning is given for each
11039component for which no component clause is present.
11040@end table
11041
11042@geindex -gnatwC (gcc)
11043
11044
11045@table @asis
11046
11047@item @code{-gnatw.C}
11048
11049@emph{Suppress warnings on missing component clauses.}
11050
11051This switch suppresses warnings for record components that are
11052missing a component clause in the situation described above.
11053@end table
11054
11055@geindex -gnatwd (gcc)
11056
11057
11058@table @asis
11059
11060@item @code{-gnatwd}
11061
11062@emph{Activate warnings on implicit dereferencing.}
11063
11064If this switch is set, then the use of a prefix of an access type
11065in an indexed component, slice, or selected component without an
11066explicit @cite{.all} will generate a warning. With this warning
11067enabled, access checks occur only at points where an explicit
11068@cite{.all} appears in the source code (assuming no warnings are
11069generated as a result of this switch). The default is that such
11070warnings are not generated.
11071@end table
11072
11073@geindex -gnatwD (gcc)
11074
11075
11076@table @asis
11077
11078@item @code{-gnatwD}
11079
11080@emph{Suppress warnings on implicit dereferencing.}
11081
11082@geindex Implicit dereferencing
11083
11084@geindex Dereferencing
11085@geindex implicit
11086
11087This switch suppresses warnings for implicit dereferences in
11088indexed components, slices, and selected components.
11089@end table
11090
11091@geindex -gnatw.d (gcc)
11092
11093
11094@table @asis
11095
11096@item @code{-gnatw.d}
11097
11098@emph{Activate tagging of warning and info messages.}
11099
11100If this switch is set, then warning messages are tagged, with one of the
11101following strings:
11102
11103@quotation
11104
11105
11106@itemize -
11107
11108@item
11109@emph{[-gnatw?]}
11110Used to tag warnings controlled by the switch @emph{-gnatwx} where x
11111is a letter a-z.
11112
11113@item
11114@emph{[-gnatw.?]}
11115Used to tag warnings controlled by the switch @emph{-gnatw.x} where x
11116is a letter a-z.
11117
11118@item
11119@emph{[-gnatel]}
11120Used to tag elaboration information (info) messages generated when the
11121static model of elaboration is used and the @emph{-gnatel} switch is set.
11122
11123@item
11124@emph{[restriction warning]}
11125Used to tag warning messages for restriction violations, activated by use
11126of the pragma @emph{Restriction_Warnings}.
11127
11128@item
11129@emph{[warning-as-error]}
11130Used to tag warning messages that have been converted to error messages by
11131use of the pragma Warning_As_Error. Note that such warnings are prefixed by
11132the string "error: " rather than "warning: ".
11133
11134@item
11135@emph{[enabled by default]}
11136Used to tag all other warnings that are always given by default, unless
11137warnings are completely suppressed using pragma @emph{Warnings(Off)} or
11138the switch @emph{-gnatws}.
11139@end itemize
11140@end quotation
11141@end table
11142
11143@geindex -gnatw.d (gcc)
11144
11145
11146@table @asis
11147
11148@item @code{-gnatw.D}
11149
11150@emph{Deactivate tagging of warning and info messages messages.}
11151
11152If this switch is set, then warning messages return to the default
11153mode in which warnings and info messages are not tagged as described above for
11154@cite{-gnatw.d}.
11155@end table
11156
11157@geindex -gnatwe (gcc)
11158
11159@geindex Warnings
11160@geindex treat as error
11161
11162
11163@table @asis
11164
11165@item @code{-gnatwe}
11166
11167@emph{Treat warnings and style checks as errors.}
11168
11169This switch causes warning messages and style check messages to be
11170treated as errors.
11171The warning string still appears, but the warning messages are counted
11172as errors, and prevent the generation of an object file. Note that this
11173is the only -gnatw switch that affects the handling of style check messages.
11174Note also that this switch has no effect on info (information) messages, which
11175are not treated as errors if this switch is present.
11176@end table
11177
11178@geindex -gnatw.e (gcc)
11179
11180
11181@table @asis
11182
11183@item @code{-gnatw.e}
11184
11185@emph{Activate every optional warning.}
11186
11187@geindex Warnings
11188@geindex activate every optional warning
11189
11190This switch activates all optional warnings, including those which
11191are not activated by @cite{-gnatwa}. The use of this switch is not
11192recommended for normal use. If you turn this switch on, it is almost
11193certain that you will get large numbers of useless warnings. The
11194warnings that are excluded from @cite{-gnatwa} are typically highly
11195specialized warnings that are suitable for use only in code that has
11196been specifically designed according to specialized coding rules.
11197@end table
11198
11199@geindex -gnatwf (gcc)
11200
11201
11202@table @asis
11203
11204@item @code{-gnatwf}
11205
11206@emph{Activate warnings on unreferenced formals.}
11207
11208@geindex Formals
11209@geindex unreferenced
11210
11211This switch causes a warning to be generated if a formal parameter
11212is not referenced in the body of the subprogram. This warning can
11213also be turned on using @emph{-gnatwu}. The
11214default is that these warnings are not generated.
11215@end table
11216
11217@geindex -gnatwF (gcc)
11218
11219
11220@table @asis
11221
11222@item @code{-gnatwF}
11223
11224@emph{Suppress warnings on unreferenced formals.}
11225
11226This switch suppresses warnings for unreferenced formal
11227parameters. Note that the
11228combination @emph{-gnatwu} followed by @emph{-gnatwF} has the
11229effect of warning on unreferenced entities other than subprogram
11230formals.
11231@end table
11232
11233@geindex -gnatwg (gcc)
11234
11235
11236@table @asis
11237
11238@item @code{-gnatwg}
11239
11240@emph{Activate warnings on unrecognized pragmas.}
11241
11242@geindex Pragmas
11243@geindex unrecognized
11244
11245This switch causes a warning to be generated if an unrecognized
11246pragma is encountered. Apart from issuing this warning, the
11247pragma is ignored and has no effect. The default
11248is that such warnings are issued (satisfying the Ada Reference
11249Manual requirement that such warnings appear).
11250@end table
11251
11252@geindex -gnatwG (gcc)
11253
11254
11255@table @asis
11256
11257@item @code{-gnatwG}
11258
11259@emph{Suppress warnings on unrecognized pragmas.}
11260
11261This switch suppresses warnings for unrecognized pragmas.
11262@end table
11263
11264@geindex -gnatw.g (gcc)
11265
11266
11267@table @asis
11268
11269@item @code{-gnatw.g}
11270
11271@emph{Warnings used for GNAT sources.}
11272
11273This switch sets the warning categories that are used by the standard
11274GNAT style. Currently this is equivalent to
11275@emph{-gnatwAao.sI.C.V.X}
11276but more warnings may be added in the future without advanced notice.
11277@end table
11278
11279@geindex -gnatwh (gcc)
11280
11281
11282@table @asis
11283
11284@item @code{-gnatwh}
11285
11286@emph{Activate warnings on hiding.}
11287
11288@geindex Hiding of Declarations
11289
11290This switch activates warnings on hiding declarations.
11291A declaration is considered hiding
11292if it is for a non-overloadable entity, and it declares an entity with the
11293same name as some other entity that is directly or use-visible. The default
11294is that such warnings are not generated.
11295@end table
11296
11297@geindex -gnatwH (gcc)
11298
11299
11300@table @asis
11301
11302@item @code{-gnatwH}
11303
11304@emph{Suppress warnings on hiding.}
11305
11306This switch suppresses warnings on hiding declarations.
11307@end table
11308
11309@geindex -gnatw.h (gcc)
11310
11311
11312@table @asis
11313
11314@item @code{-gnatw.h}
11315
11316@emph{Activate warnings on holes/gaps in records.}
11317
11318@geindex Record Representation (gaps)
11319
11320This switch activates warnings on component clauses in record
11321representation clauses that leave holes (gaps) in the record layout.
11322If this warning option is active, then record representation clauses
11323should specify a contiguous layout, adding unused fill fields if needed.
11324@end table
11325
11326@geindex -gnatw.H (gcc)
11327
11328
11329@table @asis
11330
11331@item @code{-gnatw.H}
11332
11333@emph{Suppress warnings on holes/gaps in records.}
11334
11335This switch suppresses warnings on component clauses in record
11336representation clauses that leave holes (haps) in the record layout.
11337@end table
11338
11339@geindex -gnatwi (gcc)
11340
11341
11342@table @asis
11343
11344@item @code{-gnatwi}
11345
11346@emph{Activate warnings on implementation units.}
11347
11348This switch activates warnings for a @emph{with} of an internal GNAT
11349implementation unit, defined as any unit from the @cite{Ada},
11350@cite{Interfaces}, @cite{GNAT},
11351or @cite{System}
11352hierarchies that is not
11353documented in either the Ada Reference Manual or the GNAT
11354Programmer's Reference Manual. Such units are intended only
11355for internal implementation purposes and should not be @emph{with}ed
11356by user programs. The default is that such warnings are generated
11357@end table
11358
11359@geindex -gnatwI (gcc)
11360
11361
11362@table @asis
11363
11364@item @code{-gnatwI}
11365
11366@emph{Disable warnings on implementation units.}
11367
11368This switch disables warnings for a @emph{with} of an internal GNAT
11369implementation unit.
11370@end table
11371
11372@geindex -gnatw.i (gcc)
11373
11374
11375@table @asis
11376
11377@item @code{-gnatw.i}
11378
11379@emph{Activate warnings on overlapping actuals.}
11380
11381This switch enables a warning on statically detectable overlapping actuals in
11382a subprogram call, when one of the actuals is an in-out parameter, and the
11383types of the actuals are not by-copy types. This warning is off by default.
11384@end table
11385
11386@geindex -gnatw.I (gcc)
11387
11388
11389@table @asis
11390
11391@item @code{-gnatw.I}
11392
11393@emph{Disable warnings on overlapping actuals.}
11394
11395This switch disables warnings on overlapping actuals in a call..
11396@end table
11397
11398@geindex -gnatwj (gcc)
11399
11400
11401@table @asis
11402
11403@item @code{-gnatwj}
11404
11405@emph{Activate warnings on obsolescent features (Annex J).}
11406
11407@geindex Features
11408@geindex obsolescent
11409
11410@geindex Obsolescent features
11411
11412If this warning option is activated, then warnings are generated for
11413calls to subprograms marked with @cite{pragma Obsolescent} and
11414for use of features in Annex J of the Ada Reference Manual. In the
11415case of Annex J, not all features are flagged. In particular use
11416of the renamed packages (like @cite{Text_IO}) and use of package
11417@cite{ASCII} are not flagged, since these are very common and
11418would generate many annoying positive warnings. The default is that
11419such warnings are not generated.
11420
11421In addition to the above cases, warnings are also generated for
11422GNAT features that have been provided in past versions but which
11423have been superseded (typically by features in the new Ada standard).
11424For example, @cite{pragma Ravenscar} will be flagged since its
11425function is replaced by @cite{pragma Profile(Ravenscar)}, and
11426@cite{pragma Interface_Name} will be flagged since its function
11427is replaced by @cite{pragma Import}.
11428
11429Note that this warning option functions differently from the
11430restriction @cite{No_Obsolescent_Features} in two respects.
11431First, the restriction applies only to annex J features.
11432Second, the restriction does flag uses of package @cite{ASCII}.
11433@end table
11434
11435@geindex -gnatwJ (gcc)
11436
11437
11438@table @asis
11439
11440@item @code{-gnatwJ}
11441
11442@emph{Suppress warnings on obsolescent features (Annex J).}
11443
11444This switch disables warnings on use of obsolescent features.
11445@end table
11446
11447@geindex -gnatwk (gcc)
11448
11449
11450@table @asis
11451
11452@item @code{-gnatwk}
11453
11454@emph{Activate warnings on variables that could be constants.}
11455
11456This switch activates warnings for variables that are initialized but
11457never modified, and then could be declared constants. The default is that
11458such warnings are not given.
11459@end table
11460
11461@geindex -gnatwK (gcc)
11462
11463
11464@table @asis
11465
11466@item @code{-gnatwK}
11467
11468@emph{Suppress warnings on variables that could be constants.}
11469
11470This switch disables warnings on variables that could be declared constants.
11471@end table
11472
11473@geindex -gnatw.k (gcc)
11474
11475
11476@table @asis
11477
11478@item @code{-gnatw.k}
11479
11480@emph{Activate warnings on redefinition of names in standard.}
11481
11482This switch activates warnings for declarations that declare a name that
11483is defined in package Standard. Such declarations can be confusing,
11484especially since the names in package Standard continue to be directly
11485visible, meaning that use visibiliy on such redeclared names does not
11486work as expected. Names of discriminants and components in records are
11487not included in this check.
11488@end table
11489
11490@geindex -gnatwK (gcc)
11491
11492
11493@table @asis
11494
11495@item @code{-gnatw.K}
11496
11497@emph{Suppress warnings on redefinition of names in standard.}
11498
11499This switch activates warnings for declarations that declare a name that
11500is defined in package Standard.
11501@end table
11502
11503@geindex -gnatwl (gcc)
11504
11505
11506@table @asis
11507
11508@item @code{-gnatwl}
11509
11510@emph{Activate warnings for elaboration pragmas.}
11511
11512@geindex Elaboration
11513@geindex warnings
11514
11515This switch activates warnings for possible elaboration problems,
11516including suspicious use
11517of @cite{Elaborate} pragmas, when using the static elaboration model, and
11518possible situations that may raise @cite{Program_Error} when using the
11519dynamic elaboration model.
11520See the section in this guide on elaboration checking for further details.
11521The default is that such warnings
11522are not generated.
11523@end table
11524
11525@geindex -gnatwL (gcc)
11526
11527
11528@table @asis
11529
11530@item @code{-gnatwL}
11531
11532@emph{Suppress warnings for elaboration pragmas.}
11533
11534This switch suppresses warnings for possible elaboration problems.
11535@end table
11536
11537@geindex -gnatw.l (gcc)
11538
11539
11540@table @asis
11541
11542@item @code{-gnatw.l}
11543
11544@emph{List inherited aspects.}
11545
11546This switch causes the compiler to list inherited invariants,
11547preconditions, and postconditions from Type_Invariant'Class, Invariant'Class,
11548Pre'Class, and Post'Class aspects. Also list inherited subtype predicates.
11549@end table
11550
11551@geindex -gnatw.L (gcc)
11552
11553
11554@table @asis
11555
11556@item @code{-gnatw.L}
11557
11558@emph{Suppress listing of inherited aspects.}
11559
11560This switch suppresses listing of inherited aspects.
11561@end table
11562
11563@geindex -gnatwm (gcc)
11564
11565
11566@table @asis
11567
11568@item @code{-gnatwm}
11569
11570@emph{Activate warnings on modified but unreferenced variables.}
11571
11572This switch activates warnings for variables that are assigned (using
11573an initialization value or with one or more assignment statements) but
11574whose value is never read. The warning is suppressed for volatile
11575variables and also for variables that are renamings of other variables
11576or for which an address clause is given.
11577The default is that these warnings are not given.
11578@end table
11579
11580@geindex -gnatwM (gcc)
11581
11582
11583@table @asis
11584
11585@item @code{-gnatwM}
11586
11587@emph{Disable warnings on modified but unreferenced variables.}
11588
11589This switch disables warnings for variables that are assigned or
11590initialized, but never read.
11591@end table
11592
11593@geindex -gnatw.m (gcc)
11594
11595
11596@table @asis
11597
11598@item @code{-gnatw.m}
11599
11600@emph{Activate warnings on suspicious modulus values.}
11601
11602This switch activates warnings for modulus values that seem suspicious.
11603The cases caught are where the size is the same as the modulus (e.g.
11604a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
11605with no size clause. The guess in both cases is that 2**x was intended
11606rather than x. In addition expressions of the form 2*x for small x
11607generate a warning (the almost certainly accurate guess being that
116082**x was intended). The default is that these warnings are given.
11609@end table
11610
11611@geindex -gnatw.M (gcc)
11612
11613
11614@table @asis
11615
11616@item @code{-gnatw.M}
11617
11618@emph{Disable warnings on suspicious modulus values.}
11619
11620This switch disables warnings for suspicious modulus values.
11621@end table
11622
11623@geindex -gnatwn (gcc)
11624
11625
11626@table @asis
11627
11628@item @code{-gnatwn}
11629
11630@emph{Set normal warnings mode.}
11631
11632This switch sets normal warning mode, in which enabled warnings are
11633issued and treated as warnings rather than errors. This is the default
11634mode. the switch @emph{-gnatwn} can be used to cancel the effect of
11635an explicit @emph{-gnatws} or
11636@emph{-gnatwe}. It also cancels the effect of the
11637implicit @emph{-gnatwe} that is activated by the
11638use of @emph{-gnatg}.
11639@end table
11640
11641@geindex -gnatw.n (gcc)
11642
11643@geindex Atomic Synchronization
11644@geindex warnings
11645
11646
11647@table @asis
11648
11649@item @code{-gnatw.n}
11650
11651@emph{Activate warnings on atomic synchronization.}
11652
11653This switch actives warnings when an access to an atomic variable
11654requires the generation of atomic synchronization code. These
11655warnings are off by default.
11656@end table
11657
11658@geindex -gnatw.N (gcc)
11659
11660
11661@table @asis
11662
11663@item @code{-gnatw.N}
11664
11665@emph{Suppress warnings on atomic synchronization.}
11666
11667@geindex Atomic Synchronization
11668@geindex warnings
11669
11670This switch suppresses warnings when an access to an atomic variable
11671requires the generation of atomic synchronization code.
11672@end table
11673
11674@geindex -gnatwo (gcc)
11675
11676@geindex Address Clauses
11677@geindex warnings
11678
11679
11680@table @asis
11681
11682@item @code{-gnatwo}
11683
11684@emph{Activate warnings on address clause overlays.}
11685
11686This switch activates warnings for possibly unintended initialization
11687effects of defining address clauses that cause one variable to overlap
11688another. The default is that such warnings are generated.
11689@end table
11690
11691@geindex -gnatwO (gcc)
11692
11693
11694@table @asis
11695
11696@item @code{-gnatwO}
11697
11698@emph{Suppress warnings on address clause overlays.}
11699
11700This switch suppresses warnings on possibly unintended initialization
11701effects of defining address clauses that cause one variable to overlap
11702another.
11703@end table
11704
11705@geindex -gnatw.o (gcc)
11706
11707
11708@table @asis
11709
11710@item @code{-gnatw.o}
11711
11712@emph{Activate warnings on modified but unreferenced out parameters.}
11713
11714This switch activates warnings for variables that are modified by using
11715them as actuals for a call to a procedure with an out mode formal, where
11716the resulting assigned value is never read. It is applicable in the case
11717where there is more than one out mode formal. If there is only one out
11718mode formal, the warning is issued by default (controlled by -gnatwu).
11719The warning is suppressed for volatile
11720variables and also for variables that are renamings of other variables
11721or for which an address clause is given.
11722The default is that these warnings are not given.
11723@end table
11724
11725@geindex -gnatw.O (gcc)
11726
11727
11728@table @asis
11729
11730@item @code{-gnatw.O}
11731
11732@emph{Disable warnings on modified but unreferenced out parameters.}
11733
11734This switch suppresses warnings for variables that are modified by using
11735them as actuals for a call to a procedure with an out mode formal, where
11736the resulting assigned value is never read.
11737@end table
11738
11739@geindex -gnatwp (gcc)
11740
11741@geindex Inlining
11742@geindex warnings
11743
11744
11745@table @asis
11746
11747@item @code{-gnatwp}
11748
11749@emph{Activate warnings on ineffective pragma Inlines.}
11750
11751This switch activates warnings for failure of front end inlining
11752(activated by @emph{-gnatN}) to inline a particular call. There are
11753many reasons for not being able to inline a call, including most
11754commonly that the call is too complex to inline. The default is
11755that such warnings are not given.
11756Warnings on ineffective inlining by the gcc back-end can be activated
11757separately, using the gcc switch -Winline.
11758@end table
11759
11760@geindex -gnatwP (gcc)
11761
11762
11763@table @asis
11764
11765@item @code{-gnatwP}
11766
11767@emph{Suppress warnings on ineffective pragma Inlines.}
11768
11769This switch suppresses warnings on ineffective pragma Inlines. If the
11770inlining mechanism cannot inline a call, it will simply ignore the
11771request silently.
11772@end table
11773
11774@geindex -gnatw.p (gcc)
11775
11776@geindex Parameter order
11777@geindex warnings
11778
11779
11780@table @asis
11781
11782@item @code{-gnatw.p}
11783
11784@emph{Activate warnings on parameter ordering.}
11785
11786This switch activates warnings for cases of suspicious parameter
11787ordering when the list of arguments are all simple identifiers that
11788match the names of the formals, but are in a different order. The
11789warning is suppressed if any use of named parameter notation is used,
11790so this is the appropriate way to suppress a false positive (and
11791serves to emphasize that the "misordering" is deliberate). The
11792default is that such warnings are not given.
11793@end table
11794
11795@geindex -gnatw.P (gcc)
11796
11797
11798@table @asis
11799
11800@item @code{-gnatw.P}
11801
11802@emph{Suppress warnings on parameter ordering.}
11803
11804This switch suppresses warnings on cases of suspicious parameter
11805ordering.
11806@end table
11807
11808@geindex -gnatwq (gcc)
11809
11810@geindex Parentheses
11811@geindex warnings
11812
11813
11814@table @asis
11815
11816@item @code{-gnatwq}
11817
11818@emph{Activate warnings on questionable missing parentheses.}
11819
11820This switch activates warnings for cases where parentheses are not used and
11821the result is potential ambiguity from a readers point of view. For example
11822(not a > b) when a and b are modular means ((not a) > b) and very likely the
11823programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
11824quite likely ((-x) mod 5) was intended. In such situations it seems best to
11825follow the rule of always parenthesizing to make the association clear, and
11826this warning switch warns if such parentheses are not present. The default
11827is that these warnings are given.
11828@end table
11829
11830@geindex -gnatwQ (gcc)
11831
11832
11833@table @asis
11834
11835@item @code{-gnatwQ}
11836
11837@emph{Suppress warnings on questionable missing parentheses.}
11838
11839This switch suppresses warnings for cases where the association is not
11840clear and the use of parentheses is preferred.
11841@end table
11842
11843@geindex -gnatwr (gcc)
11844
11845
11846@table @asis
11847
11848@item @code{-gnatwr}
11849
11850@emph{Activate warnings on redundant constructs.}
11851
11852This switch activates warnings for redundant constructs. The following
11853is the current list of constructs regarded as redundant:
11854
11855
11856@itemize *
11857
11858@item
11859Assignment of an item to itself.
11860
11861@item
11862Type conversion that converts an expression to its own type.
11863
11864@item
11865Use of the attribute @cite{Base} where @cite{typ'Base} is the same
11866as @cite{typ}.
11867
11868@item
11869Use of pragma @cite{Pack} when all components are placed by a record
11870representation clause.
11871
11872@item
11873Exception handler containing only a reraise statement (raise with no
11874operand) which has no effect.
11875
11876@item
11877Use of the operator abs on an operand that is known at compile time
11878to be non-negative
11879
11880@item
11881Comparison of boolean expressions to an explicit True value.
11882@end itemize
11883
11884The default is that warnings for redundant constructs are not given.
11885@end table
11886
11887@geindex -gnatwR (gcc)
11888
11889
11890@table @asis
11891
11892@item @code{-gnatwR}
11893
11894@emph{Suppress warnings on redundant constructs.}
11895
11896This switch suppresses warnings for redundant constructs.
11897@end table
11898
11899@geindex -gnatw.r (gcc)
11900
11901
11902@table @asis
11903
11904@item @code{-gnatw.r}
11905
11906@emph{Activate warnings for object renaming function.}
11907
11908This switch activates warnings for an object renaming that renames a
11909function call, which is equivalent to a constant declaration (as
11910opposed to renaming the function itself).  The default is that these
11911warnings are given.
11912@end table
11913
11914@geindex -gnatwT (gcc)
11915
11916
11917@table @asis
11918
11919@item @code{-gnatw.R}
11920
11921@emph{Suppress warnings for object renaming function.}
11922
11923This switch suppresses warnings for object renaming function.
11924@end table
11925
11926@geindex -gnatws (gcc)
11927
11928
11929@table @asis
11930
11931@item @code{-gnatws}
11932
11933@emph{Suppress all warnings.}
11934
11935This switch completely suppresses the
11936output of all warning messages from the GNAT front end, including
11937both warnings that can be controlled by switches described in this
11938section, and those that are normally given unconditionally. The
11939effect of this suppress action can only be cancelled by a subsequent
11940use of the switch @emph{-gnatwn}.
11941
11942Note that switch @emph{-gnatws} does not suppress
11943warnings from the @emph{gcc} back end.
11944To suppress these back end warnings as well, use the switch @emph{-w}
11945in addition to @emph{-gnatws}. Also this switch has no effect on the
11946handling of style check messages.
11947@end table
11948
11949@geindex -gnatw.s (gcc)
11950
11951@geindex Record Representation (component sizes)
11952
11953
11954@table @asis
11955
11956@item @code{-gnatw.s}
11957
11958@emph{Activate warnings on overridden size clauses.}
11959
11960This switch activates warnings on component clauses in record
11961representation clauses where the length given overrides that
11962specified by an explicit size clause for the component type. A
11963warning is similarly given in the array case if a specified
11964component size overrides an explicit size clause for the array
11965component type.
11966@end table
11967
11968@geindex -gnatw.S (gcc)
11969
11970
11971@table @asis
11972
11973@item @code{-gnatw.S}
11974
11975@emph{Suppress warnings on overridden size clauses.}
11976
11977This switch suppresses warnings on component clauses in record
11978representation clauses that override size clauses, and similar
11979warnings when an array component size overrides a size clause.
11980@end table
11981
11982@geindex -gnatwt (gcc)
11983
11984@geindex Deactivated code
11985@geindex warnings
11986
11987@geindex Deleted code
11988@geindex warnings
11989
11990
11991@table @asis
11992
11993@item @code{-gnatwt}
11994
11995@emph{Activate warnings for tracking of deleted conditional code.}
11996
11997This switch activates warnings for tracking of code in conditionals (IF and
11998CASE statements) that is detected to be dead code which cannot be executed, and
11999which is removed by the front end. This warning is off by default. This may be
12000useful for detecting deactivated code in certified applications.
12001@end table
12002
12003@geindex -gnatwT (gcc)
12004
12005
12006@table @asis
12007
12008@item @code{-gnatwT}
12009
12010@emph{Suppress warnings for tracking of deleted conditional code.}
12011
12012This switch suppresses warnings for tracking of deleted conditional code.
12013@end table
12014
12015@geindex -gnatw.t (gcc)
12016
12017
12018@table @asis
12019
12020@item @code{-gnatw.t}
12021
12022@emph{Activate warnings on suspicious contracts.}
12023
12024This switch activates warnings on suspicious contracts. This includes
12025warnings on suspicious postconditions (whether a pragma @cite{Postcondition} or a
12026@cite{Post} aspect in Ada 2012) and suspicious contract cases (pragma or aspect
12027@cite{Contract_Cases}). A function postcondition or contract case is suspicious
12028when no postcondition or contract case for this function mentions the result
12029of the function.  A procedure postcondition or contract case is suspicious
12030when it only refers to the pre-state of the procedure, because in that case
12031it should rather be expressed as a precondition. This switch also controls
12032warnings on suspicious cases of expressions typically found in contracts like
12033quantified expressions and uses of Update attribute. The default is that such
12034warnings are generated.
12035@end table
12036
12037@geindex -gnatw.T (gcc)
12038
12039
12040@table @asis
12041
12042@item @code{-gnatw.T}
12043
12044@emph{Suppress warnings on suspicious contracts.}
12045
12046This switch suppresses warnings on suspicious contracts.
12047@end table
12048
12049@geindex -gnatwu (gcc)
12050
12051
12052@table @asis
12053
12054@item @code{-gnatwu}
12055
12056@emph{Activate warnings on unused entities.}
12057
12058This switch activates warnings to be generated for entities that
12059are declared but not referenced, and for units that are @emph{with}ed
12060and not
12061referenced. In the case of packages, a warning is also generated if
12062no entities in the package are referenced. This means that if a with'ed
12063package is referenced but the only references are in @cite{use}
12064clauses or @cite{renames}
12065declarations, a warning is still generated. A warning is also generated
12066for a generic package that is @emph{with}ed but never instantiated.
12067In the case where a package or subprogram body is compiled, and there
12068is a @emph{with} on the corresponding spec
12069that is only referenced in the body,
12070a warning is also generated, noting that the
12071@emph{with} can be moved to the body. The default is that
12072such warnings are not generated.
12073This switch also activates warnings on unreferenced formals
12074(it includes the effect of @emph{-gnatwf}).
12075@end table
12076
12077@geindex -gnatwU (gcc)
12078
12079
12080@table @asis
12081
12082@item @code{-gnatwU}
12083
12084@emph{Suppress warnings on unused entities.}
12085
12086This switch suppresses warnings for unused entities and packages.
12087It also turns off warnings on unreferenced formals (and thus includes
12088the effect of @emph{-gnatwF}).
12089@end table
12090
12091@geindex -gnatw.u (gcc)
12092
12093
12094@table @asis
12095
12096@item @code{-gnatw.u}
12097
12098@emph{Activate warnings on unordered enumeration types.}
12099
12100This switch causes enumeration types to be considered as conceptually
12101unordered, unless an explicit pragma @cite{Ordered} is given for the type.
12102The effect is to generate warnings in clients that use explicit comparisons
12103or subranges, since these constructs both treat objects of the type as
12104ordered. (A @emph{client} is defined as a unit that is other than the unit in
12105which the type is declared, or its body or subunits.) Please refer to
12106the description of pragma @cite{Ordered} in the
12107@cite{GNAT Reference Manual} for further details.
12108The default is that such warnings are not generated.
12109@end table
12110
12111@geindex -gnatw.U (gcc)
12112
12113
12114@table @asis
12115
12116@item @code{-gnatw.U}
12117
12118@emph{Deactivate warnings on unordered enumeration types.}
12119
12120This switch causes all enumeration types to be considered as ordered, so
12121that no warnings are given for comparisons or subranges for any type.
12122@end table
12123
12124@geindex -gnatwv (gcc)
12125
12126@geindex Unassigned variable warnings
12127
12128
12129@table @asis
12130
12131@item @code{-gnatwv}
12132
12133@emph{Activate warnings on unassigned variables.}
12134
12135This switch activates warnings for access to variables which
12136may not be properly initialized. The default is that
12137such warnings are generated.
12138@end table
12139
12140@geindex -gnatwV (gcc)
12141
12142
12143@table @asis
12144
12145@item @code{-gnatwV}
12146
12147@emph{Suppress warnings on unassigned variables.}
12148
12149This switch suppresses warnings for access to variables which
12150may not be properly initialized.
12151For variables of a composite type, the warning can also be suppressed in
12152Ada 2005 by using a default initialization with a box. For example, if
12153Table is an array of records whose components are only partially uninitialized,
12154then the following code:
12155
12156@example
12157Tab : Table := (others => <>);
12158@end example
12159
12160will suppress warnings on subsequent statements that access components
12161of variable Tab.
12162@end table
12163
12164@geindex -gnatw.v (gcc)
12165
12166@geindex bit order warnings
12167
12168
12169@table @asis
12170
12171@item @code{-gnatw.v}
12172
12173@emph{Activate info messages for non-default bit order.}
12174
12175This switch activates messages (labeled "info", they are not warnings,
12176just informational messages) about the effects of non-default bit-order
12177on records to which a component clause is applied. The effect of specifying
12178non-default bit ordering is a bit subtle (and changed with Ada 2005), so
12179these messages, which are given by default, are useful in understanding the
12180exact consequences of using this feature.
12181@end table
12182
12183@geindex -gnatw.V (gcc)
12184
12185
12186@table @asis
12187
12188@item @code{-gnatw.V}
12189
12190@emph{Suppress info messages for non-default bit order.}
12191
12192This switch suppresses information messages for the effects of specifying
12193non-default bit order on record components with component clauses.
12194@end table
12195
12196@geindex -gnatww (gcc)
12197
12198@geindex String indexing warnings
12199
12200
12201@table @asis
12202
12203@item @code{-gnatww}
12204
12205@emph{Activate warnings on wrong low bound assumption.}
12206
12207This switch activates warnings for indexing an unconstrained string parameter
12208with a literal or S'Length. This is a case where the code is assuming that the
12209low bound is one, which is in general not true (for example when a slice is
12210passed). The default is that such warnings are generated.
12211@end table
12212
12213@geindex -gnatwW (gcc)
12214
12215
12216@table @asis
12217
12218@item @code{-gnatwW}
12219
12220@emph{Suppress warnings on wrong low bound assumption.}
12221
12222This switch suppresses warnings for indexing an unconstrained string parameter
12223with a literal or S'Length. Note that this warning can also be suppressed
12224in a particular case by adding an assertion that the lower bound is 1,
12225as shown in the following example:
12226
12227@example
12228procedure K (S : String) is
12229   pragma Assert (S'First = 1);
12230   ...
12231@end example
12232@end table
12233
12234@geindex -gnatw.w (gcc)
12235
12236@geindex Warnings Off control
12237
12238
12239@table @asis
12240
12241@item @code{-gnatw.w}
12242
12243@emph{Activate warnings on Warnings Off pragmas.}
12244
12245This switch activates warnings for use of @cite{pragma Warnings (Off@comma{} entity)}
12246where either the pragma is entirely useless (because it suppresses no
12247warnings), or it could be replaced by @cite{pragma Unreferenced} or
12248@cite{pragma Unmodified}.
12249Also activates warnings for the case of
12250Warnings (Off, String), where either there is no matching
12251Warnings (On, String), or the Warnings (Off) did not suppress any warning.
12252The default is that these warnings are not given.
12253@end table
12254
12255@geindex -gnatw.W (gcc)
12256
12257
12258@table @asis
12259
12260@item @code{-gnatw.W}
12261
12262@emph{Suppress warnings on unnecessary Warnings Off pragmas.}
12263
12264This switch suppresses warnings for use of @cite{pragma Warnings (Off@comma{} ...)}.
12265@end table
12266
12267@geindex -gnatwx (gcc)
12268
12269@geindex Export/Import pragma warnings
12270
12271
12272@table @asis
12273
12274@item @code{-gnatwx}
12275
12276@emph{Activate warnings on Export/Import pragmas.}
12277
12278This switch activates warnings on Export/Import pragmas when
12279the compiler detects a possible conflict between the Ada and
12280foreign language calling sequences. For example, the use of
12281default parameters in a convention C procedure is dubious
12282because the C compiler cannot supply the proper default, so
12283a warning is issued. The default is that such warnings are
12284generated.
12285@end table
12286
12287@geindex -gnatwX (gcc)
12288
12289
12290@table @asis
12291
12292@item @code{-gnatwX}
12293
12294@emph{Suppress warnings on Export/Import pragmas.}
12295
12296This switch suppresses warnings on Export/Import pragmas.
12297The sense of this is that you are telling the compiler that
12298you know what you are doing in writing the pragma, and it
12299should not complain at you.
12300@end table
12301
12302@geindex -gnatwm (gcc)
12303
12304
12305@table @asis
12306
12307@item @code{-gnatw.x}
12308
12309@emph{Activate warnings for No_Exception_Propagation mode.}
12310
12311This switch activates warnings for exception usage when pragma Restrictions
12312(No_Exception_Propagation) is in effect. Warnings are given for implicit or
12313explicit exception raises which are not covered by a local handler, and for
12314exception handlers which do not cover a local raise. The default is that these
12315warnings are not given.
12316
12317@item @code{-gnatw.X}
12318
12319@emph{Disable warnings for No_Exception_Propagation mode.}
12320
12321This switch disables warnings for exception usage when pragma Restrictions
12322(No_Exception_Propagation) is in effect.
12323@end table
12324
12325@geindex -gnatwy (gcc)
12326
12327@geindex Ada compatibility issues warnings
12328
12329
12330@table @asis
12331
12332@item @code{-gnatwy}
12333
12334@emph{Activate warnings for Ada compatibility issues.}
12335
12336For the most part, newer versions of Ada are upwards compatible
12337with older versions. For example, Ada 2005 programs will almost
12338always work when compiled as Ada 2012.
12339However there are some exceptions (for example the fact that
12340@cite{some} is now a reserved word in Ada 2012). This
12341switch activates several warnings to help in identifying
12342and correcting such incompatibilities. The default is that
12343these warnings are generated. Note that at one point Ada 2005
12344was called Ada 0Y, hence the choice of character.
12345@end table
12346
12347@geindex -gnatwY (gcc)
12348
12349@geindex Ada compatibility issues warnings
12350
12351
12352@table @asis
12353
12354@item @code{-gnatwY}
12355
12356@emph{Disable warnings for Ada compatibility issues.}
12357
12358This switch suppresses the warnings intended to help in identifying
12359incompatibilities between Ada language versions.
12360@end table
12361
12362@geindex -gnatw.y (gcc)
12363
12364@geindex Package spec needing body
12365
12366
12367@table @asis
12368
12369@item @code{-gnatw.y}
12370
12371@emph{Activate information messages for why package spec needs body.}
12372
12373There are a number of cases in which a package spec needs a body.
12374For example, the use of pragma Elaborate_Body, or the declaration
12375of a procedure specification requiring a completion. This switch
12376causes information messages to be output showing why a package
12377specification requires a body. This can be useful in the case of
12378a large package specification which is unexpectedly requiring a
12379body. The default is that such information messages are not output.
12380@end table
12381
12382@geindex -gnatw.Y (gcc)
12383
12384@geindex No information messages for why package spec needs body
12385
12386
12387@table @asis
12388
12389@item @code{-gnatw.Y}
12390
12391@emph{Disable information messages for why package spec needs body.}
12392
12393This switch suppresses the output of information messages showing why
12394a package specification needs a body.
12395@end table
12396
12397@geindex -gnatwz (gcc)
12398
12399@geindex Unchecked_Conversion warnings
12400
12401
12402@table @asis
12403
12404@item @code{-gnatwz}
12405
12406@emph{Activate warnings on unchecked conversions.}
12407
12408This switch activates warnings for unchecked conversions
12409where the types are known at compile time to have different
12410sizes. The default is that such warnings are generated. Warnings are also
12411generated for subprogram pointers with different conventions.
12412@end table
12413
12414@geindex -gnatwZ (gcc)
12415
12416
12417@table @asis
12418
12419@item @code{-gnatwZ}
12420
12421@emph{Suppress warnings on unchecked conversions.}
12422
12423This switch suppresses warnings for unchecked conversions
12424where the types are known at compile time to have different
12425sizes or conventions.
12426@end table
12427
12428@geindex -gnatw.z (gcc)
12429
12430@geindex Size/Alignment warnings
12431
12432
12433@table @asis
12434
12435@item @code{-gnatw.z}
12436
12437@emph{Activate warnings for size not a multiple of alignment.}
12438
12439This switch activates warnings for cases of record types with
12440specified @cite{Size} and @cite{Alignment} attributes where the
12441size is not a multiple of the alignment, resulting in an object
12442size that is greater than the specified size. The default
12443is that such warnings are generated.
12444@end table
12445
12446@geindex -gnatw.Z (gcc)
12447
12448@geindex Size/Alignment warnings
12449
12450
12451@table @asis
12452
12453@item @code{-gnatw.Z}
12454
12455@emph{Suppress warnings for size not a multiple of alignment.}
12456
12457This switch suppresses warnings for cases of record types with
12458specified @cite{Size} and @cite{Alignment} attributes where the
12459size is not a multiple of the alignment, resulting in an object
12460size that is greater than the specified size.
12461The warning can also be
12462suppressed by giving an explicit @cite{Object_Size} value.
12463@end table
12464
12465@geindex -Wunused (gcc)
12466
12467
12468@table @asis
12469
12470@item @code{-Wunused}
12471
12472The warnings controlled by the @emph{-gnatw} switch are generated by
12473the front end of the compiler. The @emph{GCC} back end can provide
12474additional warnings and they are controlled by the @emph{-W} switch.
12475For example, @emph{-Wunused} activates back end
12476warnings for entities that are declared but not referenced.
12477@end table
12478
12479@geindex -Wuninitialized (gcc)
12480
12481
12482@table @asis
12483
12484@item @code{-Wuninitialized}
12485
12486Similarly, @emph{-Wuninitialized} activates
12487the back end warning for uninitialized variables. This switch must be
12488used in conjunction with an optimization level greater than zero.
12489@end table
12490
12491@geindex -Wstack-usage (gcc)
12492
12493
12494@table @asis
12495
12496@item @code{-Wstack-usage=@emph{len}}
12497
12498Warn if the stack usage of a subprogram might be larger than @cite{len} bytes.
12499See @ref{fd,,Static Stack Usage Analysis} for details.
12500@end table
12501
12502@geindex -Wall (gcc)
12503
12504
12505@table @asis
12506
12507@item @code{-Wall}
12508
12509This switch enables most warnings from the @emph{GCC} back end.
12510The code generator detects a number of warning situations that are missed
12511by the @emph{GNAT} front end, and this switch can be used to activate them.
12512The use of this switch also sets the default front end warning mode to
12513@emph{-gnatwa}, that is, most front end warnings activated as well.
12514@end table
12515
12516@geindex -w (gcc)
12517
12518
12519@table @asis
12520
12521@item @code{-w}
12522
12523Conversely, this switch suppresses warnings from the @emph{GCC} back end.
12524The use of this switch also sets the default front end warning mode to
12525@emph{-gnatws}, that is, front end warnings suppressed as well.
12526@end table
12527
12528@geindex -Werror (gcc)
12529
12530
12531@table @asis
12532
12533@item @code{-Werror}
12534
12535This switch causes warnings from the @emph{GCC} back end to be treated as
12536errors.  The warning string still appears, but the warning messages are
12537counted as errors, and prevent the generation of an object file.
12538@end table
12539
12540A string of warning parameters can be used in the same parameter. For example:
12541
12542@example
12543-gnatwaGe
12544@end example
12545
12546will turn on all optional warnings except for unrecognized pragma warnings,
12547and also specify that warnings should be treated as errors.
12548
12549When no switch @emph{-gnatw} is used, this is equivalent to:
12550
12551@quotation
12552
12553
12554@itemize *
12555
12556@item
12557@code{-gnatw.a}
12558
12559@item
12560@code{-gnatwB}
12561
12562@item
12563@code{-gnatw.b}
12564
12565@item
12566@code{-gnatwC}
12567
12568@item
12569@code{-gnatw.C}
12570
12571@item
12572@code{-gnatwD}
12573
12574@item
12575@code{-gnatwF}
12576
12577@item
12578@code{-gnatwg}
12579
12580@item
12581@code{-gnatwH}
12582
12583@item
12584@code{-gnatwi}
12585
12586@item
12587@code{-gnatw.I}
12588
12589@item
12590@code{-gnatwJ}
12591
12592@item
12593@code{-gnatwK}
12594
12595@item
12596@code{-gnatwL}
12597
12598@item
12599@code{-gnatw.L}
12600
12601@item
12602@code{-gnatwM}
12603
12604@item
12605@code{-gnatw.m}
12606
12607@item
12608@code{-gnatwn}
12609
12610@item
12611@code{-gnatwo}
12612
12613@item
12614@code{-gnatw.O}
12615
12616@item
12617@code{-gnatwP}
12618
12619@item
12620@code{-gnatw.P}
12621
12622@item
12623@code{-gnatwq}
12624
12625@item
12626@code{-gnatwR}
12627
12628@item
12629@code{-gnatw.R}
12630
12631@item
12632@code{-gnatw.S}
12633
12634@item
12635@code{-gnatwT}
12636
12637@item
12638@code{-gnatw.T}
12639
12640@item
12641@code{-gnatwU}
12642
12643@item
12644@code{-gnatwv}
12645
12646@item
12647@code{-gnatww}
12648
12649@item
12650@code{-gnatw.W}
12651
12652@item
12653@code{-gnatwx}
12654
12655@item
12656@code{-gnatw.X}
12657
12658@item
12659@code{-gnatwy}
12660
12661@item
12662@code{-gnatwz}
12663@end itemize
12664@end quotation
12665
12666@node Debugging and Assertion Control,Validity Checking,Warning Message Control,Compiler Switches
12667@anchor{gnat_ugn/building_executable_programs_with_gnat debugging-and-assertion-control}@anchor{108}@anchor{gnat_ugn/building_executable_programs_with_gnat id16}@anchor{109}
12668@subsection Debugging and Assertion Control
12669
12670
12671@geindex -gnata (gcc)
12672
12673
12674@table @asis
12675
12676@item @code{-gnata}
12677
12678@geindex Assert
12679
12680@geindex Debug
12681
12682@geindex Assertions
12683
12684@geindex Precondition
12685
12686@geindex Postcondition
12687
12688@geindex Type invariants
12689
12690@geindex Subtype predicates
12691
12692The @cite{-gnata} option is equivalent to the following Assertion_Policy pragma:
12693
12694@example
12695pragma Assertion_Policy (Check);
12696@end example
12697
12698Which is a shorthand for:
12699
12700@example
12701pragma Assertion_Policy
12702  (Assert               => Check,
12703   Static_Predicate     => Check,
12704   Dynamic_Predicate    => Check,
12705   Pre                  => Check,
12706   Pre'Class            => Check,
12707   Post                 => Check,
12708   Post'Class           => Check,
12709   Type_Invariant       => Check,
12710   Type_Invariant'Class => Check);
12711@end example
12712
12713The pragmas @cite{Assert} and @cite{Debug} normally have no effect and
12714are ignored. This switch, where @code{a} stands for assert, causes
12715pragmas @cite{Assert} and @cite{Debug} to be activated. This switch also
12716causes preconditions, postconditions, subtype predicates, and
12717type invariants to be activated.
12718
12719The pragmas have the form:
12720
12721@example
12722pragma Assert (<Boolean-expression> [, <static-string-expression>])
12723pragma Debug (<procedure call>)
12724pragma Type_Invariant (<type-local-name>, <Boolean-expression>)
12725pragma Predicate (<type-local-name>, <Boolean-expression>)
12726pragma Precondition (<Boolean-expression>, <string-expression>)
12727pragma Postcondition (<Boolean-expression>, <string-expression>)
12728@end example
12729
12730The aspects have the form:
12731
12732@example
12733with [Pre|Post|Type_Invariant|Dynamic_Predicate|Static_Predicate]
12734  => <Boolean-expression>;
12735@end example
12736
12737The @cite{Assert} pragma causes @cite{Boolean-expression} to be tested.
12738If the result is @cite{True}, the pragma has no effect (other than
12739possible side effects from evaluating the expression). If the result is
12740@cite{False}, the exception @cite{Assert_Failure} declared in the package
12741@cite{System.Assertions} is raised (passing @cite{static-string-expression}, if
12742present, as the message associated with the exception). If no string
12743expression is given, the default is a string containing the file name and
12744line number of the pragma.
12745
12746The @cite{Debug} pragma causes @cite{procedure} to be called. Note that
12747@cite{pragma Debug} may appear within a declaration sequence, allowing
12748debugging procedures to be called between declarations.
12749
12750For the aspect specification, the @cite{<Boolean-expression>} is evaluated.
12751If the result is @cite{True}, the aspect has no effect. If the result
12752is @cite{False}, the exception @cite{Assert_Failure} is raised.
12753@end table
12754
12755@node Validity Checking,Style Checking,Debugging and Assertion Control,Compiler Switches
12756@anchor{gnat_ugn/building_executable_programs_with_gnat validity-checking}@anchor{fe}@anchor{gnat_ugn/building_executable_programs_with_gnat id17}@anchor{10a}
12757@subsection Validity Checking
12758
12759
12760@geindex Validity Checking
12761
12762The Ada Reference Manual defines the concept of invalid values (see
12763RM 13.9.1). The primary source of invalid values is uninitialized
12764variables. A scalar variable that is left uninitialized may contain
12765an invalid value; the concept of invalid does not apply to access or
12766composite types.
12767
12768It is an error to read an invalid value, but the RM does not require
12769run-time checks to detect such errors, except for some minimal
12770checking to prevent erroneous execution (i.e. unpredictable
12771behavior). This corresponds to the @emph{-gnatVd} switch below,
12772which is the default. For example, by default, if the expression of a
12773case statement is invalid, it will raise Constraint_Error rather than
12774causing a wild jump, and if an array index on the left-hand side of an
12775assignment is invalid, it will raise Constraint_Error rather than
12776overwriting an arbitrary memory location.
12777
12778The @emph{-gnatVa} may be used to enable additional validity checks,
12779which are not required by the RM. These checks are often very
12780expensive (which is why the RM does not require them). These checks
12781are useful in tracking down uninitialized variables, but they are
12782not usually recommended for production builds, and in particular
12783we do not recommend using these extra validity checking options in
12784combination with optimization, since this can confuse the optimizer.
12785If performance is a consideration, leading to the need to optimize,
12786then the validity checking options should not be used.
12787
12788The other @emph{-gnatV}@code{x} switches below allow finer-grained
12789control; you can enable whichever validity checks you desire. However,
12790for most debugging purposes, @emph{-gnatVa} is sufficient, and the
12791default @emph{-gnatVd} (i.e. standard Ada behavior) is usually
12792sufficient for non-debugging use.
12793
12794The @emph{-gnatB} switch tells the compiler to assume that all
12795values are valid (that is, within their declared subtype range)
12796except in the context of a use of the Valid attribute. This means
12797the compiler can generate more efficient code, since the range
12798of values is better known at compile time. However, an uninitialized
12799variable can cause wild jumps and memory corruption in this mode.
12800
12801The @emph{-gnatV}@code{x} switch allows control over the validity
12802checking mode as described below.
12803The @code{x} argument is a string of letters that
12804indicate validity checks that are performed or not performed in addition
12805to the default checks required by Ada as described above.
12806
12807@geindex -gnatVa (gcc)
12808
12809
12810@table @asis
12811
12812@item @code{-gnatVa}
12813
12814@emph{All validity checks.}
12815
12816All validity checks are turned on.
12817That is, @emph{-gnatVa} is
12818equivalent to @emph{gnatVcdfimorst}.
12819@end table
12820
12821@geindex -gnatVc (gcc)
12822
12823
12824@table @asis
12825
12826@item @code{-gnatVc}
12827
12828@emph{Validity checks for copies.}
12829
12830The right hand side of assignments, and the initializing values of
12831object declarations are validity checked.
12832@end table
12833
12834@geindex -gnatVd (gcc)
12835
12836
12837@table @asis
12838
12839@item @code{-gnatVd}
12840
12841@emph{Default (RM) validity checks.}
12842
12843Some validity checks are done by default following normal Ada semantics
12844(RM 13.9.1 (9-11)).
12845A check is done in case statements that the expression is within the range
12846of the subtype. If it is not, Constraint_Error is raised.
12847For assignments to array components, a check is done that the expression used
12848as index is within the range. If it is not, Constraint_Error is raised.
12849Both these validity checks may be turned off using switch @emph{-gnatVD}.
12850They are turned on by default. If @emph{-gnatVD} is specified, a subsequent
12851switch @emph{-gnatVd} will leave the checks turned on.
12852Switch @emph{-gnatVD} should be used only if you are sure that all such
12853expressions have valid values. If you use this switch and invalid values
12854are present, then the program is erroneous, and wild jumps or memory
12855overwriting may occur.
12856@end table
12857
12858@geindex -gnatVe (gcc)
12859
12860
12861@table @asis
12862
12863@item @code{-gnatVe}
12864
12865@emph{Validity checks for elementary components.}
12866
12867In the absence of this switch, assignments to record or array components are
12868not validity checked, even if validity checks for assignments generally
12869(@emph{-gnatVc}) are turned on. In Ada, assignment of composite values do not
12870require valid data, but assignment of individual components does. So for
12871example, there is a difference between copying the elements of an array with a
12872slice assignment, compared to assigning element by element in a loop. This
12873switch allows you to turn off validity checking for components, even when they
12874are assigned component by component.
12875@end table
12876
12877@geindex -gnatVf (gcc)
12878
12879
12880@table @asis
12881
12882@item @code{-gnatVf}
12883
12884@emph{Validity checks for floating-point values.}
12885
12886In the absence of this switch, validity checking occurs only for discrete
12887values. If @emph{-gnatVf} is specified, then validity checking also applies
12888for floating-point values, and NaNs and infinities are considered invalid,
12889as well as out of range values for constrained types. Note that this means
12890that standard IEEE infinity mode is not allowed. The exact contexts
12891in which floating-point values are checked depends on the setting of other
12892options. For example, @emph{-gnatVif} or @emph{-gnatVfi}
12893(the order does not matter) specifies that floating-point parameters of mode
12894@cite{in} should be validity checked.
12895@end table
12896
12897@geindex -gnatVi (gcc)
12898
12899
12900@table @asis
12901
12902@item @code{-gnatVi}
12903
12904@emph{Validity checks for `in` mode parameters.}
12905
12906Arguments for parameters of mode @cite{in} are validity checked in function
12907and procedure calls at the point of call.
12908@end table
12909
12910@geindex -gnatVm (gcc)
12911
12912
12913@table @asis
12914
12915@item @code{-gnatVm}
12916
12917@emph{Validity checks for `in out` mode parameters.}
12918
12919Arguments for parameters of mode @cite{in out} are validity checked in
12920procedure calls at the point of call. The @cite{'m'} here stands for
12921modify, since this concerns parameters that can be modified by the call.
12922Note that there is no specific option to test @cite{out} parameters,
12923but any reference within the subprogram will be tested in the usual
12924manner, and if an invalid value is copied back, any reference to it
12925will be subject to validity checking.
12926@end table
12927
12928@geindex -gnatVn (gcc)
12929
12930
12931@table @asis
12932
12933@item @code{-gnatVn}
12934
12935@emph{No validity checks.}
12936
12937This switch turns off all validity checking, including the default checking
12938for case statements and left hand side subscripts. Note that the use of
12939the switch @emph{-gnatp} suppresses all run-time checks, including
12940validity checks, and thus implies @emph{-gnatVn}. When this switch
12941is used, it cancels any other @emph{-gnatV} previously issued.
12942@end table
12943
12944@geindex -gnatVo (gcc)
12945
12946
12947@table @asis
12948
12949@item @code{-gnatVo}
12950
12951@emph{Validity checks for operator and attribute operands.}
12952
12953Arguments for predefined operators and attributes are validity checked.
12954This includes all operators in package @cite{Standard},
12955the shift operators defined as intrinsic in package @cite{Interfaces}
12956and operands for attributes such as @cite{Pos}. Checks are also made
12957on individual component values for composite comparisons, and on the
12958expressions in type conversions and qualified expressions. Checks are
12959also made on explicit ranges using @code{..} (e.g., slices, loops etc).
12960@end table
12961
12962@geindex -gnatVp (gcc)
12963
12964
12965@table @asis
12966
12967@item @code{-gnatVp}
12968
12969@emph{Validity checks for parameters.}
12970
12971This controls the treatment of parameters within a subprogram (as opposed
12972to @emph{-gnatVi} and @emph{-gnatVm} which control validity testing
12973of parameters on a call. If either of these call options is used, then
12974normally an assumption is made within a subprogram that the input arguments
12975have been validity checking at the point of call, and do not need checking
12976again within a subprogram). If @emph{-gnatVp} is set, then this assumption
12977is not made, and parameters are not assumed to be valid, so their validity
12978will be checked (or rechecked) within the subprogram.
12979@end table
12980
12981@geindex -gnatVr (gcc)
12982
12983
12984@table @asis
12985
12986@item @code{-gnatVr}
12987
12988@emph{Validity checks for function returns.}
12989
12990The expression in @cite{return} statements in functions is validity
12991checked.
12992@end table
12993
12994@geindex -gnatVs (gcc)
12995
12996
12997@table @asis
12998
12999@item @code{-gnatVs}
13000
13001@emph{Validity checks for subscripts.}
13002
13003All subscripts expressions are checked for validity, whether they appear
13004on the right side or left side (in default mode only left side subscripts
13005are validity checked).
13006@end table
13007
13008@geindex -gnatVt (gcc)
13009
13010
13011@table @asis
13012
13013@item @code{-gnatVt}
13014
13015@emph{Validity checks for tests.}
13016
13017Expressions used as conditions in @cite{if}, @cite{while} or @cite{exit}
13018statements are checked, as well as guard expressions in entry calls.
13019@end table
13020
13021The @emph{-gnatV} switch may be followed by a string of letters
13022to turn on a series of validity checking options.
13023For example, @code{-gnatVcr}
13024specifies that in addition to the default validity checking, copies and
13025function return expressions are to be validity checked.
13026In order to make it easier to specify the desired combination of effects,
13027the upper case letters @cite{CDFIMORST} may
13028be used to turn off the corresponding lower case option.
13029Thus @code{-gnatVaM} turns on all validity checking options except for
13030checking of @cite{**in out**} procedure arguments.
13031
13032The specification of additional validity checking generates extra code (and
13033in the case of @emph{-gnatVa} the code expansion can be substantial).
13034However, these additional checks can be very useful in detecting
13035uninitialized variables, incorrect use of unchecked conversion, and other
13036errors leading to invalid values. The use of pragma @cite{Initialize_Scalars}
13037is useful in conjunction with the extra validity checking, since this
13038ensures that wherever possible uninitialized variables have invalid values.
13039
13040See also the pragma @cite{Validity_Checks} which allows modification of
13041the validity checking mode at the program source level, and also allows for
13042temporary disabling of validity checks.
13043
13044@node Style Checking,Run-Time Checks,Validity Checking,Compiler Switches
13045@anchor{gnat_ugn/building_executable_programs_with_gnat id18}@anchor{10b}@anchor{gnat_ugn/building_executable_programs_with_gnat style-checking}@anchor{103}
13046@subsection Style Checking
13047
13048
13049@geindex Style checking
13050
13051@geindex -gnaty (gcc)
13052
13053The @emph{-gnatyx} switch causes the compiler to
13054enforce specified style rules. A limited set of style rules has been used
13055in writing the GNAT sources themselves. This switch allows user programs
13056to activate all or some of these checks. If the source program fails a
13057specified style check, an appropriate message is given, preceded by
13058the character sequence '(style)'. This message does not prevent
13059successful compilation (unless the @emph{-gnatwe} switch is used).
13060
13061Note that this is by no means intended to be a general facility for
13062checking arbitrary coding standards. It is simply an embedding of the
13063style rules we have chosen for the GNAT sources. If you are starting
13064a project which does not have established style standards, you may
13065find it useful to adopt the entire set of GNAT coding standards, or
13066some subset of them.
13067
13068
13069The string @cite{x} is a sequence of letters or digits
13070indicating the particular style
13071checks to be performed. The following checks are defined:
13072
13073@geindex -gnaty[0-9] (gcc)
13074
13075
13076@table @asis
13077
13078@item @code{-gnaty0}
13079
13080@emph{Specify indentation level.}
13081
13082If a digit from 1-9 appears
13083in the string after @emph{-gnaty}
13084then proper indentation is checked, with the digit indicating the
13085indentation level required. A value of zero turns off this style check.
13086The general style of required indentation is as specified by
13087the examples in the Ada Reference Manual. Full line comments must be
13088aligned with the @cite{--} starting on a column that is a multiple of
13089the alignment level, or they may be aligned the same way as the following
13090non-blank line (this is useful when full line comments appear in the middle
13091of a statement, or they may be aligned with the source line on the previous
13092non-blank line.
13093@end table
13094
13095@geindex -gnatya (gcc)
13096
13097
13098@table @asis
13099
13100@item @code{-gnatya}
13101
13102@emph{Check attribute casing.}
13103
13104Attribute names, including the case of keywords such as @cite{digits}
13105used as attributes names, must be written in mixed case, that is, the
13106initial letter and any letter following an underscore must be uppercase.
13107All other letters must be lowercase.
13108@end table
13109
13110@geindex -gnatyA (gcc)
13111
13112
13113@table @asis
13114
13115@item @code{-gnatyA}
13116
13117@emph{Use of array index numbers in array attributes.}
13118
13119When using the array attributes First, Last, Range,
13120or Length, the index number must be omitted for one-dimensional arrays
13121and is required for multi-dimensional arrays.
13122@end table
13123
13124@geindex -gnatyb (gcc)
13125
13126
13127@table @asis
13128
13129@item @code{-gnatyb}
13130
13131@emph{Blanks not allowed at statement end.}
13132
13133Trailing blanks are not allowed at the end of statements. The purpose of this
13134rule, together with h (no horizontal tabs), is to enforce a canonical format
13135for the use of blanks to separate source tokens.
13136@end table
13137
13138@geindex -gnatyB (gcc)
13139
13140
13141@table @asis
13142
13143@item @code{-gnatyB}
13144
13145@emph{Check Boolean operators.}
13146
13147The use of AND/OR operators is not permitted except in the cases of modular
13148operands, array operands, and simple stand-alone boolean variables or
13149boolean constants. In all other cases @cite{and then}/@cite{or else} are
13150required.
13151@end table
13152
13153@geindex -gnatyc (gcc)
13154
13155
13156@table @asis
13157
13158@item @code{-gnatyc}
13159
13160@emph{Check comments, double space.}
13161
13162Comments must meet the following set of rules:
13163
13164
13165@itemize *
13166
13167@item
13168The '@cite{--}' that starts the column must either start in column one,
13169or else at least one blank must precede this sequence.
13170
13171@item
13172Comments that follow other tokens on a line must have at least one blank
13173following the '@cite{--}' at the start of the comment.
13174
13175@item
13176Full line comments must have at least two blanks following the
13177'@cite{--}' that starts the comment, with the following exceptions.
13178
13179@item
13180A line consisting only of the '@cite{--}' characters, possibly preceded
13181by blanks is permitted.
13182
13183@item
13184A comment starting with '@cite{--x}' where @cite{x} is a special character
13185is permitted.
13186This allows proper processing of the output generated by specialized tools
13187including @emph{gnatprep} (where '@cite{--!}' is used) and the SPARK
13188annotation
13189language (where '@cite{--#}' is used). For the purposes of this rule, a
13190special character is defined as being in one of the ASCII ranges
13191@cite{16#21#...16#2F#} or @cite{16#3A#...16#3F#}.
13192Note that this usage is not permitted
13193in GNAT implementation units (i.e., when @emph{-gnatg} is used).
13194
13195@item
13196A line consisting entirely of minus signs, possibly preceded by blanks, is
13197permitted. This allows the construction of box comments where lines of minus
13198signs are used to form the top and bottom of the box.
13199
13200@item
13201A comment that starts and ends with '@cite{--}' is permitted as long as at
13202least one blank follows the initial '@cite{--}'. Together with the preceding
13203rule, this allows the construction of box comments, as shown in the following
13204example:
13205
13206@example
13207---------------------------
13208-- This is a box comment --
13209-- with two text lines.  --
13210---------------------------
13211@end example
13212@end itemize
13213@end table
13214
13215@geindex -gnatyC (gcc)
13216
13217
13218@table @asis
13219
13220@item @code{-gnatyC}
13221
13222@emph{Check comments, single space.}
13223
13224This is identical to @cite{c} except that only one space
13225is required following the @cite{--} of a comment instead of two.
13226@end table
13227
13228@geindex -gnatyd (gcc)
13229
13230
13231@table @asis
13232
13233@item @code{-gnatyd}
13234
13235@emph{Check no DOS line terminators present.}
13236
13237All lines must be terminated by a single ASCII.LF
13238character (in particular the DOS line terminator sequence CR/LF is not
13239allowed).
13240@end table
13241
13242@geindex -gnatye (gcc)
13243
13244
13245@table @asis
13246
13247@item @code{-gnatye}
13248
13249@emph{Check end/exit labels.}
13250
13251Optional labels on @cite{end} statements ending subprograms and on
13252@cite{exit} statements exiting named loops, are required to be present.
13253@end table
13254
13255@geindex -gnatyf (gcc)
13256
13257
13258@table @asis
13259
13260@item @code{-gnatyf}
13261
13262@emph{No form feeds or vertical tabs.}
13263
13264Neither form feeds nor vertical tab characters are permitted
13265in the source text.
13266@end table
13267
13268@geindex -gnatyg (gcc)
13269
13270
13271@table @asis
13272
13273@item @code{-gnatyg}
13274
13275@emph{GNAT style mode.}
13276
13277The set of style check switches is set to match that used by the GNAT sources.
13278This may be useful when developing code that is eventually intended to be
13279incorporated into GNAT. Currently this is equivalent to @emph{-gnatwydISux})
13280but additional style switches may be added to this set in the future without
13281advance notice.
13282@end table
13283
13284@geindex -gnatyh (gcc)
13285
13286
13287@table @asis
13288
13289@item @code{-gnatyh}
13290
13291@emph{No horizontal tabs.}
13292
13293Horizontal tab characters are not permitted in the source text.
13294Together with the b (no blanks at end of line) check, this
13295enforces a canonical form for the use of blanks to separate
13296source tokens.
13297@end table
13298
13299@geindex -gnatyi (gcc)
13300
13301
13302@table @asis
13303
13304@item @code{-gnatyi}
13305
13306@emph{Check if-then layout.}
13307
13308The keyword @cite{then} must appear either on the same
13309line as corresponding @cite{if}, or on a line on its own, lined
13310up under the @cite{if}.
13311@end table
13312
13313@geindex -gnatyI (gcc)
13314
13315
13316@table @asis
13317
13318@item @code{-gnatyI}
13319
13320@emph{check mode IN keywords.}
13321
13322Mode @cite{in} (the default mode) is not
13323allowed to be given explicitly. @cite{in out} is fine,
13324but not @cite{in} on its own.
13325@end table
13326
13327@geindex -gnatyk (gcc)
13328
13329
13330@table @asis
13331
13332@item @code{-gnatyk}
13333
13334@emph{Check keyword casing.}
13335
13336All keywords must be in lower case (with the exception of keywords
13337such as @cite{digits} used as attribute names to which this check
13338does not apply).
13339@end table
13340
13341@geindex -gnatyl (gcc)
13342
13343
13344@table @asis
13345
13346@item @code{-gnatyl}
13347
13348@emph{Check layout.}
13349
13350Layout of statement and declaration constructs must follow the
13351recommendations in the Ada Reference Manual, as indicated by the
13352form of the syntax rules. For example an @cite{else} keyword must
13353be lined up with the corresponding @cite{if} keyword.
13354
13355There are two respects in which the style rule enforced by this check
13356option are more liberal than those in the Ada Reference Manual. First
13357in the case of record declarations, it is permissible to put the
13358@cite{record} keyword on the same line as the @cite{type} keyword, and
13359then the @cite{end} in @cite{end record} must line up under @cite{type}.
13360This is also permitted when the type declaration is split on two lines.
13361For example, any of the following three layouts is acceptable:
13362
13363@example
13364type q is record
13365   a : integer;
13366   b : integer;
13367end record;
13368
13369type q is
13370   record
13371      a : integer;
13372      b : integer;
13373   end record;
13374
13375type q is
13376   record
13377      a : integer;
13378      b : integer;
13379end record;
13380@end example
13381
13382Second, in the case of a block statement, a permitted alternative
13383is to put the block label on the same line as the @cite{declare} or
13384@cite{begin} keyword, and then line the @cite{end} keyword up under
13385the block label. For example both the following are permitted:
13386
13387@example
13388Block : declare
13389   A : Integer := 3;
13390begin
13391   Proc (A, A);
13392end Block;
13393
13394Block :
13395   declare
13396      A : Integer := 3;
13397   begin
13398      Proc (A, A);
13399   end Block;
13400@end example
13401
13402The same alternative format is allowed for loops. For example, both of
13403the following are permitted:
13404
13405@example
13406Clear : while J < 10 loop
13407   A (J) := 0;
13408end loop Clear;
13409
13410Clear :
13411   while J < 10 loop
13412      A (J) := 0;
13413   end loop Clear;
13414@end example
13415@end table
13416
13417@geindex -gnatyLnnn (gcc)
13418
13419
13420@table @asis
13421
13422@item @code{-gnatyL}
13423
13424@emph{Set maximum nesting level.}
13425
13426The maximum level of nesting of constructs (including subprograms, loops,
13427blocks, packages, and conditionals) may not exceed the given value
13428@emph{nnn}. A value of zero disconnects this style check.
13429@end table
13430
13431@geindex -gnatym (gcc)
13432
13433
13434@table @asis
13435
13436@item @code{-gnatym}
13437
13438@emph{Check maximum line length.}
13439
13440The length of source lines must not exceed 79 characters, including
13441any trailing blanks. The value of 79 allows convenient display on an
1344280 character wide device or window, allowing for possible special
13443treatment of 80 character lines. Note that this count is of
13444characters in the source text. This means that a tab character counts
13445as one character in this count and a wide character sequence counts as
13446a single character (however many bytes are needed in the encoding).
13447@end table
13448
13449@geindex -gnatyMnnn (gcc)
13450
13451
13452@table @asis
13453
13454@item @code{-gnatyM}
13455
13456@emph{Set maximum line length.}
13457
13458The length of lines must not exceed the
13459given value @emph{nnn}. The maximum value that can be specified is 32767.
13460If neither style option for setting the line length is used, then the
13461default is 255. This also controls the maximum length of lexical elements,
13462where the only restriction is that they must fit on a single line.
13463@end table
13464
13465@geindex -gnatyn (gcc)
13466
13467
13468@table @asis
13469
13470@item @code{-gnatyn}
13471
13472@emph{Check casing of entities in Standard.}
13473
13474Any identifier from Standard must be cased
13475to match the presentation in the Ada Reference Manual (for example,
13476@cite{Integer} and @cite{ASCII.NUL}).
13477@end table
13478
13479@geindex -gnatyN (gcc)
13480
13481
13482@table @asis
13483
13484@item @code{-gnatyN}
13485
13486@emph{Turn off all style checks.}
13487
13488All style check options are turned off.
13489@end table
13490
13491@geindex -gnatyo (gcc)
13492
13493
13494@table @asis
13495
13496@item @code{-gnatyo}
13497
13498@emph{Check order of subprogram bodies.}
13499
13500All subprogram bodies in a given scope
13501(e.g., a package body) must be in alphabetical order. The ordering
13502rule uses normal Ada rules for comparing strings, ignoring casing
13503of letters, except that if there is a trailing numeric suffix, then
13504the value of this suffix is used in the ordering (e.g., Junk2 comes
13505before Junk10).
13506@end table
13507
13508@geindex -gnatyO (gcc)
13509
13510
13511@table @asis
13512
13513@item @code{-gnatyO}
13514
13515@emph{Check that overriding subprograms are explicitly marked as such.}
13516
13517This applies to all subprograms of a derived type that override a primitive
13518operation of the type, for both tagged and untagged types. In particular,
13519the declaration of a primitive operation of a type extension that overrides
13520an inherited operation must carry an overriding indicator. Another case is
13521the declaration of a function that overrides a predefined operator (such
13522as an equality operator).
13523@end table
13524
13525@geindex -gnatyp (gcc)
13526
13527
13528@table @asis
13529
13530@item @code{-gnatyp}
13531
13532@emph{Check pragma casing.}
13533
13534Pragma names must be written in mixed case, that is, the
13535initial letter and any letter following an underscore must be uppercase.
13536All other letters must be lowercase. An exception is that SPARK_Mode is
13537allowed as an alternative for Spark_Mode.
13538@end table
13539
13540@geindex -gnatyr (gcc)
13541
13542
13543@table @asis
13544
13545@item @code{-gnatyr}
13546
13547@emph{Check references.}
13548
13549All identifier references must be cased in the same way as the
13550corresponding declaration. No specific casing style is imposed on
13551identifiers. The only requirement is for consistency of references
13552with declarations.
13553@end table
13554
13555@geindex -gnatys (gcc)
13556
13557
13558@table @asis
13559
13560@item @code{-gnatys}
13561
13562@emph{Check separate specs.}
13563
13564Separate declarations ('specs') are required for subprograms (a
13565body is not allowed to serve as its own declaration). The only
13566exception is that parameterless library level procedures are
13567not required to have a separate declaration. This exception covers
13568the most frequent form of main program procedures.
13569@end table
13570
13571@geindex -gnatyS (gcc)
13572
13573
13574@table @asis
13575
13576@item @code{-gnatyS}
13577
13578@emph{Check no statements after then/else.}
13579
13580No statements are allowed
13581on the same line as a @cite{then} or @cite{else} keyword following the
13582keyword in an @cite{if} statement. @cite{or else} and @cite{and then} are not
13583affected, and a special exception allows a pragma to appear after @cite{else}.
13584@end table
13585
13586@geindex -gnatyt (gcc)
13587
13588
13589@table @asis
13590
13591@item @code{-gnatyt}
13592
13593@emph{Check token spacing.}
13594
13595The following token spacing rules are enforced:
13596
13597
13598@itemize *
13599
13600@item
13601The keywords @cite{abs} and @cite{not} must be followed by a space.
13602
13603@item
13604The token @cite{=>} must be surrounded by spaces.
13605
13606@item
13607The token @cite{<>} must be preceded by a space or a left parenthesis.
13608
13609@item
13610Binary operators other than @cite{**} must be surrounded by spaces.
13611There is no restriction on the layout of the @cite{**} binary operator.
13612
13613@item
13614Colon must be surrounded by spaces.
13615
13616@item
13617Colon-equal (assignment, initialization) must be surrounded by spaces.
13618
13619@item
13620Comma must be the first non-blank character on the line, or be
13621immediately preceded by a non-blank character, and must be followed
13622by a space.
13623
13624@item
13625If the token preceding a left parenthesis ends with a letter or digit, then
13626a space must separate the two tokens.
13627
13628@item
13629If the token following a right parenthesis starts with a letter or digit, then
13630a space must separate the two tokens.
13631
13632@item
13633A right parenthesis must either be the first non-blank character on
13634a line, or it must be preceded by a non-blank character.
13635
13636@item
13637A semicolon must not be preceded by a space, and must not be followed by
13638a non-blank character.
13639
13640@item
13641A unary plus or minus may not be followed by a space.
13642
13643@item
13644A vertical bar must be surrounded by spaces.
13645@end itemize
13646
13647Exactly one blank (and no other white space) must appear between
13648a @cite{not} token and a following @cite{in} token.
13649@end table
13650
13651@geindex -gnatyu (gcc)
13652
13653
13654@table @asis
13655
13656@item @code{-gnatyu}
13657
13658@emph{Check unnecessary blank lines.}
13659
13660Unnecessary blank lines are not allowed. A blank line is considered
13661unnecessary if it appears at the end of the file, or if more than
13662one blank line occurs in sequence.
13663@end table
13664
13665@geindex -gnatyx (gcc)
13666
13667
13668@table @asis
13669
13670@item @code{-gnatyx}
13671
13672@emph{Check extra parentheses.}
13673
13674Unnecessary extra level of parentheses (C-style) are not allowed
13675around conditions in @cite{if} statements, @cite{while} statements and
13676@cite{exit} statements.
13677@end table
13678
13679@geindex -gnatyy (gcc)
13680
13681
13682@table @asis
13683
13684@item @code{-gnatyy}
13685
13686@emph{Set all standard style check options.}
13687
13688This is equivalent to @cite{gnaty3aAbcefhiklmnprst}, that is all checking
13689options enabled with the exception of @emph{-gnatyB}, @emph{-gnatyd},
13690@emph{-gnatyI}, @emph{-gnatyLnnn}, @emph{-gnatyo}, @emph{-gnatyO},
13691@emph{-gnatyS}, @emph{-gnatyu}, and @emph{-gnatyx}.
13692@end table
13693
13694@geindex -gnaty- (gcc)
13695
13696
13697@table @asis
13698
13699@item @code{-gnaty-}
13700
13701@emph{Remove style check options.}
13702
13703This causes any subsequent options in the string to act as canceling the
13704corresponding style check option. To cancel maximum nesting level control,
13705use @emph{L} parameter witout any integer value after that, because any
13706digit following @emph{-} in the parameter string of the @emph{-gnaty}
13707option will be threated as canceling indentation check. The same is true
13708for @emph{M} parameter. @emph{y} and @emph{N} parameters are not
13709allowed after @emph{-}.
13710@end table
13711
13712@geindex -gnaty+ (gcc)
13713
13714
13715@table @asis
13716
13717@item @code{-gnaty+}
13718
13719@emph{Enable style check options.}
13720
13721This causes any subsequent options in the string to enable the corresponding
13722style check option. That is, it cancels the effect of a previous -,
13723if any.
13724@end table
13725
13726@c end of switch description (leave this comment to ease automatic parsing for
13727
13728@c GPS
13729
13730In the above rules, appearing in column one is always permitted, that is,
13731counts as meeting either a requirement for a required preceding space,
13732or as meeting a requirement for no preceding space.
13733
13734Appearing at the end of a line is also always permitted, that is, counts
13735as meeting either a requirement for a following space, or as meeting
13736a requirement for no following space.
13737
13738If any of these style rules is violated, a message is generated giving
13739details on the violation. The initial characters of such messages are
13740always '@cite{(style)}'. Note that these messages are treated as warning
13741messages, so they normally do not prevent the generation of an object
13742file. The @emph{-gnatwe} switch can be used to treat warning messages,
13743including style messages, as fatal errors.
13744
13745The switch @code{-gnaty} on its own (that is not
13746followed by any letters or digits) is equivalent
13747to the use of @emph{-gnatyy} as described above, that is all
13748built-in standard style check options are enabled.
13749
13750The switch @code{-gnatyN} clears any previously set style checks.
13751
13752@node Run-Time Checks,Using gcc for Syntax Checking,Style Checking,Compiler Switches
13753@anchor{gnat_ugn/building_executable_programs_with_gnat run-time-checks}@anchor{101}@anchor{gnat_ugn/building_executable_programs_with_gnat id19}@anchor{10c}
13754@subsection Run-Time Checks
13755
13756
13757@geindex Division by zero
13758
13759@geindex Access before elaboration
13760
13761@geindex Checks
13762@geindex division by zero
13763
13764@geindex Checks
13765@geindex access before elaboration
13766
13767@geindex Checks
13768@geindex stack overflow checking
13769
13770By default, the following checks are suppressed: stack overflow
13771checks, and checks for access before elaboration on subprogram
13772calls. All other checks, including overflow checks, range checks and
13773array bounds checks, are turned on by default. The following @emph{gcc}
13774switches refine this default behavior.
13775
13776@geindex -gnatp (gcc)
13777
13778
13779@table @asis
13780
13781@item @code{-gnatp}
13782
13783@geindex Suppressing checks
13784
13785@geindex Checks
13786@geindex suppressing
13787
13788This switch causes the unit to be compiled
13789as though @cite{pragma Suppress (All_checks)}
13790had been present in the source. Validity checks are also eliminated (in
13791other words @emph{-gnatp} also implies @emph{-gnatVn}.
13792Use this switch to improve the performance
13793of the code at the expense of safety in the presence of invalid data or
13794program bugs.
13795
13796Note that when checks are suppressed, the compiler is allowed, but not
13797required, to omit the checking code. If the run-time cost of the
13798checking code is zero or near-zero, the compiler will generate it even
13799if checks are suppressed. In particular, if the compiler can prove
13800that a certain check will necessarily fail, it will generate code to
13801do an unconditional 'raise', even if checks are suppressed. The
13802compiler warns in this case. Another case in which checks may not be
13803eliminated is when they are embedded in certain run time routines such
13804as math library routines.
13805
13806Of course, run-time checks are omitted whenever the compiler can prove
13807that they will not fail, whether or not checks are suppressed.
13808
13809Note that if you suppress a check that would have failed, program
13810execution is erroneous, which means the behavior is totally
13811unpredictable. The program might crash, or print wrong answers, or
13812do anything else. It might even do exactly what you wanted it to do
13813(and then it might start failing mysteriously next week or next
13814year). The compiler will generate code based on the assumption that
13815the condition being checked is true, which can result in erroneous
13816execution if that assumption is wrong.
13817
13818The checks subject to suppression include all the checks defined by the Ada
13819standard, the additional implementation defined checks @cite{Alignment_Check},
13820@cite{Duplicated_Tag_Check}, @cite{Predicate_Check}, Container_Checks, Tampering_Check,
13821and @cite{Validity_Check}, as well as any checks introduced using @cite{pragma Check_Name}. Note that @cite{Atomic_Synchronization} is not automatically
13822suppressed by use of this option.
13823
13824If the code depends on certain checks being active, you can use
13825pragma @cite{Unsuppress} either as a configuration pragma or as
13826a local pragma to make sure that a specified check is performed
13827even if @emph{gnatp} is specified.
13828
13829The @emph{-gnatp} switch has no effect if a subsequent
13830@emph{-gnat-p} switch appears.
13831@end table
13832
13833@geindex -gnat-p (gcc)
13834
13835@geindex Suppressing checks
13836
13837@geindex Checks
13838@geindex suppressing
13839
13840@geindex Suppress
13841
13842
13843@table @asis
13844
13845@item @code{-gnat-p}
13846
13847This switch cancels the effect of a previous @emph{gnatp} switch.
13848@end table
13849
13850@geindex -gnato?? (gcc)
13851
13852@geindex Overflow checks
13853
13854@geindex Overflow mode
13855
13856@geindex Check
13857@geindex overflow
13858
13859
13860@table @asis
13861
13862@item @code{-gnato??}
13863
13864This switch controls the mode used for computing intermediate
13865arithmetic integer operations, and also enables overflow checking.
13866For a full description of overflow mode and checking control, see
13867the 'Overflow Check Handling in GNAT' appendix in this
13868User's Guide.
13869
13870Overflow checks are always enabled by this switch. The argument
13871controls the mode, using the codes
13872
13873
13874@table @asis
13875
13876@item @emph{1 = STRICT}
13877
13878In STRICT mode, intermediate operations are always done using the
13879base type, and overflow checking ensures that the result is within
13880the base type range.
13881
13882@item @emph{2 = MINIMIZED}
13883
13884In MINIMIZED mode, overflows in intermediate operations are avoided
13885where possible by using a larger integer type for the computation
13886(typically @cite{Long_Long_Integer}). Overflow checking ensures that
13887the result fits in this larger integer type.
13888
13889@item @emph{3 = ELIMINATED}
13890
13891In ELIMINATED mode, overflows in intermediate operations are avoided
13892by using multi-precision arithmetic. In this case, overflow checking
13893has no effect on intermediate operations (since overflow is impossible).
13894@end table
13895
13896If two digits are present after @emph{-gnato} then the first digit
13897sets the mode for expressions outside assertions, and the second digit
13898sets the mode for expressions within assertions. Here assertions is used
13899in the technical sense (which includes for example precondition and
13900postcondition expressions).
13901
13902If one digit is present, the corresponding mode is applicable to both
13903expressions within and outside assertion expressions.
13904
13905If no digits are present, the default is to enable overflow checks
13906and set STRICT mode for both kinds of expressions. This is compatible
13907with the use of @emph{-gnato} in previous versions of GNAT.
13908
13909@geindex Machine_Overflows
13910
13911Note that the @emph{-gnato??} switch does not affect the code generated
13912for any floating-point operations; it applies only to integer semantics.
13913For floating-point, GNAT has the @cite{Machine_Overflows}
13914attribute set to @cite{False} and the normal mode of operation is to
13915generate IEEE NaN and infinite values on overflow or invalid operations
13916(such as dividing 0.0 by 0.0).
13917
13918The reason that we distinguish overflow checking from other kinds of
13919range constraint checking is that a failure of an overflow check, unlike
13920for example the failure of a range check, can result in an incorrect
13921value, but cannot cause random memory destruction (like an out of range
13922subscript), or a wild jump (from an out of range case value). Overflow
13923checking is also quite expensive in time and space, since in general it
13924requires the use of double length arithmetic.
13925
13926Note again that the default is @emph{-gnato11} (equivalent to @emph{-gnato1}),
13927so overflow checking is performed in STRICT mode by default.
13928@end table
13929
13930@geindex -gnatE (gcc)
13931
13932@geindex Elaboration checks
13933
13934@geindex Check
13935@geindex elaboration
13936
13937
13938@table @asis
13939
13940@item @code{-gnatE}
13941
13942Enables dynamic checks for access-before-elaboration
13943on subprogram calls and generic instantiations.
13944Note that @emph{-gnatE} is not necessary for safety, because in the
13945default mode, GNAT ensures statically that the checks would not fail.
13946For full details of the effect and use of this switch,
13947@ref{1e,,Compiling with gcc}.
13948@end table
13949
13950@geindex -fstack-check (gcc)
13951
13952@geindex Stack Overflow Checking
13953
13954@geindex Checks
13955@geindex stack overflow checking
13956
13957
13958@table @asis
13959
13960@item @code{-fstack-check}
13961
13962Activates stack overflow checking. For full details of the effect and use of
13963this switch see @ref{fc,,Stack Overflow Checking}.
13964@end table
13965
13966@geindex Unsuppress
13967
13968The setting of these switches only controls the default setting of the
13969checks. You may modify them using either @cite{Suppress} (to remove
13970checks) or @cite{Unsuppress} (to add back suppressed checks) pragmas in
13971the program source.
13972
13973@node Using gcc for Syntax Checking,Using gcc for Semantic Checking,Run-Time Checks,Compiler Switches
13974@anchor{gnat_ugn/building_executable_programs_with_gnat id20}@anchor{10d}@anchor{gnat_ugn/building_executable_programs_with_gnat using-gcc-for-syntax-checking}@anchor{10e}
13975@subsection Using @emph{gcc} for Syntax Checking
13976
13977
13978@geindex -gnats (gcc)
13979
13980
13981@table @asis
13982
13983@item @code{-gnats}
13984
13985The @cite{s} stands for 'syntax'.
13986
13987Run GNAT in syntax checking only mode. For
13988example, the command
13989
13990@example
13991$ gcc -c -gnats x.adb
13992@end example
13993
13994compiles file @code{x.adb} in syntax-check-only mode. You can check a
13995series of files in a single command
13996, and can use wild cards to specify such a group of files.
13997Note that you must specify the @emph{-c} (compile
13998only) flag in addition to the @emph{-gnats} flag.
13999
14000You may use other switches in conjunction with @emph{-gnats}. In
14001particular, @emph{-gnatl} and @emph{-gnatv} are useful to control the
14002format of any generated error messages.
14003
14004When the source file is empty or contains only empty lines and/or comments,
14005the output is a warning:
14006
14007@example
14008$ gcc -c -gnats -x ada toto.txt
14009toto.txt:1:01: warning: empty file, contains no compilation units
14010$
14011@end example
14012
14013Otherwise, the output is simply the error messages, if any. No object file or
14014ALI file is generated by a syntax-only compilation. Also, no units other
14015than the one specified are accessed. For example, if a unit @cite{X}
14016@emph{with}s a unit @cite{Y}, compiling unit @cite{X} in syntax
14017check only mode does not access the source file containing unit
14018@cite{Y}.
14019
14020@geindex Multiple units
14021@geindex syntax checking
14022
14023Normally, GNAT allows only a single unit in a source file. However, this
14024restriction does not apply in syntax-check-only mode, and it is possible
14025to check a file containing multiple compilation units concatenated
14026together. This is primarily used by the @cite{gnatchop} utility
14027(@ref{38,,Renaming Files with gnatchop}).
14028@end table
14029
14030@node Using gcc for Semantic Checking,Compiling Different Versions of Ada,Using gcc for Syntax Checking,Compiler Switches
14031@anchor{gnat_ugn/building_executable_programs_with_gnat id21}@anchor{10f}@anchor{gnat_ugn/building_executable_programs_with_gnat using-gcc-for-semantic-checking}@anchor{110}
14032@subsection Using @emph{gcc} for Semantic Checking
14033
14034
14035@geindex -gnatc (gcc)
14036
14037
14038@table @asis
14039
14040@item @code{-gnatc}
14041
14042The @cite{c} stands for 'check'.
14043Causes the compiler to operate in semantic check mode,
14044with full checking for all illegalities specified in the
14045Ada Reference Manual, but without generation of any object code
14046(no object file is generated).
14047
14048Because dependent files must be accessed, you must follow the GNAT
14049semantic restrictions on file structuring to operate in this mode:
14050
14051
14052@itemize *
14053
14054@item
14055The needed source files must be accessible
14056(see @ref{8e,,Search Paths and the Run-Time Library (RTL)}).
14057
14058@item
14059Each file must contain only one compilation unit.
14060
14061@item
14062The file name and unit name must match (@ref{54,,File Naming Rules}).
14063@end itemize
14064
14065The output consists of error messages as appropriate. No object file is
14066generated. An @code{ALI} file is generated for use in the context of
14067cross-reference tools, but this file is marked as not being suitable
14068for binding (since no object file is generated).
14069The checking corresponds exactly to the notion of
14070legality in the Ada Reference Manual.
14071
14072Any unit can be compiled in semantics-checking-only mode, including
14073units that would not normally be compiled (subunits,
14074and specifications where a separate body is present).
14075@end table
14076
14077@node Compiling Different Versions of Ada,Character Set Control,Using gcc for Semantic Checking,Compiler Switches
14078@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{111}
14079@subsection Compiling Different Versions of Ada
14080
14081
14082The switches described in this section allow you to explicitly specify
14083the version of the Ada language that your programs are written in.
14084The default mode is Ada 2012,
14085but you can also specify Ada 95, Ada 2005 mode, or
14086indicate Ada 83 compatibility mode.
14087
14088@geindex Compatibility with Ada 83
14089
14090@geindex -gnat83 (gcc)
14091
14092@geindex ACVC
14093@geindex Ada 83 tests
14094
14095@geindex Ada 83 mode
14096
14097
14098@table @asis
14099
14100@item @code{-gnat83} (Ada 83 Compatibility Mode)
14101
14102Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
14103specifies that the program is to be compiled in Ada 83 mode. With
14104@emph{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
14105semantics where this can be done easily.
14106It is not possible to guarantee this switch does a perfect
14107job; some subtle tests, such as are
14108found in earlier ACVC tests (and that have been removed from the ACATS suite
14109for Ada 95), might not compile correctly.
14110Nevertheless, this switch may be useful in some circumstances, for example
14111where, due to contractual reasons, existing code needs to be maintained
14112using only Ada 83 features.
14113
14114With few exceptions (most notably the need to use @cite{<>} on
14115unconstrained
14116@geindex Generic formal parameters
14117generic formal parameters,
14118the use of the new Ada 95 / Ada 2005
14119reserved words, and the use of packages
14120with optional bodies), it is not necessary to specify the
14121@emph{-gnat83} switch when compiling Ada 83 programs, because, with rare
14122exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
14123a correct Ada 83 program is usually also a correct program
14124in these later versions of the language standard. For further information
14125please refer to the @cite{Compatibility_and_Porting_Guide} chapter in the
14126@cite{GNAT Reference Manual}.
14127@end table
14128
14129@geindex -gnat95 (gcc)
14130
14131@geindex Ada 95 mode
14132
14133
14134@table @asis
14135
14136@item @code{-gnat95} (Ada 95 mode)
14137
14138This switch directs the compiler to implement the Ada 95 version of the
14139language.
14140Since Ada 95 is almost completely upwards
14141compatible with Ada 83, Ada 83 programs may generally be compiled using
14142this switch (see the description of the @emph{-gnat83} switch for further
14143information about Ada 83 mode).
14144If an Ada 2005 program is compiled in Ada 95 mode,
14145uses of the new Ada 2005 features will cause error
14146messages or warnings.
14147
14148This switch also can be used to cancel the effect of a previous
14149@emph{-gnat83}, @emph{-gnat05/2005}, or @emph{-gnat12/2012}
14150switch earlier in the command line.
14151@end table
14152
14153@geindex -gnat05 (gcc)
14154
14155@geindex -gnat2005 (gcc)
14156
14157@geindex Ada 2005 mode
14158
14159
14160@table @asis
14161
14162@item @code{-gnat05} or @code{-gnat2005} (Ada 2005 mode)
14163
14164This switch directs the compiler to implement the Ada 2005 version of the
14165language, as documented in the official Ada standards document.
14166Since Ada 2005 is almost completely upwards
14167compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
14168may generally be compiled using this switch (see the description of the
14169@emph{-gnat83} and @emph{-gnat95} switches for further
14170information).
14171@end table
14172
14173@geindex -gnat12 (gcc)
14174
14175@geindex -gnat2012 (gcc)
14176
14177@geindex Ada 2012 mode
14178
14179
14180@table @asis
14181
14182@item @code{-gnat12} or @code{-gnat2012} (Ada 2012 mode)
14183
14184This switch directs the compiler to implement the Ada 2012 version of the
14185language (also the default).
14186Since Ada 2012 is almost completely upwards
14187compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
14188Ada 83 and Ada 95 programs
14189may generally be compiled using this switch (see the description of the
14190@emph{-gnat83}, @emph{-gnat95}, and @emph{-gnat05/2005} switches
14191for further information).
14192@end table
14193
14194@geindex -gnatX (gcc)
14195
14196@geindex Ada language extensions
14197
14198@geindex GNAT extensions
14199
14200
14201@table @asis
14202
14203@item @code{-gnatX} (Enable GNAT Extensions)
14204
14205This switch directs the compiler to implement the latest version of the
14206language (currently Ada 2012) and also to enable certain GNAT implementation
14207extensions that are not part of any Ada standard. For a full list of these
14208extensions, see the GNAT reference manual.
14209@end table
14210
14211@node Character Set Control,File Naming Control,Compiling Different Versions of Ada,Compiler Switches
14212@anchor{gnat_ugn/building_executable_programs_with_gnat id23}@anchor{112}@anchor{gnat_ugn/building_executable_programs_with_gnat character-set-control}@anchor{4a}
14213@subsection Character Set Control
14214
14215
14216@geindex -gnati (gcc)
14217
14218
14219@table @asis
14220
14221@item @code{-gnati@emph{c}}
14222
14223Normally GNAT recognizes the Latin-1 character set in source program
14224identifiers, as described in the Ada Reference Manual.
14225This switch causes
14226GNAT to recognize alternate character sets in identifiers. @cite{c} is a
14227single character  indicating the character set, as follows:
14228
14229
14230@multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
14231@item
14232
14233@emph{1}
14234
14235@tab
14236
14237ISO 8859-1 (Latin-1) identifiers
14238
14239@item
14240
14241@emph{2}
14242
14243@tab
14244
14245ISO 8859-2 (Latin-2) letters allowed in identifiers
14246
14247@item
14248
14249@emph{3}
14250
14251@tab
14252
14253ISO 8859-3 (Latin-3) letters allowed in identifiers
14254
14255@item
14256
14257@emph{4}
14258
14259@tab
14260
14261ISO 8859-4 (Latin-4) letters allowed in identifiers
14262
14263@item
14264
14265@emph{5}
14266
14267@tab
14268
14269ISO 8859-5 (Cyrillic) letters allowed in identifiers
14270
14271@item
14272
14273@emph{9}
14274
14275@tab
14276
14277ISO 8859-15 (Latin-9) letters allowed in identifiers
14278
14279@item
14280
14281@emph{p}
14282
14283@tab
14284
14285IBM PC letters (code page 437) allowed in identifiers
14286
14287@item
14288
14289@emph{8}
14290
14291@tab
14292
14293IBM PC letters (code page 850) allowed in identifiers
14294
14295@item
14296
14297@emph{f}
14298
14299@tab
14300
14301Full upper-half codes allowed in identifiers
14302
14303@item
14304
14305@emph{n}
14306
14307@tab
14308
14309No upper-half codes allowed in identifiers
14310
14311@item
14312
14313@emph{w}
14314
14315@tab
14316
14317Wide-character codes (that is, codes greater than 255)
14318allowed in identifiers
14319
14320@end multitable
14321
14322
14323See @ref{40,,Foreign Language Representation} for full details on the
14324implementation of these character sets.
14325@end table
14326
14327@geindex -gnatW (gcc)
14328
14329
14330@table @asis
14331
14332@item @code{-gnatW@emph{e}}
14333
14334Specify the method of encoding for wide characters.
14335@cite{e} is one of the following:
14336
14337
14338@multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
14339@item
14340
14341@emph{h}
14342
14343@tab
14344
14345Hex encoding (brackets coding also recognized)
14346
14347@item
14348
14349@emph{u}
14350
14351@tab
14352
14353Upper half encoding (brackets encoding also recognized)
14354
14355@item
14356
14357@emph{s}
14358
14359@tab
14360
14361Shift/JIS encoding (brackets encoding also recognized)
14362
14363@item
14364
14365@emph{e}
14366
14367@tab
14368
14369EUC encoding (brackets encoding also recognized)
14370
14371@item
14372
14373@emph{8}
14374
14375@tab
14376
14377UTF-8 encoding (brackets encoding also recognized)
14378
14379@item
14380
14381@emph{b}
14382
14383@tab
14384
14385Brackets encoding only (default value)
14386
14387@end multitable
14388
14389
14390For full details on these encoding
14391methods see @ref{50,,Wide_Character Encodings}.
14392Note that brackets coding is always accepted, even if one of the other
14393options is specified, so for example @emph{-gnatW8} specifies that both
14394brackets and UTF-8 encodings will be recognized. The units that are
14395with'ed directly or indirectly will be scanned using the specified
14396representation scheme, and so if one of the non-brackets scheme is
14397used, it must be used consistently throughout the program. However,
14398since brackets encoding is always recognized, it may be conveniently
14399used in standard libraries, allowing these libraries to be used with
14400any of the available coding schemes.
14401
14402Note that brackets encoding only applies to program text. Within comments,
14403brackets are considered to be normal graphic characters, and bracket sequences
14404are never recognized as wide characters.
14405
14406If no @emph{-gnatW?} parameter is present, then the default
14407representation is normally Brackets encoding only. However, if the
14408first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
14409byte order mark or BOM for UTF-8), then these three characters are
14410skipped and the default representation for the file is set to UTF-8.
14411
14412Note that the wide character representation that is specified (explicitly
14413or by default) for the main program also acts as the default encoding used
14414for Wide_Text_IO files if not specifically overridden by a WCEM form
14415parameter.
14416@end table
14417
14418When no @emph{-gnatW?} is specified, then characters (other than wide
14419characters represented using brackets notation) are treated as 8-bit
14420Latin-1 codes. The codes recognized are the Latin-1 graphic characters,
14421and ASCII format effectors (CR, LF, HT, VT). Other lower half control
14422characters in the range 16#00#..16#1F# are not accepted in program text
14423or in comments. Upper half control characters (16#80#..16#9F#) are rejected
14424in program text, but allowed and ignored in comments. Note in particular
14425that the Next Line (NEL) character whose encoding is 16#85# is not recognized
14426as an end of line in this default mode. If your source program contains
14427instances of the NEL character used as a line terminator,
14428you must use UTF-8 encoding for the whole
14429source program. In default mode, all lines must be ended by a standard
14430end of line sequence (CR, CR/LF, or LF).
14431
14432Note that the convention of simply accepting all upper half characters in
14433comments means that programs that use standard ASCII for program text, but
14434UTF-8 encoding for comments are accepted in default mode, providing that the
14435comments are ended by an appropriate (CR, or CR/LF, or LF) line terminator.
14436This is a common mode for many programs with foreign language comments.
14437
14438@node File Naming Control,Subprogram Inlining Control,Character Set Control,Compiler Switches
14439@anchor{gnat_ugn/building_executable_programs_with_gnat file-naming-control}@anchor{113}@anchor{gnat_ugn/building_executable_programs_with_gnat id24}@anchor{114}
14440@subsection File Naming Control
14441
14442
14443@geindex -gnatk (gcc)
14444
14445
14446@table @asis
14447
14448@item @code{-gnatk@emph{n}}
14449
14450Activates file name 'krunching'. @cite{n}, a decimal integer in the range
144511-999, indicates the maximum allowable length of a file name (not
14452including the @code{.ads} or @code{.adb} extension). The default is not
14453to enable file name krunching.
14454
14455For the source file naming rules, @ref{54,,File Naming Rules}.
14456@end table
14457
14458@node Subprogram Inlining Control,Auxiliary Output Control,File Naming Control,Compiler Switches
14459@anchor{gnat_ugn/building_executable_programs_with_gnat subprogram-inlining-control}@anchor{115}@anchor{gnat_ugn/building_executable_programs_with_gnat id25}@anchor{116}
14460@subsection Subprogram Inlining Control
14461
14462
14463@geindex -gnatn (gcc)
14464
14465
14466@table @asis
14467
14468@item @code{-gnatn[12]}
14469
14470The @cite{n} here is intended to suggest the first syllable of the
14471word 'inline'.
14472GNAT recognizes and processes @cite{Inline} pragmas. However, for the
14473inlining to actually occur, optimization must be enabled and, in order
14474to enable inlining of subprograms specified by pragma @cite{Inline},
14475you must also specify this switch.
14476In the absence of this switch, GNAT does not attempt
14477inlining and does not need to access the bodies of
14478subprograms for which @cite{pragma Inline} is specified if they are not
14479in the current unit.
14480
14481You can optionally specify the inlining level: 1 for moderate inlining across
14482modules, which is a good compromise between compilation times and performances
14483at run time, or 2 for full inlining across modules, which may bring about
14484longer compilation times. If no inlining level is specified, the compiler will
14485pick it based on the optimization level: 1 for @emph{-O1}, @emph{-O2} or
14486@emph{-Os} and 2 for @emph{-O3}.
14487
14488If you specify this switch the compiler will access these bodies,
14489creating an extra source dependency for the resulting object file, and
14490where possible, the call will be inlined.
14491For further details on when inlining is possible
14492see @ref{117,,Inlining of Subprograms}.
14493@end table
14494
14495@geindex -gnatN (gcc)
14496
14497
14498@table @asis
14499
14500@item @code{-gnatN}
14501
14502This switch activates front-end inlining which also
14503generates additional dependencies.
14504
14505When using a gcc-based back end (in practice this means using any version
14506of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
14507@emph{-gnatN} is deprecated, and the use of @emph{-gnatn} is preferred.
14508Historically front end inlining was more extensive than the gcc back end
14509inlining, but that is no longer the case.
14510@end table
14511
14512@node Auxiliary Output Control,Debugging Control,Subprogram Inlining Control,Compiler Switches
14513@anchor{gnat_ugn/building_executable_programs_with_gnat auxiliary-output-control}@anchor{118}@anchor{gnat_ugn/building_executable_programs_with_gnat id26}@anchor{119}
14514@subsection Auxiliary Output Control
14515
14516
14517@geindex -gnatt (gcc)
14518
14519@geindex Writing internal trees
14520
14521@geindex Internal trees
14522@geindex writing to file
14523
14524
14525@table @asis
14526
14527@item @code{-gnatt}
14528
14529Causes GNAT to write the internal tree for a unit to a file (with the
14530extension @code{.adt}.
14531This not normally required, but is used by separate analysis tools.
14532Typically
14533these tools do the necessary compilations automatically, so you should
14534not have to specify this switch in normal operation.
14535Note that the combination of switches @emph{-gnatct}
14536generates a tree in the form required by ASIS applications.
14537@end table
14538
14539@geindex -gnatu (gcc)
14540
14541
14542@table @asis
14543
14544@item @code{-gnatu}
14545
14546Print a list of units required by this compilation on @code{stdout}.
14547The listing includes all units on which the unit being compiled depends
14548either directly or indirectly.
14549@end table
14550
14551@geindex -pass-exit-codes (gcc)
14552
14553
14554@table @asis
14555
14556@item @code{-pass-exit-codes}
14557
14558If this switch is not used, the exit code returned by @emph{gcc} when
14559compiling multiple files indicates whether all source files have
14560been successfully used to generate object files or not.
14561
14562When @emph{-pass-exit-codes} is used, @emph{gcc} exits with an extended
14563exit status and allows an integrated development environment to better
14564react to a compilation failure. Those exit status are:
14565
14566
14567@multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
14568@item
14569
14570@emph{5}
14571
14572@tab
14573
14574There was an error in at least one source file.
14575
14576@item
14577
14578@emph{3}
14579
14580@tab
14581
14582At least one source file did not generate an object file.
14583
14584@item
14585
14586@emph{2}
14587
14588@tab
14589
14590The compiler died unexpectedly (internal error for example).
14591
14592@item
14593
14594@emph{0}
14595
14596@tab
14597
14598An object file has been generated for every source file.
14599
14600@end multitable
14601
14602@end table
14603
14604@node Debugging Control,Exception Handling Control,Auxiliary Output Control,Compiler Switches
14605@anchor{gnat_ugn/building_executable_programs_with_gnat debugging-control}@anchor{11a}@anchor{gnat_ugn/building_executable_programs_with_gnat id27}@anchor{11b}
14606@subsection Debugging Control
14607
14608
14609@quotation
14610
14611@geindex Debugging options
14612@end quotation
14613
14614@geindex -gnatd (gcc)
14615
14616
14617@table @asis
14618
14619@item @code{-gnatd@emph{x}}
14620
14621Activate internal debugging switches. @cite{x} is a letter or digit, or
14622string of letters or digits, which specifies the type of debugging
14623outputs desired. Normally these are used only for internal development
14624or system debugging purposes. You can find full documentation for these
14625switches in the body of the @cite{Debug} unit in the compiler source
14626file @code{debug.adb}.
14627@end table
14628
14629@geindex -gnatG (gcc)
14630
14631
14632@table @asis
14633
14634@item @code{-gnatG[=@emph{nn}]}
14635
14636This switch causes the compiler to generate auxiliary output containing
14637a pseudo-source listing of the generated expanded code. Like most Ada
14638compilers, GNAT works by first transforming the high level Ada code into
14639lower level constructs. For example, tasking operations are transformed
14640into calls to the tasking run-time routines. A unique capability of GNAT
14641is to list this expanded code in a form very close to normal Ada source.
14642This is very useful in understanding the implications of various Ada
14643usage on the efficiency of the generated code. There are many cases in
14644Ada (e.g., the use of controlled types), where simple Ada statements can
14645generate a lot of run-time code. By using @emph{-gnatG} you can identify
14646these cases, and consider whether it may be desirable to modify the coding
14647approach to improve efficiency.
14648
14649The optional parameter @cite{nn} if present after -gnatG specifies an
14650alternative maximum line length that overrides the normal default of 72.
14651This value is in the range 40-999999, values less than 40 being silently
14652reset to 40. The equal sign is optional.
14653
14654The format of the output is very similar to standard Ada source, and is
14655easily understood by an Ada programmer. The following special syntactic
14656additions correspond to low level features used in the generated code that
14657do not have any exact analogies in pure Ada source form. The following
14658is a partial list of these special constructions. See the spec
14659of package @cite{Sprint} in file @code{sprint.ads} for a full list.
14660
14661@geindex -gnatL (gcc)
14662
14663If the switch @emph{-gnatL} is used in conjunction with
14664@emph{-gnatG}, then the original source lines are interspersed
14665in the expanded source (as comment lines with the original line number).
14666
14667
14668@table @asis
14669
14670@item @code{new @emph{xxx} [storage_pool = @emph{yyy}]}
14671
14672Shows the storage pool being used for an allocator.
14673
14674@item @code{at end @emph{procedure-name};}
14675
14676Shows the finalization (cleanup) procedure for a scope.
14677
14678@item @code{(if @emph{expr} then @emph{expr} else @emph{expr})}
14679
14680Conditional expression equivalent to the @cite{x?y:z} construction in C.
14681
14682@item @code{@emph{target}^(@emph{source})}
14683
14684A conversion with floating-point truncation instead of rounding.
14685
14686@item @code{@emph{target}?(@emph{source})}
14687
14688A conversion that bypasses normal Ada semantic checking. In particular
14689enumeration types and fixed-point types are treated simply as integers.
14690
14691@item @code{@emph{target}?^(@emph{source})}
14692
14693Combines the above two cases.
14694@end table
14695
14696@code{@emph{x} #/ @emph{y}}
14697
14698@code{@emph{x} #mod @emph{y}}
14699
14700@code{@emph{x} # @emph{y}}
14701
14702
14703@table @asis
14704
14705@item @code{@emph{x} #rem @emph{y}}
14706
14707A division or multiplication of fixed-point values which are treated as
14708integers without any kind of scaling.
14709
14710@item @code{free @emph{expr} [storage_pool = @emph{xxx}]}
14711
14712Shows the storage pool associated with a @cite{free} statement.
14713
14714@item @code{[subtype or type declaration]}
14715
14716Used to list an equivalent declaration for an internally generated
14717type that is referenced elsewhere in the listing.
14718
14719@item @code{freeze @emph{type-name} [@emph{actions}]}
14720
14721Shows the point at which @cite{type-name} is frozen, with possible
14722associated actions to be performed at the freeze point.
14723
14724@item @code{reference @emph{itype}}
14725
14726Reference (and hence definition) to internal type @cite{itype}.
14727
14728@item @code{@emph{function-name}! (@emph{arg}, @emph{arg}, @emph{arg})}
14729
14730Intrinsic function call.
14731
14732@item @code{@emph{label-name} : label}
14733
14734Declaration of label @cite{labelname}.
14735
14736@item @code{#$ @emph{subprogram-name}}
14737
14738An implicit call to a run-time support routine
14739(to meet the requirement of H.3.1(9) in a
14740convenient manner).
14741
14742@item @code{@emph{expr} && @emph{expr} && @emph{expr} ... && @emph{expr}}
14743
14744A multiple concatenation (same effect as @cite{expr} & @cite{expr} &
14745@cite{expr}, but handled more efficiently).
14746
14747@item @code{[constraint_error]}
14748
14749Raise the @cite{Constraint_Error} exception.
14750
14751@item @code{@emph{expression}'reference}
14752
14753A pointer to the result of evaluating @{expression@}.
14754
14755@item @code{@emph{target-type}!(@emph{source-expression})}
14756
14757An unchecked conversion of @cite{source-expression} to @cite{target-type}.
14758
14759@item @code{[@emph{numerator}/@emph{denominator}]}
14760
14761Used to represent internal real literals (that) have no exact
14762representation in base 2-16 (for example, the result of compile time
14763evaluation of the expression 1.0/27.0).
14764@end table
14765@end table
14766
14767@geindex -gnatD (gcc)
14768
14769
14770@table @asis
14771
14772@item @code{-gnatD[=nn]}
14773
14774When used in conjunction with @emph{-gnatG}, this switch causes
14775the expanded source, as described above for
14776@emph{-gnatG} to be written to files with names
14777@code{xxx.dg}, where @code{xxx} is the normal file name,
14778instead of to the standard output file. For
14779example, if the source file name is @code{hello.adb}, then a file
14780@code{hello.adb.dg} will be written.  The debugging
14781information generated by the @emph{gcc} @emph{-g} switch
14782will refer to the generated @code{xxx.dg} file. This allows
14783you to do source level debugging using the generated code which is
14784sometimes useful for complex code, for example to find out exactly
14785which part of a complex construction raised an exception. This switch
14786also suppress generation of cross-reference information (see
14787@emph{-gnatx}) since otherwise the cross-reference information
14788would refer to the @code{.dg} file, which would cause
14789confusion since this is not the original source file.
14790
14791Note that @emph{-gnatD} actually implies @emph{-gnatG}
14792automatically, so it is not necessary to give both options.
14793In other words @emph{-gnatD} is equivalent to @emph{-gnatDG}).
14794
14795@geindex -gnatL (gcc)
14796
14797If the switch @emph{-gnatL} is used in conjunction with
14798@emph{-gnatDG}, then the original source lines are interspersed
14799in the expanded source (as comment lines with the original line number).
14800
14801The optional parameter @cite{nn} if present after -gnatD specifies an
14802alternative maximum line length that overrides the normal default of 72.
14803This value is in the range 40-999999, values less than 40 being silently
14804reset to 40. The equal sign is optional.
14805@end table
14806
14807@geindex -gnatr (gcc)
14808
14809@geindex pragma Restrictions
14810
14811
14812@table @asis
14813
14814@item @code{-gnatr}
14815
14816This switch causes pragma Restrictions to be treated as Restriction_Warnings
14817so that violation of restrictions causes warnings rather than illegalities.
14818This is useful during the development process when new restrictions are added
14819or investigated. The switch also causes pragma Profile to be treated as
14820Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
14821restriction warnings rather than restrictions.
14822@end table
14823
14824@geindex -gnatR (gcc)
14825
14826
14827@table @asis
14828
14829@item @code{-gnatR[0|1|2|3[s]]}
14830
14831This switch controls output from the compiler of a listing showing
14832representation information for declared types and objects. For
14833@emph{-gnatR0}, no information is output (equivalent to omitting
14834the @emph{-gnatR} switch). For @emph{-gnatR1} (which is the default,
14835so @emph{-gnatR} with no parameter has the same effect), size and alignment
14836information is listed for declared array and record types. For
14837@emph{-gnatR2}, size and alignment information is listed for all
14838declared types and objects. The @cite{Linker_Section} is also listed for any
14839entity for which the @cite{Linker_Section} is set explicitly or implicitly (the
14840latter case occurs for objects of a type for which a @cite{Linker_Section}
14841is set).
14842
14843Finally @emph{-gnatR3} includes symbolic
14844expressions for values that are computed at run time for
14845variant records. These symbolic expressions have a mostly obvious
14846format with #n being used to represent the value of the n'th
14847discriminant. See source files @code{repinfo.ads/adb} in the
14848@cite{GNAT} sources for full details on the format of @emph{-gnatR3}
14849output. If the switch is followed by an s (e.g., @emph{-gnatR2s}), then
14850the output is to a file with the name @code{file.rep} where
14851file is the name of the corresponding source file.
14852
14853@item @code{-gnatRm[s]}
14854
14855This form of the switch controls output of subprogram conventions
14856and parameter passing mechanisms for all subprograms. A following
14857@cite{s} means output to a file as described above.
14858
14859Note that it is possible for record components to have zero size. In
14860this case, the component clause uses an obvious extension of permitted
14861Ada syntax, for example @cite{at 0 range 0 .. -1}.
14862
14863Representation information requires that code be generated (since it is the
14864code generator that lays out complex data structures). If an attempt is made
14865to output representation information when no code is generated, for example
14866when a subunit is compiled on its own, then no information can be generated
14867and the compiler outputs a message to this effect.
14868@end table
14869
14870@geindex -gnatS (gcc)
14871
14872
14873@table @asis
14874
14875@item @code{-gnatS}
14876
14877The use of the switch @emph{-gnatS} for an
14878Ada compilation will cause the compiler to output a
14879representation of package Standard in a form very
14880close to standard Ada. It is not quite possible to
14881do this entirely in standard Ada (since new
14882numeric base types cannot be created in standard
14883Ada), but the output is easily
14884readable to any Ada programmer, and is useful to
14885determine the characteristics of target dependent
14886types in package Standard.
14887@end table
14888
14889@geindex -gnatx (gcc)
14890
14891
14892@table @asis
14893
14894@item @code{-gnatx}
14895
14896Normally the compiler generates full cross-referencing information in
14897the @code{ALI} file. This information is used by a number of tools,
14898including @cite{gnatfind} and @cite{gnatxref}. The @emph{-gnatx} switch
14899suppresses this information. This saves some space and may slightly
14900speed up compilation, but means that these tools cannot be used.
14901@end table
14902
14903@node Exception Handling Control,Units to Sources Mapping Files,Debugging Control,Compiler Switches
14904@anchor{gnat_ugn/building_executable_programs_with_gnat id28}@anchor{11c}@anchor{gnat_ugn/building_executable_programs_with_gnat exception-handling-control}@anchor{11d}
14905@subsection Exception Handling Control
14906
14907
14908GNAT uses two methods for handling exceptions at run-time. The
14909@cite{setjmp/longjmp} method saves the context when entering
14910a frame with an exception handler. Then when an exception is
14911raised, the context can be restored immediately, without the
14912need for tracing stack frames. This method provides very fast
14913exception propagation, but introduces significant overhead for
14914the use of exception handlers, even if no exception is raised.
14915
14916The other approach is called 'zero cost' exception handling.
14917With this method, the compiler builds static tables to describe
14918the exception ranges. No dynamic code is required when entering
14919a frame containing an exception handler. When an exception is
14920raised, the tables are used to control a back trace of the
14921subprogram invocation stack to locate the required exception
14922handler. This method has considerably poorer performance for
14923the propagation of exceptions, but there is no overhead for
14924exception handlers if no exception is raised. Note that in this
14925mode and in the context of mixed Ada and C/C++ programming,
14926to propagate an exception through a C/C++ code, the C/C++ code
14927must be compiled with the @emph{-funwind-tables} GCC's
14928option.
14929
14930The following switches may be used to control which of the
14931two exception handling methods is used.
14932
14933@geindex --RTS=sjlj (gnatmake)
14934
14935
14936@table @asis
14937
14938@item @code{--RTS=sjlj}
14939
14940This switch causes the setjmp/longjmp run-time (when available) to be used
14941for exception handling. If the default
14942mechanism for the target is zero cost exceptions, then
14943this switch can be used to modify this default, and must be
14944used for all units in the partition.
14945This option is rarely used. One case in which it may be
14946advantageous is if you have an application where exception
14947raising is common and the overall performance of the
14948application is improved by favoring exception propagation.
14949@end table
14950
14951@geindex --RTS=zcx (gnatmake)
14952
14953@geindex Zero Cost Exceptions
14954
14955
14956@table @asis
14957
14958@item @code{--RTS=zcx}
14959
14960This switch causes the zero cost approach to be used
14961for exception handling. If this is the default mechanism for the
14962target (see below), then this switch is unneeded. If the default
14963mechanism for the target is setjmp/longjmp exceptions, then
14964this switch can be used to modify this default, and must be
14965used for all units in the partition.
14966This option can only be used if the zero cost approach
14967is available for the target in use, otherwise it will generate an error.
14968@end table
14969
14970The same option @emph{--RTS} must be used both for @emph{gcc}
14971and @emph{gnatbind}. Passing this option to @emph{gnatmake}
14972(@ref{e2,,Switches for gnatmake}) will ensure the required consistency
14973through the compilation and binding steps.
14974
14975@node Units to Sources Mapping Files,Code Generation Control,Exception Handling Control,Compiler Switches
14976@anchor{gnat_ugn/building_executable_programs_with_gnat id29}@anchor{11e}@anchor{gnat_ugn/building_executable_programs_with_gnat units-to-sources-mapping-files}@anchor{ff}
14977@subsection Units to Sources Mapping Files
14978
14979
14980@geindex -gnatem (gcc)
14981
14982
14983@table @asis
14984
14985@item @code{-gnatem=@emph{path}}
14986
14987A mapping file is a way to communicate to the compiler two mappings:
14988from unit names to file names (without any directory information) and from
14989file names to path names (with full directory information). These mappings
14990are used by the compiler to short-circuit the path search.
14991
14992The use of mapping files is not required for correct operation of the
14993compiler, but mapping files can improve efficiency, particularly when
14994sources are read over a slow network connection. In normal operation,
14995you need not be concerned with the format or use of mapping files,
14996and the @emph{-gnatem} switch is not a switch that you would use
14997explicitly. It is intended primarily for use by automatic tools such as
14998@emph{gnatmake} running under the project file facility. The
14999description here of the format of mapping files is provided
15000for completeness and for possible use by other tools.
15001
15002A mapping file is a sequence of sets of three lines. In each set, the
15003first line is the unit name, in lower case, with @cite{%s} appended
15004for specs and @cite{%b} appended for bodies; the second line is the
15005file name; and the third line is the path name.
15006
15007Example:
15008
15009@example
15010main%b
15011main.2.ada
15012/gnat/project1/sources/main.2.ada
15013@end example
15014
15015When the switch @emph{-gnatem} is specified, the compiler will
15016create in memory the two mappings from the specified file. If there is
15017any problem (nonexistent file, truncated file or duplicate entries),
15018no mapping will be created.
15019
15020Several @emph{-gnatem} switches may be specified; however, only the
15021last one on the command line will be taken into account.
15022
15023When using a project file, @emph{gnatmake} creates a temporary
15024mapping file and communicates it to the compiler using this switch.
15025@end table
15026
15027@node Code Generation Control,,Units to Sources Mapping Files,Compiler Switches
15028@anchor{gnat_ugn/building_executable_programs_with_gnat code-generation-control}@anchor{11f}@anchor{gnat_ugn/building_executable_programs_with_gnat id30}@anchor{120}
15029@subsection Code Generation Control
15030
15031
15032The GCC technology provides a wide range of target dependent
15033@code{-m} switches for controlling
15034details of code generation with respect to different versions of
15035architectures. This includes variations in instruction sets (e.g.,
15036different members of the power pc family), and different requirements
15037for optimal arrangement of instructions (e.g., different members of
15038the x86 family). The list of available @emph{-m} switches may be
15039found in the GCC documentation.
15040
15041Use of these @emph{-m} switches may in some cases result in improved
15042code performance.
15043
15044The GNAT technology is tested and qualified without any
15045@code{-m} switches,
15046so generally the most reliable approach is to avoid the use of these
15047switches. However, we generally expect most of these switches to work
15048successfully with GNAT, and many customers have reported successful
15049use of these options.
15050
15051Our general advice is to avoid the use of @emph{-m} switches unless
15052special needs lead to requirements in this area. In particular,
15053there is no point in using @emph{-m} switches to improve performance
15054unless you actually see a performance improvement.
15055
15056@node Binding with gnatbind,Linking with gnatlink,Compiler Switches,Building Executable Programs with GNAT
15057@anchor{gnat_ugn/building_executable_programs_with_gnat binding-with-gnatbind}@anchor{1f}@anchor{gnat_ugn/building_executable_programs_with_gnat id31}@anchor{121}
15058@section Binding with @cite{gnatbind}
15059
15060
15061@geindex gnatbind
15062
15063This chapter describes the GNAT binder, @cite{gnatbind}, which is used
15064to bind compiled GNAT objects.
15065
15066Note: to invoke @cite{gnatbind} with a project file, use the @cite{gnat}
15067driver (see @ref{122,,The GNAT Driver and Project Files}).
15068
15069The @cite{gnatbind} program performs four separate functions:
15070
15071
15072@itemize *
15073
15074@item
15075Checks that a program is consistent, in accordance with the rules in
15076Chapter 10 of the Ada Reference Manual. In particular, error
15077messages are generated if a program uses inconsistent versions of a
15078given unit.
15079
15080@item
15081Checks that an acceptable order of elaboration exists for the program
15082and issues an error message if it cannot find an order of elaboration
15083that satisfies the rules in Chapter 10 of the Ada Language Manual.
15084
15085@item
15086Generates a main program incorporating the given elaboration order.
15087This program is a small Ada package (body and spec) that
15088must be subsequently compiled
15089using the GNAT compiler. The necessary compilation step is usually
15090performed automatically by @emph{gnatlink}. The two most important
15091functions of this program
15092are to call the elaboration routines of units in an appropriate order
15093and to call the main program.
15094
15095@item
15096Determines the set of object files required by the given main program.
15097This information is output in the forms of comments in the generated program,
15098to be read by the @emph{gnatlink} utility used to link the Ada application.
15099@end itemize
15100
15101@menu
15102* Running gnatbind::
15103* Switches for gnatbind::
15104* Command-Line Access::
15105* Search Paths for gnatbind::
15106* Examples of gnatbind Usage::
15107
15108@end menu
15109
15110@node Running gnatbind,Switches for gnatbind,,Binding with gnatbind
15111@anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatbind}@anchor{123}@anchor{gnat_ugn/building_executable_programs_with_gnat id32}@anchor{124}
15112@subsection Running @cite{gnatbind}
15113
15114
15115The form of the @cite{gnatbind} command is
15116
15117@example
15118$ gnatbind [`switches`] `mainprog`[.ali] [`switches`]
15119@end example
15120
15121where @code{mainprog.adb} is the Ada file containing the main program
15122unit body. @cite{gnatbind} constructs an Ada
15123package in two files whose names are
15124@code{b~mainprog.ads}, and @code{b~mainprog.adb}.
15125For example, if given the
15126parameter @code{hello.ali}, for a main program contained in file
15127@code{hello.adb}, the binder output files would be @code{b~hello.ads}
15128and @code{b~hello.adb}.
15129
15130When doing consistency checking, the binder takes into consideration
15131any source files it can locate. For example, if the binder determines
15132that the given main program requires the package @cite{Pack}, whose
15133@code{.ALI}
15134file is @code{pack.ali} and whose corresponding source spec file is
15135@code{pack.ads}, it attempts to locate the source file @code{pack.ads}
15136(using the same search path conventions as previously described for the
15137@emph{gcc} command). If it can locate this source file, it checks that
15138the time stamps
15139or source checksums of the source and its references to in @code{ALI} files
15140match. In other words, any @code{ALI} files that mentions this spec must have
15141resulted from compiling this version of the source file (or in the case
15142where the source checksums match, a version close enough that the
15143difference does not matter).
15144
15145@geindex Source files
15146@geindex use by binder
15147
15148The effect of this consistency checking, which includes source files, is
15149that the binder ensures that the program is consistent with the latest
15150version of the source files that can be located at bind time. Editing a
15151source file without compiling files that depend on the source file cause
15152error messages to be generated by the binder.
15153
15154For example, suppose you have a main program @code{hello.adb} and a
15155package @cite{P}, from file @code{p.ads} and you perform the following
15156steps:
15157
15158
15159@itemize *
15160
15161@item
15162Enter @cite{gcc -c hello.adb} to compile the main program.
15163
15164@item
15165Enter @cite{gcc -c p.ads} to compile package @cite{P}.
15166
15167@item
15168Edit file @code{p.ads}.
15169
15170@item
15171Enter @cite{gnatbind hello}.
15172@end itemize
15173
15174At this point, the file @code{p.ali} contains an out-of-date time stamp
15175because the file @code{p.ads} has been edited. The attempt at binding
15176fails, and the binder generates the following error messages:
15177
15178@example
15179error: "hello.adb" must be recompiled ("p.ads" has been modified)
15180error: "p.ads" has been modified and must be recompiled
15181@end example
15182
15183Now both files must be recompiled as indicated, and then the bind can
15184succeed, generating a main program. You need not normally be concerned
15185with the contents of this file, but for reference purposes a sample
15186binder output file is given in @ref{10,,Example of Binder Output File}.
15187
15188In most normal usage, the default mode of @emph{gnatbind} which is to
15189generate the main package in Ada, as described in the previous section.
15190In particular, this means that any Ada programmer can read and understand
15191the generated main program. It can also be debugged just like any other
15192Ada code provided the @emph{-g} switch is used for
15193@emph{gnatbind} and @emph{gnatlink}.
15194
15195@node Switches for gnatbind,Command-Line Access,Running gnatbind,Binding with gnatbind
15196@anchor{gnat_ugn/building_executable_programs_with_gnat id33}@anchor{125}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatbind}@anchor{126}
15197@subsection Switches for @emph{gnatbind}
15198
15199
15200The following switches are available with @cite{gnatbind}; details will
15201be presented in subsequent sections.
15202
15203@geindex --version (gnatbind)
15204
15205
15206@table @asis
15207
15208@item @code{--version}
15209
15210Display Copyright and version, then exit disregarding all other options.
15211@end table
15212
15213@geindex --help (gnatbind)
15214
15215
15216@table @asis
15217
15218@item @code{--help}
15219
15220If @emph{--version} was not used, display usage, then exit disregarding
15221all other options.
15222@end table
15223
15224@geindex -a (gnatbind)
15225
15226
15227@table @asis
15228
15229@item @code{-a}
15230
15231Indicates that, if supported by the platform, the adainit procedure should
15232be treated as an initialisation routine by the linker (a constructor). This
15233is intended to be used by the Project Manager to automatically initialize
15234shared Stand-Alone Libraries.
15235@end table
15236
15237@geindex -aO (gnatbind)
15238
15239
15240@table @asis
15241
15242@item @code{-aO}
15243
15244Specify directory to be searched for ALI files.
15245@end table
15246
15247@geindex -aI (gnatbind)
15248
15249
15250@table @asis
15251
15252@item @code{-aI}
15253
15254Specify directory to be searched for source file.
15255@end table
15256
15257@geindex -A (gnatbind)
15258
15259
15260@table @asis
15261
15262@item @code{-A[=@emph{filename}]}
15263
15264Output ALI list (to standard output or to the named file).
15265@end table
15266
15267@geindex -b (gnatbind)
15268
15269
15270@table @asis
15271
15272@item @code{-b}
15273
15274Generate brief messages to @code{stderr} even if verbose mode set.
15275@end table
15276
15277@geindex -c (gnatbind)
15278
15279
15280@table @asis
15281
15282@item @code{-c}
15283
15284Check only, no generation of binder output file.
15285@end table
15286
15287@geindex -dnn[k|m] (gnatbind)
15288
15289
15290@table @asis
15291
15292@item @code{-d@emph{nn}[k|m]}
15293
15294This switch can be used to change the default task stack size value
15295to a specified size @cite{nn}, which is expressed in bytes by default, or
15296in kilobytes when suffixed with @cite{k} or in megabytes when suffixed
15297with @cite{m}.
15298In the absence of a @code{[k|m]} suffix, this switch is equivalent,
15299in effect, to completing all task specs with
15300
15301@example
15302pragma Storage_Size (nn);
15303@end example
15304
15305When they do not already have such a pragma.
15306@end table
15307
15308@geindex -D (gnatbind)
15309
15310
15311@table @asis
15312
15313@item @code{-D@emph{nn}[k|m]}
15314
15315This switch can be used to change the default secondary stack size value
15316to a specified size @cite{nn}, which is expressed in bytes by default, or
15317in kilobytes when suffixed with @cite{k} or in megabytes when suffixed
15318with @cite{m}.
15319
15320The secondary stack is used to deal with functions that return a variable
15321sized result, for example a function returning an unconstrained
15322String. There are two ways in which this secondary stack is allocated.
15323
15324For most targets, the secondary stack is growing on demand and is allocated
15325as a chain of blocks in the heap. The -D option is not very
15326relevant. It only give some control over the size of the allocated
15327blocks (whose size is the minimum of the default secondary stack size value,
15328and the actual size needed for the current allocation request).
15329
15330For certain targets, notably VxWorks 653,
15331the secondary stack is allocated by carving off a fixed ratio chunk of the
15332primary task stack. The -D option is used to define the
15333size of the environment task's secondary stack.
15334@end table
15335
15336@geindex -e (gnatbind)
15337
15338
15339@table @asis
15340
15341@item @code{-e}
15342
15343Output complete list of elaboration-order dependencies.
15344@end table
15345
15346@geindex -Ea (gnatbind)
15347
15348
15349@table @asis
15350
15351@item @code{-Ea}
15352
15353Store tracebacks in exception occurrences when the target supports it.
15354The "a" is for "address"; tracebacks will contain hexadecimal addresses,
15355unless symbolic tracebacks are enabled.
15356
15357See also the packages @cite{GNAT.Traceback} and
15358@cite{GNAT.Traceback.Symbolic} for more information.
15359Note that on x86 ports, you must not use @emph{-fomit-frame-pointer}
15360@emph{gcc} option.
15361@end table
15362
15363@geindex -Es (gnatbind)
15364
15365
15366@table @asis
15367
15368@item @code{-Es}
15369
15370Store tracebacks in exception occurrences when the target supports it.
15371The "s" is for "symbolic"; symbolic tracebacks are enabled.
15372@end table
15373
15374@geindex -E (gnatbind)
15375
15376
15377@table @asis
15378
15379@item @code{-E}
15380
15381Currently the same as @cite{-Ea}.
15382@end table
15383
15384@geindex -F (gnatbind)
15385
15386
15387@table @asis
15388
15389@item @code{-F}
15390
15391Force the checks of elaboration flags. @emph{gnatbind} does not normally
15392generate checks of elaboration flags for the main executable, except when
15393a Stand-Alone Library is used. However, there are cases when this cannot be
15394detected by gnatbind. An example is importing an interface of a Stand-Alone
15395Library through a pragma Import and only specifying through a linker switch
15396this Stand-Alone Library. This switch is used to guarantee that elaboration
15397flag checks are generated.
15398@end table
15399
15400@geindex -h (gnatbind)
15401
15402
15403@table @asis
15404
15405@item @code{-h}
15406
15407Output usage (help) information.
15408
15409@geindex -H32 (gnatbind)
15410
15411@item @code{-H32}
15412
15413Use 32-bit allocations for @cite{__gnat_malloc} (and thus for access types).
15414For further details see @ref{127,,Dynamic Allocation Control}.
15415
15416@geindex -H64 (gnatbind)
15417
15418@geindex __gnat_malloc
15419
15420@item @code{-H64}
15421
15422Use 64-bit allocations for @cite{__gnat_malloc} (and thus for access types).
15423For further details see @ref{127,,Dynamic Allocation Control}.
15424
15425@geindex -I (gnatbind)
15426
15427@item @code{-I}
15428
15429Specify directory to be searched for source and ALI files.
15430
15431@geindex -I- (gnatbind)
15432
15433@item @code{-I-}
15434
15435Do not look for sources in the current directory where @cite{gnatbind} was
15436invoked, and do not look for ALI files in the directory containing the
15437ALI file named in the @cite{gnatbind} command line.
15438
15439@geindex -l (gnatbind)
15440
15441@item @code{-l}
15442
15443Output chosen elaboration order.
15444
15445@geindex -L (gnatbind)
15446
15447@item @code{-L@emph{xxx}}
15448
15449Bind the units for library building. In this case the adainit and
15450adafinal procedures (@ref{ba,,Binding with Non-Ada Main Programs})
15451are renamed to @cite{xxx`init and `xxx`final. Implies -n. (:ref:`GNAT_and_Libraries}, for more details.)
15452
15453@geindex -M (gnatbind)
15454
15455@item @code{-M@emph{xyz}}
15456
15457Rename generated main program from main to xyz. This option is
15458supported on cross environments only.
15459
15460@geindex -m (gnatbind)
15461
15462@item @code{-m@emph{n}}
15463
15464Limit number of detected errors or warnings to @cite{n}, where @cite{n} is
15465in the range 1..999999. The default value if no switch is
15466given is 9999. If the number of warnings reaches this limit, then a
15467message is output and further warnings are suppressed, the bind
15468continues in this case. If the number of errors reaches this
15469limit, then a message is output and the bind is abandoned.
15470A value of zero means that no limit is enforced. The equal
15471sign is optional.
15472
15473@geindex -n (gnatbind)
15474
15475@item @code{-n}
15476
15477No main program.
15478
15479@geindex -nostdinc (gnatbind)
15480
15481@item @code{-nostdinc}
15482
15483Do not look for sources in the system default directory.
15484
15485@geindex -nostdlib (gnatbind)
15486
15487@item @code{-nostdlib}
15488
15489Do not look for library files in the system default directory.
15490
15491@geindex --RTS (gnatbind)
15492
15493@item @code{--RTS=@emph{rts-path}}
15494
15495Specifies the default location of the runtime library. Same meaning as the
15496equivalent @emph{gnatmake} flag (@ref{e2,,Switches for gnatmake}).
15497
15498@geindex -o (gnatbind)
15499
15500@item @code{-o @emph{file}}
15501
15502Name the output file @cite{file} (default is @code{b~`xxx}.adb`).
15503Note that if this option is used, then linking must be done manually,
15504gnatlink cannot be used.
15505
15506@geindex -O (gnatbind)
15507
15508@item @code{-O[=@emph{filename}]}
15509
15510Output object list (to standard output or to the named file).
15511
15512@geindex -p (gnatbind)
15513
15514@item @code{-p}
15515
15516Pessimistic (worst-case) elaboration order.
15517
15518@geindex -P (gnatbind)
15519
15520@item @code{-P}
15521
15522Generate binder file suitable for CodePeer.
15523
15524@geindex -R (gnatbind)
15525
15526@item @code{-R}
15527
15528Output closure source list, which includes all non-run-time units that are
15529included in the bind.
15530
15531@geindex -Ra (gnatbind)
15532
15533@item @code{-Ra}
15534
15535Like @emph{-R} but the list includes run-time units.
15536
15537@geindex -s (gnatbind)
15538
15539@item @code{-s}
15540
15541Require all source files to be present.
15542
15543@geindex -S (gnatbind)
15544
15545@item @code{-S@emph{xxx}}
15546
15547Specifies the value to be used when detecting uninitialized scalar
15548objects with pragma Initialize_Scalars.
15549The @cite{xxx} string specified with the switch is one of:
15550
15551
15552@itemize *
15553
15554@item
15555@code{in} for an invalid value.
15556
15557If zero is invalid for the discrete type in question,
15558then the scalar value is set to all zero bits.
15559For signed discrete types, the largest possible negative value of
15560the underlying scalar is set (i.e. a one bit followed by all zero bits).
15561For unsigned discrete types, the underlying scalar value is set to all
15562one bits. For floating-point types, a NaN value is set
15563(see body of package System.Scalar_Values for exact values).
15564
15565@item
15566@code{lo} for low value.
15567
15568If zero is invalid for the discrete type in question,
15569then the scalar value is set to all zero bits.
15570For signed discrete types, the largest possible negative value of
15571the underlying scalar is set (i.e. a one bit followed by all zero bits).
15572For unsigned discrete types, the underlying scalar value is set to all
15573zero bits. For floating-point, a small value is set
15574(see body of package System.Scalar_Values for exact values).
15575
15576@item
15577@code{hi} for high value.
15578
15579If zero is invalid for the discrete type in question,
15580then the scalar value is set to all one bits.
15581For signed discrete types, the largest possible positive value of
15582the underlying scalar is set (i.e. a zero bit followed by all one bits).
15583For unsigned discrete types, the underlying scalar value is set to all
15584one bits. For floating-point, a large value is set
15585(see body of package System.Scalar_Values for exact values).
15586
15587@item
15588@cite{xx} for hex value (two hex digits).
15589
15590The underlying scalar is set to a value consisting of repeated bytes, whose
15591value corresponds to the given value. For example if @code{BF} is given,
15592then a 32-bit scalar value will be set to the bit patterm @code{16#BFBFBFBF#}.
15593@end itemize
15594
15595@geindex GNAT_INIT_SCALARS
15596
15597In addition, you can specify @emph{-Sev} to indicate that the value is
15598to be set at run time. In this case, the program will look for an environment
15599variable of the form @code{GNAT_INIT_SCALARS=@emph{yy}}, where @cite{yy} is one
15600of @emph{in/lo/hi/`xx*` with the same meanings as above.
15601If no environment variable is found, or if it does not have a valid value,
15602then the default is *in} (invalid values).
15603@end table
15604
15605@geindex -static (gnatbind)
15606
15607
15608@table @asis
15609
15610@item @code{-static}
15611
15612Link against a static GNAT run time.
15613
15614@geindex -shared (gnatbind)
15615
15616@item @code{-shared}
15617
15618Link against a shared GNAT run time when available.
15619
15620@geindex -t (gnatbind)
15621
15622@item @code{-t}
15623
15624Tolerate time stamp and other consistency errors.
15625
15626@geindex -T (gnatbind)
15627
15628@item @code{-T@emph{n}}
15629
15630Set the time slice value to @cite{n} milliseconds. If the system supports
15631the specification of a specific time slice value, then the indicated value
15632is used. If the system does not support specific time slice values, but
15633does support some general notion of round-robin scheduling, then any
15634nonzero value will activate round-robin scheduling.
15635
15636A value of zero is treated specially. It turns off time
15637slicing, and in addition, indicates to the tasking run time that the
15638semantics should match as closely as possible the Annex D
15639requirements of the Ada RM, and in particular sets the default
15640scheduling policy to @cite{FIFO_Within_Priorities}.
15641
15642@geindex -u (gnatbind)
15643
15644@item @code{-u@emph{n}}
15645
15646Enable dynamic stack usage, with @cite{n} results stored and displayed
15647at program termination. A result is generated when a task
15648terminates. Results that can't be stored are displayed on the fly, at
15649task termination. This option is currently not supported on Itanium
15650platforms. (See @ref{128,,Dynamic Stack Usage Analysis} for details.)
15651
15652@geindex -v (gnatbind)
15653
15654@item @code{-v}
15655
15656Verbose mode. Write error messages, header, summary output to
15657@code{stdout}.
15658
15659@geindex -V (gnatbind)
15660
15661@item @code{-V@emph{key}=@emph{value}}
15662
15663Store the given association of @cite{key} to @cite{value} in the bind environment.
15664Values stored this way can be retrieved at run time using
15665@cite{GNAT.Bind_Environment}.
15666
15667@geindex -w (gnatbind)
15668
15669@item @code{-w@emph{x}}
15670
15671Warning mode; @cite{x} = s/e for suppress/treat as error.
15672
15673@geindex -Wx (gnatbind)
15674
15675@item @code{-Wx@emph{e}}
15676
15677Override default wide character encoding for standard Text_IO files.
15678
15679@geindex -x (gnatbind)
15680
15681@item @code{-x}
15682
15683Exclude source files (check object consistency only).
15684
15685@geindex -Xnnn (gnatbind)
15686
15687@item @code{-X@emph{nnn}}
15688
15689Set default exit status value, normally 0 for POSIX compliance.
15690
15691@geindex -y (gnatbind)
15692
15693@item @code{-y}
15694
15695Enable leap seconds support in @cite{Ada.Calendar} and its children.
15696
15697@geindex -z (gnatbind)
15698
15699@item @code{-z}
15700
15701No main subprogram.
15702@end table
15703
15704You may obtain this listing of switches by running @cite{gnatbind} with
15705no arguments.
15706
15707@menu
15708* Consistency-Checking Modes::
15709* Binder Error Message Control::
15710* Elaboration Control::
15711* Output Control::
15712* Dynamic Allocation Control::
15713* Binding with Non-Ada Main Programs::
15714* Binding Programs with No Main Subprogram::
15715
15716@end menu
15717
15718@node Consistency-Checking Modes,Binder Error Message Control,,Switches for gnatbind
15719@anchor{gnat_ugn/building_executable_programs_with_gnat consistency-checking-modes}@anchor{129}@anchor{gnat_ugn/building_executable_programs_with_gnat id34}@anchor{12a}
15720@subsubsection Consistency-Checking Modes
15721
15722
15723As described earlier, by default @cite{gnatbind} checks
15724that object files are consistent with one another and are consistent
15725with any source files it can locate. The following switches control binder
15726access to sources.
15727
15728@quotation
15729
15730@geindex -s (gnatbind)
15731@end quotation
15732
15733
15734@table @asis
15735
15736@item @code{-s}
15737
15738Require source files to be present. In this mode, the binder must be
15739able to locate all source files that are referenced, in order to check
15740their consistency. In normal mode, if a source file cannot be located it
15741is simply ignored. If you specify this switch, a missing source
15742file is an error.
15743
15744@geindex -Wx (gnatbind)
15745
15746@item @code{-Wx@emph{e}}
15747
15748Override default wide character encoding for standard Text_IO files.
15749Normally the default wide character encoding method used for standard
15750[Wide_[Wide_]]Text_IO files is taken from the encoding specified for
15751the main source input (see description of switch
15752@emph{-gnatWx} for the compiler). The
15753use of this switch for the binder (which has the same set of
15754possible arguments) overrides this default as specified.
15755
15756@geindex -x (gnatbind)
15757
15758@item @code{-x}
15759
15760Exclude source files. In this mode, the binder only checks that ALI
15761files are consistent with one another. Source files are not accessed.
15762The binder runs faster in this mode, and there is still a guarantee that
15763the resulting program is self-consistent.
15764If a source file has been edited since it was last compiled, and you
15765specify this switch, the binder will not detect that the object
15766file is out of date with respect to the source file. Note that this is the
15767mode that is automatically used by @emph{gnatmake} because in this
15768case the checking against sources has already been performed by
15769@emph{gnatmake} in the course of compilation (i.e., before binding).
15770@end table
15771
15772@node Binder Error Message Control,Elaboration Control,Consistency-Checking Modes,Switches for gnatbind
15773@anchor{gnat_ugn/building_executable_programs_with_gnat id35}@anchor{12b}@anchor{gnat_ugn/building_executable_programs_with_gnat binder-error-message-control}@anchor{12c}
15774@subsubsection Binder Error Message Control
15775
15776
15777The following switches provide control over the generation of error
15778messages from the binder:
15779
15780@quotation
15781
15782@geindex -v (gnatbind)
15783@end quotation
15784
15785
15786@table @asis
15787
15788@item @code{-v}
15789
15790Verbose mode. In the normal mode, brief error messages are generated to
15791@code{stderr}. If this switch is present, a header is written
15792to @code{stdout} and any error messages are directed to @code{stdout}.
15793All that is written to @code{stderr} is a brief summary message.
15794
15795@geindex -b (gnatbind)
15796
15797@item @code{-b}
15798
15799Generate brief error messages to @code{stderr} even if verbose mode is
15800specified. This is relevant only when used with the
15801@emph{-v} switch.
15802
15803@geindex -m (gnatbind)
15804
15805@item @code{-m@emph{n}}
15806
15807Limits the number of error messages to @cite{n}, a decimal integer in the
15808range 1-999. The binder terminates immediately if this limit is reached.
15809
15810@geindex -M (gnatbind)
15811
15812@item @code{-M@emph{xxx}}
15813
15814Renames the generated main program from @cite{main} to @cite{xxx}.
15815This is useful in the case of some cross-building environments, where
15816the actual main program is separate from the one generated
15817by @cite{gnatbind}.
15818
15819@geindex -ws (gnatbind)
15820
15821@geindex Warnings
15822
15823@item @code{-ws}
15824
15825Suppress all warning messages.
15826
15827@geindex -we (gnatbind)
15828
15829@item @code{-we}
15830
15831Treat any warning messages as fatal errors.
15832
15833@geindex -t (gnatbind)
15834
15835@geindex Time stamp checks
15836@geindex in binder
15837
15838@geindex Binder consistency checks
15839
15840@geindex Consistency checks
15841@geindex in binder
15842
15843@item @code{-t}
15844
15845The binder performs a number of consistency checks including:
15846
15847
15848@itemize *
15849
15850@item
15851Check that time stamps of a given source unit are consistent
15852
15853@item
15854Check that checksums of a given source unit are consistent
15855
15856@item
15857Check that consistent versions of @cite{GNAT} were used for compilation
15858
15859@item
15860Check consistency of configuration pragmas as required
15861@end itemize
15862
15863Normally failure of such checks, in accordance with the consistency
15864requirements of the Ada Reference Manual, causes error messages to be
15865generated which abort the binder and prevent the output of a binder
15866file and subsequent link to obtain an executable.
15867
15868The @emph{-t} switch converts these error messages
15869into warnings, so that
15870binding and linking can continue to completion even in the presence of such
15871errors. The result may be a failed link (due to missing symbols), or a
15872non-functional executable which has undefined semantics.
15873
15874@cartouche
15875@quotation Note
15876This means that @emph{-t} should be used only in unusual situations,
15877with extreme care.
15878@end quotation
15879@end cartouche
15880@end table
15881
15882@node Elaboration Control,Output Control,Binder Error Message Control,Switches for gnatbind
15883@anchor{gnat_ugn/building_executable_programs_with_gnat id36}@anchor{12d}@anchor{gnat_ugn/building_executable_programs_with_gnat elaboration-control}@anchor{12e}
15884@subsubsection Elaboration Control
15885
15886
15887The following switches provide additional control over the elaboration
15888order. For full details see @ref{11,,Elaboration Order Handling in GNAT}.
15889
15890@quotation
15891
15892@geindex -p (gnatbind)
15893@end quotation
15894
15895
15896@table @asis
15897
15898@item @code{-p}
15899
15900Normally the binder attempts to choose an elaboration order that is
15901likely to minimize the likelihood of an elaboration order error resulting
15902in raising a @cite{Program_Error} exception. This switch reverses the
15903action of the binder, and requests that it deliberately choose an order
15904that is likely to maximize the likelihood of an elaboration error.
15905This is useful in ensuring portability and avoiding dependence on
15906accidental fortuitous elaboration ordering.
15907
15908Normally it only makes sense to use the @emph{-p}
15909switch if dynamic
15910elaboration checking is used (@emph{-gnatE} switch used for compilation).
15911This is because in the default static elaboration mode, all necessary
15912@cite{Elaborate} and @cite{Elaborate_All} pragmas are implicitly inserted.
15913These implicit pragmas are still respected by the binder in
15914@emph{-p} mode, so a
15915safe elaboration order is assured.
15916
15917Note that @emph{-p} is not intended for
15918production use; it is more for debugging/experimental use.
15919@end table
15920
15921@node Output Control,Dynamic Allocation Control,Elaboration Control,Switches for gnatbind
15922@anchor{gnat_ugn/building_executable_programs_with_gnat output-control}@anchor{12f}@anchor{gnat_ugn/building_executable_programs_with_gnat id37}@anchor{130}
15923@subsubsection Output Control
15924
15925
15926The following switches allow additional control over the output
15927generated by the binder.
15928
15929@quotation
15930
15931@geindex -c (gnatbind)
15932@end quotation
15933
15934
15935@table @asis
15936
15937@item @code{-c}
15938
15939Check only. Do not generate the binder output file. In this mode the
15940binder performs all error checks but does not generate an output file.
15941
15942@geindex -e (gnatbind)
15943
15944@item @code{-e}
15945
15946Output complete list of elaboration-order dependencies, showing the
15947reason for each dependency. This output can be rather extensive but may
15948be useful in diagnosing problems with elaboration order. The output is
15949written to @code{stdout}.
15950
15951@geindex -h (gnatbind)
15952
15953@item @code{-h}
15954
15955Output usage information. The output is written to @code{stdout}.
15956
15957@geindex -K (gnatbind)
15958
15959@item @code{-K}
15960
15961Output linker options to @code{stdout}. Includes library search paths,
15962contents of pragmas Ident and Linker_Options, and libraries added
15963by @cite{gnatbind}.
15964
15965@geindex -l (gnatbind)
15966
15967@item @code{-l}
15968
15969Output chosen elaboration order. The output is written to @code{stdout}.
15970
15971@geindex -O (gnatbind)
15972
15973@item @code{-O}
15974
15975Output full names of all the object files that must be linked to provide
15976the Ada component of the program. The output is written to @code{stdout}.
15977This list includes the files explicitly supplied and referenced by the user
15978as well as implicitly referenced run-time unit files. The latter are
15979omitted if the corresponding units reside in shared libraries. The
15980directory names for the run-time units depend on the system configuration.
15981
15982@geindex -o (gnatbind)
15983
15984@item @code{-o @emph{file}}
15985
15986Set name of output file to @cite{file} instead of the normal
15987@code{b~`mainprog}.adb` default. Note that @cite{file} denote the Ada
15988binder generated body filename.
15989Note that if this option is used, then linking must be done manually.
15990It is not possible to use gnatlink in this case, since it cannot locate
15991the binder file.
15992
15993@geindex -r (gnatbind)
15994
15995@item @code{-r}
15996
15997Generate list of @cite{pragma Restrictions} that could be applied to
15998the current unit. This is useful for code audit purposes, and also may
15999be used to improve code generation in some cases.
16000@end table
16001
16002@node Dynamic Allocation Control,Binding with Non-Ada Main Programs,Output Control,Switches for gnatbind
16003@anchor{gnat_ugn/building_executable_programs_with_gnat dynamic-allocation-control}@anchor{127}@anchor{gnat_ugn/building_executable_programs_with_gnat id38}@anchor{131}
16004@subsubsection Dynamic Allocation Control
16005
16006
16007The heap control switches -- @emph{-H32} and @emph{-H64} --
16008determine whether dynamic allocation uses 32-bit or 64-bit memory.
16009They only affect compiler-generated allocations via @cite{__gnat_malloc};
16010explicit calls to @cite{malloc} and related functions from the C
16011run-time library are unaffected.
16012
16013
16014@table @asis
16015
16016@item @code{-H32}
16017
16018Allocate memory on 32-bit heap
16019
16020@item @code{-H64}
16021
16022Allocate memory on 64-bit heap.  This is the default
16023unless explicitly overridden by a @cite{'Size} clause on the access type.
16024@end table
16025
16026These switches are only effective on VMS platforms.
16027
16028@node Binding with Non-Ada Main Programs,Binding Programs with No Main Subprogram,Dynamic Allocation Control,Switches for gnatbind
16029@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{132}
16030@subsubsection Binding with Non-Ada Main Programs
16031
16032
16033The description so far has assumed that the main
16034program is in Ada, and that the task of the binder is to generate a
16035corresponding function @cite{main} that invokes this Ada main
16036program. GNAT also supports the building of executable programs where
16037the main program is not in Ada, but some of the called routines are
16038written in Ada and compiled using GNAT (@ref{46,,Mixed Language Programming}).
16039The following switch is used in this situation:
16040
16041@quotation
16042
16043@geindex -n (gnatbind)
16044@end quotation
16045
16046
16047@table @asis
16048
16049@item @code{-n}
16050
16051No main program. The main program is not in Ada.
16052@end table
16053
16054In this case, most of the functions of the binder are still required,
16055but instead of generating a main program, the binder generates a file
16056containing the following callable routines:
16057
16058@quotation
16059
16060@geindex adainit
16061
16062
16063@table @asis
16064
16065@item @emph{adainit}
16066
16067You must call this routine to initialize the Ada part of the program by
16068calling the necessary elaboration routines. A call to @cite{adainit} is
16069required before the first call to an Ada subprogram.
16070
16071Note that it is assumed that the basic execution environment must be setup
16072to be appropriate for Ada execution at the point where the first Ada
16073subprogram is called. In particular, if the Ada code will do any
16074floating-point operations, then the FPU must be setup in an appropriate
16075manner. For the case of the x86, for example, full precision mode is
16076required. The procedure GNAT.Float_Control.Reset may be used to ensure
16077that the FPU is in the right state.
16078@end table
16079
16080@geindex adafinal
16081
16082
16083@table @asis
16084
16085@item @emph{adafinal}
16086
16087You must call this routine to perform any library-level finalization
16088required by the Ada subprograms. A call to @cite{adafinal} is required
16089after the last call to an Ada subprogram, and before the program
16090terminates.
16091@end table
16092@end quotation
16093
16094@geindex -n (gnatbind)
16095
16096@geindex Binder
16097@geindex multiple input files
16098
16099If the @emph{-n} switch
16100is given, more than one ALI file may appear on
16101the command line for @cite{gnatbind}. The normal @emph{closure}
16102calculation is performed for each of the specified units. Calculating
16103the closure means finding out the set of units involved by tracing
16104@emph{with} references. The reason it is necessary to be able to
16105specify more than one ALI file is that a given program may invoke two or
16106more quite separate groups of Ada units.
16107
16108The binder takes the name of its output file from the last specified ALI
16109file, unless overridden by the use of the @emph{-o file}.
16110
16111@geindex -o (gnatbind)
16112
16113The output is an Ada unit in source form that can be compiled with GNAT.
16114This compilation occurs automatically as part of the @emph{gnatlink}
16115processing.
16116
16117Currently the GNAT run time requires a FPU using 80 bits mode
16118precision. Under targets where this is not the default it is required to
16119call GNAT.Float_Control.Reset before using floating point numbers (this
16120include float computation, float input and output) in the Ada code. A
16121side effect is that this could be the wrong mode for the foreign code
16122where floating point computation could be broken after this call.
16123
16124@node Binding Programs with No Main Subprogram,,Binding with Non-Ada Main Programs,Switches for gnatbind
16125@anchor{gnat_ugn/building_executable_programs_with_gnat binding-programs-with-no-main-subprogram}@anchor{133}@anchor{gnat_ugn/building_executable_programs_with_gnat id40}@anchor{134}
16126@subsubsection Binding Programs with No Main Subprogram
16127
16128
16129It is possible to have an Ada program which does not have a main
16130subprogram. This program will call the elaboration routines of all the
16131packages, then the finalization routines.
16132
16133The following switch is used to bind programs organized in this manner:
16134
16135@quotation
16136
16137@geindex -z (gnatbind)
16138@end quotation
16139
16140
16141@table @asis
16142
16143@item @code{-z}
16144
16145Normally the binder checks that the unit name given on the command line
16146corresponds to a suitable main subprogram. When this switch is used,
16147a list of ALI files can be given, and the execution of the program
16148consists of elaboration of these units in an appropriate order. Note
16149that the default wide character encoding method for standard Text_IO
16150files is always set to Brackets if this switch is set (you can use
16151the binder switch
16152@emph{-Wx} to override this default).
16153@end table
16154
16155@node Command-Line Access,Search Paths for gnatbind,Switches for gnatbind,Binding with gnatbind
16156@anchor{gnat_ugn/building_executable_programs_with_gnat id41}@anchor{135}@anchor{gnat_ugn/building_executable_programs_with_gnat command-line-access}@anchor{136}
16157@subsection Command-Line Access
16158
16159
16160The package @cite{Ada.Command_Line} provides access to the command-line
16161arguments and program name. In order for this interface to operate
16162correctly, the two variables
16163
16164@example
16165int gnat_argc;
16166char **gnat_argv;
16167@end example
16168
16169@geindex gnat_argv
16170
16171@geindex gnat_argc
16172
16173are declared in one of the GNAT library routines. These variables must
16174be set from the actual @cite{argc} and @cite{argv} values passed to the
16175main program. With no @emph{n} present, @cite{gnatbind}
16176generates the C main program to automatically set these variables.
16177If the @emph{n} switch is used, there is no automatic way to
16178set these variables. If they are not set, the procedures in
16179@cite{Ada.Command_Line} will not be available, and any attempt to use
16180them will raise @cite{Constraint_Error}. If command line access is
16181required, your main program must set @cite{gnat_argc} and
16182@cite{gnat_argv} from the @cite{argc} and @cite{argv} values passed to
16183it.
16184
16185@node Search Paths for gnatbind,Examples of gnatbind Usage,Command-Line Access,Binding with gnatbind
16186@anchor{gnat_ugn/building_executable_programs_with_gnat search-paths-for-gnatbind}@anchor{91}@anchor{gnat_ugn/building_executable_programs_with_gnat id42}@anchor{137}
16187@subsection Search Paths for @cite{gnatbind}
16188
16189
16190The binder takes the name of an ALI file as its argument and needs to
16191locate source files as well as other ALI files to verify object consistency.
16192
16193For source files, it follows exactly the same search rules as @emph{gcc}
16194(see @ref{8e,,Search Paths and the Run-Time Library (RTL)}). For ALI files the
16195directories searched are:
16196
16197
16198@itemize *
16199
16200@item
16201The directory containing the ALI file named in the command line, unless
16202the switch @emph{-I-} is specified.
16203
16204@item
16205All directories specified by @emph{-I}
16206switches on the @cite{gnatbind}
16207command line, in the order given.
16208
16209@geindex ADA_PRJ_OBJECTS_FILE
16210
16211@item
16212Each of the directories listed in the text file whose name is given
16213by the
16214@geindex ADA_PRJ_OBJECTS_FILE
16215@geindex environment variable; ADA_PRJ_OBJECTS_FILE
16216@code{ADA_PRJ_OBJECTS_FILE} environment variable.
16217
16218@geindex ADA_PRJ_OBJECTS_FILE
16219@geindex environment variable; ADA_PRJ_OBJECTS_FILE
16220@code{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the gnat
16221driver when project files are used. It should not normally be set
16222by other means.
16223
16224@geindex ADA_OBJECTS_PATH
16225
16226@item
16227Each of the directories listed in the value of the
16228@geindex ADA_OBJECTS_PATH
16229@geindex environment variable; ADA_OBJECTS_PATH
16230@code{ADA_OBJECTS_PATH} environment variable.
16231Construct this value
16232exactly as the
16233@geindex PATH
16234@geindex environment variable; PATH
16235@code{PATH} environment variable: a list of directory
16236names separated by colons (semicolons when working with the NT version
16237of GNAT).
16238
16239@item
16240The content of the @code{ada_object_path} file which is part of the GNAT
16241installation tree and is used to store standard libraries such as the
16242GNAT Run Time Library (RTL) unless the switch @emph{-nostdlib} is
16243specified. See @ref{8b,,Installing a library}
16244@end itemize
16245
16246@geindex -I (gnatbind)
16247
16248@geindex -aI (gnatbind)
16249
16250@geindex -aO (gnatbind)
16251
16252In the binder the switch @emph{-I}
16253is used to specify both source and
16254library file paths. Use @emph{-aI}
16255instead if you want to specify
16256source paths only, and @emph{-aO}
16257if you want to specify library paths
16258only. This means that for the binder
16259@code{-I@emph{dir}} is equivalent to
16260@code{-aI@emph{dir}}
16261@code{-aO`@emph{dir}}.
16262The binder generates the bind file (a C language source file) in the
16263current working directory.
16264
16265@geindex Ada
16266
16267@geindex System
16268
16269@geindex Interfaces
16270
16271@geindex GNAT
16272
16273The packages @cite{Ada}, @cite{System}, and @cite{Interfaces} and their
16274children make up the GNAT Run-Time Library, together with the package
16275GNAT and its children, which contain a set of useful additional
16276library functions provided by GNAT. The sources for these units are
16277needed by the compiler and are kept together in one directory. The ALI
16278files and object files generated by compiling the RTL are needed by the
16279binder and the linker and are kept together in one directory, typically
16280different from the directory containing the sources. In a normal
16281installation, you need not specify these directory names when compiling
16282or binding. Either the environment variables or the built-in defaults
16283cause these files to be found.
16284
16285Besides simplifying access to the RTL, a major use of search paths is
16286in compiling sources from multiple directories. This can make
16287development environments much more flexible.
16288
16289@node Examples of gnatbind Usage,,Search Paths for gnatbind,Binding with gnatbind
16290@anchor{gnat_ugn/building_executable_programs_with_gnat examples-of-gnatbind-usage}@anchor{138}@anchor{gnat_ugn/building_executable_programs_with_gnat id43}@anchor{139}
16291@subsection Examples of @cite{gnatbind} Usage
16292
16293
16294Here are some examples of @cite{gnatbind} invovations:
16295
16296@quotation
16297
16298@example
16299gnatbind hello
16300@end example
16301
16302The main program @cite{Hello} (source program in @code{hello.adb}) is
16303bound using the standard switch settings. The generated main program is
16304@code{b~hello.adb}. This is the normal, default use of the binder.
16305
16306@example
16307gnatbind hello -o mainprog.adb
16308@end example
16309
16310The main program @cite{Hello} (source program in @code{hello.adb}) is
16311bound using the standard switch settings. The generated main program is
16312@code{mainprog.adb} with the associated spec in
16313@code{mainprog.ads}. Note that you must specify the body here not the
16314spec. Note that if this option is used, then linking must be done manually,
16315since gnatlink will not be able to find the generated file.
16316@end quotation
16317
16318@node Linking with gnatlink,Using the GNU make Utility,Binding with gnatbind,Building Executable Programs with GNAT
16319@anchor{gnat_ugn/building_executable_programs_with_gnat id44}@anchor{13a}@anchor{gnat_ugn/building_executable_programs_with_gnat linking-with-gnatlink}@anchor{20}
16320@section Linking with @emph{gnatlink}
16321
16322
16323@geindex gnatlink
16324
16325This chapter discusses @emph{gnatlink}, a tool that links
16326an Ada program and builds an executable file. This utility
16327invokes the system linker (via the @emph{gcc} command)
16328with a correct list of object files and library references.
16329@emph{gnatlink} automatically determines the list of files and
16330references for the Ada part of a program. It uses the binder file
16331generated by the @emph{gnatbind} to determine this list.
16332
16333Note: to invoke @cite{gnatlink} with a project file, use the @cite{gnat}
16334driver (see @ref{122,,The GNAT Driver and Project Files}).
16335
16336@menu
16337* Running gnatlink::
16338* Switches for gnatlink::
16339
16340@end menu
16341
16342@node Running gnatlink,Switches for gnatlink,,Linking with gnatlink
16343@anchor{gnat_ugn/building_executable_programs_with_gnat id45}@anchor{13b}@anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatlink}@anchor{13c}
16344@subsection Running @emph{gnatlink}
16345
16346
16347The form of the @emph{gnatlink} command is
16348
16349@example
16350$ gnatlink [`switches`] `mainprog`[.ali]
16351           [`non-Ada objects`] [`linker options`]
16352@end example
16353
16354The arguments of @emph{gnatlink} (switches, main @code{ALI} file,
16355non-Ada objects
16356or linker options) may be in any order, provided that no non-Ada object may
16357be mistaken for a main @code{ALI} file.
16358Any file name @code{F} without the @code{.ali}
16359extension will be taken as the main @code{ALI} file if a file exists
16360whose name is the concatenation of @code{F} and @code{.ali}.
16361
16362@code{mainprog.ali} references the ALI file of the main program.
16363The @code{.ali} extension of this file can be omitted. From this
16364reference, @emph{gnatlink} locates the corresponding binder file
16365@code{b~mainprog.adb} and, using the information in this file along
16366with the list of non-Ada objects and linker options, constructs a
16367linker command file to create the executable.
16368
16369The arguments other than the @emph{gnatlink} switches and the main
16370@code{ALI} file are passed to the linker uninterpreted.
16371They typically include the names of
16372object files for units written in other languages than Ada and any library
16373references required to resolve references in any of these foreign language
16374units, or in @cite{Import} pragmas in any Ada units.
16375
16376@cite{linker options} is an optional list of linker specific
16377switches.
16378The default linker called by gnatlink is @emph{gcc} which in
16379turn calls the appropriate system linker.
16380
16381One useful option for the linker is @emph{-s}: it reduces the size of the
16382executable by removing all symbol table and relocation information from the
16383executable.
16384
16385Standard options for the linker such as @emph{-lmy_lib} or
16386@emph{-Ldir} can be added as is.
16387For options that are not recognized by
16388@emph{gcc} as linker options, use the @emph{gcc} switches
16389@emph{-Xlinker} or @emph{-Wl,}.
16390
16391Refer to the GCC documentation for
16392details.
16393
16394Here is an example showing how to generate a linker map:
16395
16396@example
16397$ gnatlink my_prog -Wl,-Map,MAPFILE
16398@end example
16399
16400Using @cite{linker options} it is possible to set the program stack and
16401heap size.
16402See @ref{13d,,Setting Stack Size from gnatlink} and
16403@ref{13e,,Setting Heap Size from gnatlink}.
16404
16405@emph{gnatlink} determines the list of objects required by the Ada
16406program and prepends them to the list of objects passed to the linker.
16407@emph{gnatlink} also gathers any arguments set by the use of
16408@cite{pragma Linker_Options} and adds them to the list of arguments
16409presented to the linker.
16410
16411@node Switches for gnatlink,,Running gnatlink,Linking with gnatlink
16412@anchor{gnat_ugn/building_executable_programs_with_gnat id46}@anchor{13f}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatlink}@anchor{140}
16413@subsection Switches for @emph{gnatlink}
16414
16415
16416The following switches are available with the @emph{gnatlink} utility:
16417
16418@geindex --version (gnatlink)
16419
16420
16421@table @asis
16422
16423@item @code{--version}
16424
16425Display Copyright and version, then exit disregarding all other options.
16426@end table
16427
16428@geindex --help (gnatlink)
16429
16430
16431@table @asis
16432
16433@item @code{--help}
16434
16435If @emph{--version} was not used, display usage, then exit disregarding
16436all other options.
16437@end table
16438
16439@geindex Command line length
16440
16441@geindex -f (gnatlink)
16442
16443
16444@table @asis
16445
16446@item @code{-f}
16447
16448On some targets, the command line length is limited, and @emph{gnatlink}
16449will generate a separate file for the linker if the list of object files
16450is too long.
16451The @emph{-f} switch forces this file
16452to be generated even if
16453the limit is not exceeded. This is useful in some cases to deal with
16454special situations where the command line length is exceeded.
16455@end table
16456
16457@geindex Debugging information
16458@geindex including
16459
16460@geindex -g (gnatlink)
16461
16462
16463@table @asis
16464
16465@item @code{-g}
16466
16467The option to include debugging information causes the Ada bind file (in
16468other words, @code{b~mainprog.adb}) to be compiled with @emph{-g}.
16469In addition, the binder does not delete the @code{b~mainprog.adb},
16470@code{b~mainprog.o} and @code{b~mainprog.ali} files.
16471Without @emph{-g}, the binder removes these files by default.
16472@end table
16473
16474@geindex -n (gnatlink)
16475
16476
16477@table @asis
16478
16479@item @code{-n}
16480
16481Do not compile the file generated by the binder. This may be used when
16482a link is rerun with different options, but there is no need to recompile
16483the binder file.
16484@end table
16485
16486@geindex -v (gnatlink)
16487
16488
16489@table @asis
16490
16491@item @code{-v}
16492
16493Verbose mode. Causes additional information to be output, including a full
16494list of the included object files.
16495This switch option is most useful when you want
16496to see what set of object files are being used in the link step.
16497@end table
16498
16499@geindex -v -v (gnatlink)
16500
16501
16502@table @asis
16503
16504@item @code{-v -v}
16505
16506Very verbose mode. Requests that the compiler operate in verbose mode when
16507it compiles the binder file, and that the system linker run in verbose mode.
16508@end table
16509
16510@geindex -o (gnatlink)
16511
16512
16513@table @asis
16514
16515@item @code{-o @emph{exec-name}}
16516
16517@cite{exec-name} specifies an alternate name for the generated
16518executable program. If this switch is omitted, the executable has the same
16519name as the main unit. For example, @cite{gnatlink try.ali} creates
16520an executable called @code{try}.
16521@end table
16522
16523@geindex -b (gnatlink)
16524
16525
16526@table @asis
16527
16528@item @code{-b @emph{target}}
16529
16530Compile your program to run on @cite{target}, which is the name of a
16531system configuration. You must have a GNAT cross-compiler built if
16532@cite{target} is not the same as your host system.
16533@end table
16534
16535@geindex -B (gnatlink)
16536
16537
16538@table @asis
16539
16540@item @code{-B@emph{dir}}
16541
16542Load compiler executables (for example, @cite{gnat1}, the Ada compiler)
16543from @cite{dir} instead of the default location. Only use this switch
16544when multiple versions of the GNAT compiler are available.
16545See the @cite{Directory Options} section in @cite{The_GNU_Compiler_Collection}
16546for further details. You would normally use the @emph{-b} or
16547@emph{-V} switch instead.
16548@end table
16549
16550@geindex -M (gnatlink)
16551
16552
16553@table @asis
16554
16555@item @code{-M}
16556
16557When linking an executable, create a map file. The name of the map file
16558has the same name as the executable with extension ".map".
16559@end table
16560
16561@geindex -M= (gnatlink)
16562
16563
16564@table @asis
16565
16566@item @code{-M=@emph{mapfile}}
16567
16568When linking an executable, create a map file. The name of the map file is
16569@cite{mapfile}.
16570@end table
16571
16572@geindex --GCC=compiler_name (gnatlink)
16573
16574
16575@table @asis
16576
16577@item @code{--GCC=@emph{compiler_name}}
16578
16579Program used for compiling the binder file. The default is
16580@code{gcc}. You need to use quotes around @cite{compiler_name} if
16581@cite{compiler_name} contains spaces or other separator characters.
16582As an example @code{--GCC="foo -x -y"} will instruct @emph{gnatlink} to
16583use @code{foo -x -y} as your compiler. Note that switch @code{-c} is always
16584inserted after your command name. Thus in the above example the compiler
16585command that will be used by @emph{gnatlink} will be @code{foo -c -x -y}.
16586A limitation of this syntax is that the name and path name of the executable
16587itself must not include any embedded spaces. If the compiler executable is
16588different from the default one (gcc or <prefix>-gcc), then the back-end
16589switches in the ALI file are not used to compile the binder generated source.
16590For example, this is the case with @code{--GCC="foo -x -y"}. But the back end
16591switches will be used for @code{--GCC="gcc -gnatv"}. If several
16592@code{--GCC=compiler_name} are used, only the last @cite{compiler_name}
16593is taken into account. However, all the additional switches are also taken
16594into account. Thus,
16595@code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
16596@code{--GCC="bar -x -y -z -t"}.
16597@end table
16598
16599@geindex --LINK= (gnatlink)
16600
16601
16602@table @asis
16603
16604@item @code{--LINK=@emph{name}}
16605
16606@cite{name} is the name of the linker to be invoked. This is especially
16607useful in mixed language programs since languages such as C++ require
16608their own linker to be used. When this switch is omitted, the default
16609name for the linker is @emph{gcc}. When this switch is used, the
16610specified linker is called instead of @emph{gcc} with exactly the same
16611parameters that would have been passed to @emph{gcc} so if the desired
16612linker requires different parameters it is necessary to use a wrapper
16613script that massages the parameters before invoking the real linker. It
16614may be useful to control the exact invocation by using the verbose
16615switch.
16616@end table
16617
16618@node Using the GNU make Utility,,Linking with gnatlink,Building Executable Programs with GNAT
16619@anchor{gnat_ugn/building_executable_programs_with_gnat id47}@anchor{141}@anchor{gnat_ugn/building_executable_programs_with_gnat using-the-gnu-make-utility}@anchor{21}
16620@section Using the GNU @cite{make} Utility
16621
16622
16623@geindex make (GNU)
16624@geindex GNU make
16625
16626This chapter offers some examples of makefiles that solve specific
16627problems. It does not explain how to write a makefile, nor does it try to replace the
16628@emph{gnatmake} utility (@ref{1d,,Building with gnatmake}).
16629
16630All the examples in this section are specific to the GNU version of
16631make. Although @emph{make} is a standard utility, and the basic language
16632is the same, these examples use some advanced features found only in
16633@cite{GNU make}.
16634
16635@menu
16636* Using gnatmake in a Makefile::
16637* Automatically Creating a List of Directories::
16638* Generating the Command Line Switches::
16639* Overcoming Command Line Length Limits::
16640
16641@end menu
16642
16643@node Using gnatmake in a Makefile,Automatically Creating a List of Directories,,Using the GNU make Utility
16644@anchor{gnat_ugn/building_executable_programs_with_gnat using-gnatmake-in-a-makefile}@anchor{142}@anchor{gnat_ugn/building_executable_programs_with_gnat id48}@anchor{143}
16645@subsection Using gnatmake in a Makefile
16646
16647
16648@c index makefile (GNU make)
16649
16650Complex project organizations can be handled in a very powerful way by
16651using GNU make combined with gnatmake. For instance, here is a Makefile
16652which allows you to build each subsystem of a big project into a separate
16653shared library. Such a makefile allows you to significantly reduce the link
16654time of very big applications while maintaining full coherence at
16655each step of the build process.
16656
16657The list of dependencies are handled automatically by
16658@emph{gnatmake}. The Makefile is simply used to call gnatmake in each of
16659the appropriate directories.
16660
16661Note that you should also read the example on how to automatically
16662create the list of directories
16663(@ref{144,,Automatically Creating a List of Directories})
16664which might help you in case your project has a lot of subdirectories.
16665
16666@example
16667## This Makefile is intended to be used with the following directory
16668## configuration:
16669##  - The sources are split into a series of csc (computer software components)
16670##    Each of these csc is put in its own directory.
16671##    Their name are referenced by the directory names.
16672##    They will be compiled into shared library (although this would also work
16673##    with static libraries
16674##  - The main program (and possibly other packages that do not belong to any
16675##    csc is put in the top level directory (where the Makefile is).
16676##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
16677##                    \\_ second_csc (sources) __ lib (will contain the library)
16678##                    \\_ ...
16679## Although this Makefile is build for shared library, it is easy to modify
16680## to build partial link objects instead (modify the lines with -shared and
16681## gnatlink below)
16682##
16683## With this makefile, you can change any file in the system or add any new
16684## file, and everything will be recompiled correctly (only the relevant shared
16685## objects will be recompiled, and the main program will be re-linked).
16686
16687# The list of computer software component for your project. This might be
16688# generated automatically.
16689CSC_LIST=aa bb cc
16690
16691# Name of the main program (no extension)
16692MAIN=main
16693
16694# If we need to build objects with -fPIC, uncomment the following line
16695#NEED_FPIC=-fPIC
16696
16697# The following variable should give the directory containing libgnat.so
16698# You can get this directory through 'gnatls -v'. This is usually the last
16699# directory in the Object_Path.
16700GLIB=...
16701
16702# The directories for the libraries
16703# (This macro expands the list of CSC to the list of shared libraries, you
16704# could simply use the expanded form:
16705# LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
16706LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
16707
16708$@{MAIN@}: objects $@{LIB_DIR@}
16709    gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
16710    gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
16711
16712objects::
16713    # recompile the sources
16714    gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
16715
16716# Note: In a future version of GNAT, the following commands will be simplified
16717# by a new tool, gnatmlib
16718$@{LIB_DIR@}:
16719    mkdir -p $@{dir $@@ @}
16720    cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
16721    cd $@{dir $@@ @} && cp -f ../*.ali .
16722
16723# The dependencies for the modules
16724# Note that we have to force the expansion of *.o, since in some cases
16725# make won't be able to do it itself.
16726aa/lib/libaa.so: $@{wildcard aa/*.o@}
16727bb/lib/libbb.so: $@{wildcard bb/*.o@}
16728cc/lib/libcc.so: $@{wildcard cc/*.o@}
16729
16730# Make sure all of the shared libraries are in the path before starting the
16731# program
16732run::
16733    LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
16734
16735clean::
16736    $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
16737    $@{RM@} $@{CSC_LIST:%=%/*.ali@}
16738    $@{RM@} $@{CSC_LIST:%=%/*.o@}
16739    $@{RM@} *.o *.ali $@{MAIN@}
16740@end example
16741
16742@node Automatically Creating a List of Directories,Generating the Command Line Switches,Using gnatmake in a Makefile,Using the GNU make Utility
16743@anchor{gnat_ugn/building_executable_programs_with_gnat automatically-creating-a-list-of-directories}@anchor{144}@anchor{gnat_ugn/building_executable_programs_with_gnat id49}@anchor{145}
16744@subsection Automatically Creating a List of Directories
16745
16746
16747In most makefiles, you will have to specify a list of directories, and
16748store it in a variable. For small projects, it is often easier to
16749specify each of them by hand, since you then have full control over what
16750is the proper order for these directories, which ones should be
16751included.
16752
16753However, in larger projects, which might involve hundreds of
16754subdirectories, it might be more convenient to generate this list
16755automatically.
16756
16757The example below presents two methods. The first one, although less
16758general, gives you more control over the list. It involves wildcard
16759characters, that are automatically expanded by @emph{make}. Its
16760shortcoming is that you need to explicitly specify some of the
16761organization of your project, such as for instance the directory tree
16762depth, whether some directories are found in a separate tree, etc.
16763
16764The second method is the most general one. It requires an external
16765program, called @emph{find}, which is standard on all Unix systems. All
16766the directories found under a given root directory will be added to the
16767list.
16768
16769@example
16770# The examples below are based on the following directory hierarchy:
16771# All the directories can contain any number of files
16772# ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
16773#                       ->  ab
16774#                       ->  ac
16775#                ->  b  ->  ba  ->  baa
16776#                       ->  bb
16777#                       ->  bc
16778# This Makefile creates a variable called DIRS, that can be reused any time
16779# you need this list (see the other examples in this section)
16780
16781# The root of your project's directory hierarchy
16782ROOT_DIRECTORY=.
16783
16784####
16785# First method: specify explicitly the list of directories
16786# This allows you to specify any subset of all the directories you need.
16787####
16788
16789DIRS := a/aa/ a/ab/ b/ba/
16790
16791####
16792# Second method: use wildcards
16793# Note that the argument(s) to wildcard below should end with a '/'.
16794# Since wildcards also return file names, we have to filter them out
16795# to avoid duplicate directory names.
16796# We thus use make's `dir` and `sort` functions.
16797# It sets DIRs to the following value (note that the directories aaa and baa
16798# are not given, unless you change the arguments to wildcard).
16799# DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
16800####
16801
16802DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
16803                    $@{ROOT_DIRECTORY@}/*/*/@}@}@}
16804
16805####
16806# Third method: use an external program
16807# This command is much faster if run on local disks, avoiding NFS slowdowns.
16808# This is the most complete command: it sets DIRs to the following value:
16809# DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
16810####
16811
16812DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
16813@end example
16814
16815@node Generating the Command Line Switches,Overcoming Command Line Length Limits,Automatically Creating a List of Directories,Using the GNU make Utility
16816@anchor{gnat_ugn/building_executable_programs_with_gnat id50}@anchor{146}@anchor{gnat_ugn/building_executable_programs_with_gnat generating-the-command-line-switches}@anchor{147}
16817@subsection Generating the Command Line Switches
16818
16819
16820Once you have created the list of directories as explained in the
16821previous section (@ref{144,,Automatically Creating a List of Directories}),
16822you can easily generate the command line arguments to pass to gnatmake.
16823
16824For the sake of completeness, this example assumes that the source path
16825is not the same as the object path, and that you have two separate lists
16826of directories.
16827
16828@example
16829# see "Automatically creating a list of directories" to create
16830# these variables
16831SOURCE_DIRS=
16832OBJECT_DIRS=
16833
16834GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
16835GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
16836
16837all:
16838        gnatmake $@{GNATMAKE_SWITCHES@} main_unit
16839@end example
16840
16841@node Overcoming Command Line Length Limits,,Generating the Command Line Switches,Using the GNU make Utility
16842@anchor{gnat_ugn/building_executable_programs_with_gnat overcoming-command-line-length-limits}@anchor{148}@anchor{gnat_ugn/building_executable_programs_with_gnat id51}@anchor{149}
16843@subsection Overcoming Command Line Length Limits
16844
16845
16846One problem that might be encountered on big projects is that many
16847operating systems limit the length of the command line. It is thus hard to give
16848gnatmake the list of source and object directories.
16849
16850This example shows how you can set up environment variables, which will
16851make @emph{gnatmake} behave exactly as if the directories had been
16852specified on the command line, but have a much higher length limit (or
16853even none on most systems).
16854
16855It assumes that you have created a list of directories in your Makefile,
16856using one of the methods presented in
16857@ref{144,,Automatically Creating a List of Directories}.
16858For the sake of completeness, we assume that the object
16859path (where the ALI files are found) is different from the sources patch.
16860
16861Note a small trick in the Makefile below: for efficiency reasons, we
16862create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
16863expanded immediately by @cite{make}. This way we overcome the standard
16864make behavior which is to expand the variables only when they are
16865actually used.
16866
16867On Windows, if you are using the standard Windows command shell, you must
16868replace colons with semicolons in the assignments to these variables.
16869
16870@example
16871# In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
16872# This is the same thing as putting the -I arguments on the command line.
16873# (the equivalent of using -aI on the command line would be to define
16874#  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
16875# You can of course have different values for these variables.
16876#
16877# Note also that we need to keep the previous values of these variables, since
16878# they might have been set before running 'make' to specify where the GNAT
16879# library is installed.
16880
16881# see "Automatically creating a list of directories" to create these
16882# variables
16883SOURCE_DIRS=
16884OBJECT_DIRS=
16885
16886empty:=
16887space:=$@{empty@} $@{empty@}
16888SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
16889OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
16890ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
16891ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
16892export ADA_INCLUDE_PATH
16893export ADA_OBJECTS_PATH
16894
16895all:
16896        gnatmake main_unit
16897@end example
16898
16899@c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
16900
16901@node GNAT Project Manager,Tools Supporting Project Files,Building Executable Programs with GNAT,Top
16902@anchor{gnat_ugn/gnat_project_manager doc}@anchor{14a}@anchor{gnat_ugn/gnat_project_manager gnat-project-manager}@anchor{b}@anchor{gnat_ugn/gnat_project_manager id1}@anchor{14b}
16903@chapter GNAT Project Manager
16904
16905
16906@menu
16907* Introduction::
16908* Building With Projects::
16909* Organizing Projects into Subsystems::
16910* Scenarios in Projects::
16911* Library Projects::
16912* Project Extension::
16913* Aggregate Projects::
16914* Aggregate Library Projects::
16915* Project File Reference::
16916
16917@end menu
16918
16919@node Introduction,Building With Projects,,GNAT Project Manager
16920@anchor{gnat_ugn/gnat_project_manager introduction}@anchor{14c}@anchor{gnat_ugn/gnat_project_manager gnat-project-manager-introduction}@anchor{14d}
16921@section Introduction
16922
16923
16924This chapter describes GNAT's @emph{Project Manager}, a facility that allows
16925you to manage complex builds involving a number of source files, directories,
16926and options for different system configurations. In particular,
16927project files allow you to specify:
16928
16929
16930@itemize *
16931
16932@item
16933The directory or set of directories containing the source files, and/or the
16934names of the specific source files themselves
16935
16936@item
16937The directory in which the compiler's output
16938(@code{ALI} files, object files, tree files, etc.) is to be placed
16939
16940@item
16941The directory in which the executable programs are to be placed
16942
16943@item
16944Switch settings for any of the project-enabled tools;
16945you can apply these settings either globally or to individual compilation units.
16946
16947@item
16948The source files containing the main subprogram(s) to be built
16949
16950@item
16951The source programming language(s)
16952
16953@item
16954Source file naming conventions; you can specify these either globally or for
16955individual compilation units (see @ref{14e,,Naming Schemes}).
16956
16957@item
16958Change any of the above settings depending on external values, thus enabling
16959the reuse of the projects in various @strong{scenarios} (see @ref{14f,,Scenarios in Projects}).
16960
16961@item
16962Automatically build libraries as part of the build process
16963(see @ref{8a,,Library Projects}).
16964@end itemize
16965
16966Project files are written in a syntax close to that of Ada, using familiar
16967notions such as packages, context clauses, declarations, default values,
16968assignments, and inheritance (see @ref{150,,Project File Reference}).
16969
16970Project files can be built hierarchically from other project files, simplifying
16971complex system integration and project reuse (see @ref{151,,Organizing Projects into Subsystems}).
16972
16973
16974@itemize *
16975
16976@item
16977One project can import other projects containing needed source files.
16978More generally, the Project Manager lets you structure large development
16979efforts into hierarchical subsystems, where build decisions are delegated
16980to the subsystem level, and thus different compilation environments
16981(switch settings) used for different subsystems.
16982
16983@item
16984You can organize GNAT projects in a hierarchy: a child project
16985can extend a parent project, inheriting the parent's source files and
16986optionally overriding any of them with alternative versions
16987(see @ref{152,,Project Extension}).
16988@end itemize
16989
16990Several tools support project files, generally in addition to specifying
16991the information on the command line itself). They share common switches
16992to control the loading of the project (in particular
16993@code{-P@emph{projectfile}} and
16994@code{-X@emph{vbl}=@emph{value}}).
16995
16996The Project Manager supports a wide range of development strategies,
16997for systems of all sizes.  Here are some typical practices that are
16998easily handled:
16999
17000
17001@itemize *
17002
17003@item
17004Using a common set of source files and generating object files in different
17005directories via different switch settings. It can be used for instance, for
17006generating separate sets of object files for debugging and for production.
17007
17008@item
17009Using a mostly-shared set of source files with different versions of
17010some units or subunits. It can be used for instance, for grouping and hiding
17011all OS dependencies in a small number of implementation units.
17012@end itemize
17013
17014Project files can be used to achieve some of the effects of a source
17015versioning system (for example, defining separate projects for
17016the different sets of sources that comprise different releases) but the
17017Project Manager is independent of any source configuration management tool
17018that might be used by the developers.
17019
17020The various sections below introduce the different concepts related to
17021projects. Each section starts with examples and use cases, and then goes into
17022the details of related project file capabilities.
17023
17024@node Building With Projects,Organizing Projects into Subsystems,Introduction,GNAT Project Manager
17025@anchor{gnat_ugn/gnat_project_manager building-with-projects}@anchor{153}@anchor{gnat_ugn/gnat_project_manager id2}@anchor{154}
17026@section Building With Projects
17027
17028
17029In its simplest form, a unique project is used to build a single executable.
17030This section concentrates on such a simple setup. Later sections will extend
17031this basic model to more complex setups.
17032
17033The following concepts are the foundation of project files, and will be further
17034detailed later in this documentation. They are summarized here as a reference.
17035
17036
17037@table @asis
17038
17039@item @strong{Project file}:
17040
17041A text file using an Ada-like syntax, generally using the @code{.gpr}
17042extension. It defines build-related characteristics of an application.
17043The characteristics include the list of sources, the location of those
17044sources, the location for the generated object files, the name of
17045the main program, and the options for the various tools involved in the
17046build process.
17047
17048@item @strong{Project attribute}:
17049
17050A specific project characteristic is defined by an attribute clause. Its
17051value is a string or a sequence of strings. All settings in a project
17052are defined through a list of predefined attributes with precise
17053semantics. See @ref{155,,Attributes}.
17054
17055@item @strong{Package in a project}:
17056
17057Global attributes are defined at the top level of a project.
17058Attributes affecting specific tools are grouped in a
17059package whose name is related to tool's function. The most common
17060packages are @cite{Builder}, @cite{Compiler}, @cite{Binder},
17061and @cite{Linker}. See @ref{156,,Packages}.
17062
17063@item @strong{Project variables}:
17064
17065In addition to attributes, a project can use variables to store intermediate
17066values and avoid duplication in complex expressions. It can be initialized
17067with a value coming from the environment.
17068A frequent use of variables is to define scenarios.
17069See @ref{157,,External Values}, @ref{14f,,Scenarios in Projects}, and @ref{158,,Variables}.
17070
17071@item @strong{Source files} and @strong{source directories}:
17072
17073A source file is associated with a language through a naming convention. For
17074instance, @cite{foo.c} is typically the name of a C source file;
17075@cite{bar.ads} or @cite{bar.1.ada} are two common naming conventions for a
17076file containing an Ada spec. A compilation unit is often composed of a main
17077source file and potentially several auxiliary ones, such as header files in C.
17078The naming conventions can be user defined @ref{14e,,Naming Schemes}, and will
17079drive the builder to call the appropriate compiler for the given source file.
17080Source files are searched for in the source directories associated with the
17081project through the @strong{Source_Dirs} attribute. By default, all the files (in
17082these source directories) following the naming conventions associated with the
17083declared languages are considered to be part of the project. It is also
17084possible to limit the list of source files using the @strong{Source_Files} or
17085@strong{Source_List_File} attributes. Note that those last two attributes only
17086accept basenames with no directory information.
17087
17088@item @strong{Object files} and @strong{object directory}:
17089
17090An object file is an intermediate file produced by the compiler from a
17091compilation unit. It is used by post-compilation tools to produce
17092final executables or libraries. Object files produced in the context of
17093a given project are stored in a single directory that can be specified by the
17094@strong{Object_Dir} attribute. In order to store objects in
17095two or more object directories, the system must be split into
17096distinct subsystems with their own project file.
17097@end table
17098
17099The following subsections introduce gradually all the attributes of interest
17100for simple build needs. Here is the simple setup that will be used in the
17101following examples.
17102
17103The Ada source files @code{pack.ads}, @code{pack.adb}, and @code{proc.adb} are in
17104the @code{common/} directory. The file @code{proc.adb} contains an Ada main
17105subprogram @cite{Proc} that @emph{with}s package @cite{Pack}. We want to compile
17106these source files with the switch
17107@emph{-O2}, and put the resulting files in
17108the directory @code{obj/}.
17109
17110@example
17111common/
17112  pack.ads
17113  pack.adb
17114  proc.adb
17115common/obj/
17116  proc.ali, proc.o pack.ali, pack.o
17117@end example
17118
17119Our project is to be called @emph{Build}. The name of the
17120file is the name of the project (case-insensitive) with the
17121@code{.gpr} extension, therefore the project file name is @code{build.gpr}. This
17122is not mandatory, but a warning is issued when this convention is not followed.
17123
17124This is a very simple example, and as stated above, a single project
17125file is enough for it. We will thus create a new file, that for now
17126should contain the following code:
17127
17128@example
17129project Build is
17130end Build;
17131@end example
17132
17133@menu
17134* Source Files and Directories::
17135* Duplicate Sources in Projects::
17136* Object and Exec Directory::
17137* Main Subprograms::
17138* Tools Options in Project Files::
17139* Compiling with Project Files::
17140* Executable File Names::
17141* Avoid Duplication With Variables::
17142* Naming Schemes::
17143* Installation::
17144* Distributed support::
17145
17146@end menu
17147
17148@node Source Files and Directories,Duplicate Sources in Projects,,Building With Projects
17149@anchor{gnat_ugn/gnat_project_manager id3}@anchor{159}@anchor{gnat_ugn/gnat_project_manager source-files-and-directories}@anchor{15a}
17150@subsection Source Files and Directories
17151
17152
17153When you create a new project, the first thing to describe is how to find the
17154corresponding source files. These are the only settings that are needed by all
17155the tools that will use this project (builder, compiler, binder and linker for
17156the compilation, IDEs to edit the source files,...).
17157
17158@geindex Source directories (GNAT Project Manager)
17159
17160The first step is to declare the source directories, which are the directories
17161to be searched to find source files. In the case of the example,
17162the @code{common} directory is the only source directory.
17163
17164@geindex Source_Dirs (GNAT Project Manager)
17165
17166There are several ways of defining source directories:
17167
17168
17169@itemize *
17170
17171@item
17172When the attribute @strong{Source_Dirs} is not used, a project contains a
17173single source directory which is the one where the project file itself
17174resides. In our example, if @code{build.gpr} is placed in the @code{common}
17175directory, the project has the needed implicit source directory.
17176
17177@item
17178The attribute @strong{Source_Dirs} can be set to a list of path names, one
17179for each of the source directories. Such paths can either be absolute
17180names (for instance @code{"/usr/local/common/"} on UNIX), or relative to the
17181directory in which the project file resides (for instance "." if
17182@code{build.gpr} is inside @code{common/}, or "common" if it is one level up).
17183Each of the source directories must exist and be readable.
17184
17185@geindex portability of path names (GNAT Project Manager)
17186
17187The syntax for directories is platform specific. For portability, however,
17188the project manager will always properly translate UNIX-like path names to
17189the native format of the specific platform. For instance, when the same
17190project file is to be used both on Unix and Windows, "/" should be used as
17191the directory separator rather than "\".
17192
17193@item
17194The attribute @strong{Source_Dirs} can automatically include subdirectories
17195using a special syntax inspired by some UNIX shells. If any of the paths in
17196the list ends with "@code{**}", then that path and all its subdirectories
17197(recursively) are included in the list of source directories. For instance,
17198@code{**} and @code{./**} represent the complete directory tree rooted at
17199the directory in which the project file resides.
17200
17201@geindex Source directories (GNAT Project Manager)
17202
17203@geindex Excluded_Source_Dirs (GNAT Project Manager)
17204
17205When using that construct, it can sometimes be convenient to also use the
17206attribute @strong{Excluded_Source_Dirs}, which is also a list of paths. Each entry
17207specifies a directory whose immediate content, not including subdirs, is to
17208be excluded. It is also possible to exclude a complete directory subtree
17209using the "**" notation.
17210
17211@geindex Ignore_Source_Sub_Dirs (GNAT Project Manager)
17212
17213It is often desirable to remove, from the source directories, directory
17214subtrees rooted at some subdirectories. An example is the subdirectories
17215created by a Version Control System such as Subversion that creates directory
17216subtrees rooted at subdirectories ".svn". To do that, attribute
17217@strong{Ignore_Source_Sub_Dirs} can be used. It specifies the list of simple
17218file names for the roots of these undesirable directory subtrees.
17219
17220@example
17221for Source_Dirs use ("./**");
17222for Ignore_Source_Sub_Dirs use (".svn");
17223@end example
17224@end itemize
17225
17226When applied to the simple example, and because we generally prefer to have
17227the project file at the toplevel directory rather than mixed with the sources,
17228we will create the following file
17229
17230@example
17231build.gpr
17232project Build is
17233   for Source_Dirs use ("common");  --  <<<<
17234end Build;
17235@end example
17236
17237Once source directories have been specified, one may need to indicate
17238source files of interest. By default, all source files present in the source
17239directories are considered by the project manager. When this is not desired,
17240it is possible to specify the list of sources to consider explicitly.
17241In such a case, only source file base names are indicated and not
17242their absolute or relative path names. The project manager is in charge of
17243locating the specified source files in the specified source directories.
17244
17245
17246@itemize *
17247
17248@item
17249By default, the project manager searches for all source files of all
17250specified languages in all the source directories.
17251
17252Since the project manager was initially developed for Ada environments, the
17253default language is usually Ada and the above project file is complete: it
17254defines without ambiguity the sources composing the project: that is to say,
17255all the sources in subdirectory "common" for the default language (Ada) using
17256the default naming convention.
17257
17258@geindex Languages (GNAT Project Manager)
17259
17260However, when compiling a multi-language application, or a pure C
17261application, the project manager must be told which languages are of
17262interest, which is done by setting the @strong{Languages} attribute to a list of
17263strings, each of which is the name of a language.
17264
17265@geindex Naming scheme (GNAT Project Manager)
17266
17267Even when using only Ada, the default naming might not be suitable. Indeed,
17268how does the project manager recognizes an "Ada file" from any other
17269file? Project files can describe the naming scheme used for source files,
17270and override the default (see @ref{14e,,Naming Schemes}). The default is the
17271standard GNAT extension (@code{.adb} for bodies and @code{.ads} for
17272specs), which is what is used in our example, explaining why no naming scheme
17273is explicitly specified.
17274See @ref{14e,,Naming Schemes}.
17275
17276@geindex Source_Files (GNAT Project Manager)
17277
17278@item
17279@cite{Source_Files}.
17280In some cases, source directories might contain files that should not be
17281included in a project. One can specify the explicit list of file names to
17282be considered through the @strong{Source_Files} attribute.
17283When this attribute is defined, instead of looking at every file in the
17284source directories, the project manager takes only those names into
17285consideration  reports  errors if they cannot be found in the source
17286directories or does not correspond to the naming scheme.
17287
17288@item
17289For various reasons, it is sometimes useful to have a project with no
17290sources (most of the time because the attributes defined in the project
17291file will be reused in other projects, as explained in
17292@ref{151,,Organizing Projects into Subsystems}. To do this, the attribute
17293@emph{Source_Files} is set to the empty list, i.e. @cite{()}. Alternatively,
17294@emph{Source_Dirs} can be set to the empty list, with the same
17295result.
17296
17297@geindex Source_List_File (GNAT Project Manager)
17298
17299@item
17300@cite{Source_List_File}.
17301If there is a great number of files, it might be more convenient to use
17302the attribute @strong{Source_List_File}, which specifies the full path of a file.
17303This file must contain a list of source file names (one per line, no
17304directory information) that are searched as if they had been defined
17305through @emph{Source_Files}. Such a file can easily be created through
17306external tools.
17307
17308A warning is issued if both attributes @cite{Source_Files} and
17309@cite{Source_List_File} are given explicit values. In this case, the
17310attribute @cite{Source_Files} prevails.
17311
17312@geindex Excluded_Source_Files (GNAT Project Manager)
17313
17314@geindex Locally_Removed_Files (GNAT Project Manager)
17315
17316@geindex Excluded_Source_List_File (GNAT Project Manager)
17317
17318@item
17319@cite{Excluded_Source_Files}.
17320Specifying an explicit list of files is not always convenient.It might be
17321more convenient to use the default search rules with specific exceptions.
17322This can be done thanks to the attribute @strong{Excluded_Source_Files}
17323(or its synonym @strong{Locally_Removed_Files}).
17324Its value is the list of file names that should not be taken into account.
17325This attribute is often used when extending a project,
17326see @ref{152,,Project Extension}. A similar attribute
17327@strong{Excluded_Source_List_File} plays the same
17328role but takes the name of file containing file names similarly to
17329@cite{Source_List_File}.
17330@end itemize
17331
17332In most simple cases, such as the above example, the default source file search
17333behavior provides the expected result, and we do not need to add anything after
17334setting @cite{Source_Dirs}. The project manager automatically finds
17335@code{pack.ads}, @code{pack.adb}, and @code{proc.adb} as source files of the
17336project.
17337
17338Note that by default a warning is issued when a project has no sources attached
17339to it and this is not explicitly indicated in the project file.
17340
17341@node Duplicate Sources in Projects,Object and Exec Directory,Source Files and Directories,Building With Projects
17342@anchor{gnat_ugn/gnat_project_manager duplicate-sources-in-projects}@anchor{15b}@anchor{gnat_ugn/gnat_project_manager id4}@anchor{15c}
17343@subsection Duplicate Sources in Projects
17344
17345
17346If the order of the source directories is known statically, that is if
17347@cite{"/**"} is not used in the string list @cite{Source_Dirs}, then there may
17348be several files with the same name sitting in different directories of the
17349project. In this case, only the file in the first directory is considered as a
17350source of the project and the others are hidden. If @cite{"/**"} is used in the
17351string list @cite{Source_Dirs}, it is an error to have several files with the
17352same name in the same directory @cite{"/**"} subtree, since there would be an
17353ambiguity as to which one should be used. However, two files with the same name
17354may exist in two single directories or directory subtrees. In this case, the
17355one in the first directory or directory subtree is a source of the project.
17356
17357If there are two sources in different directories of the same @cite{"/**"}
17358subtree, one way to resolve the problem is to exclude the directory of the
17359file that should not be used as a source of the project.
17360
17361@node Object and Exec Directory,Main Subprograms,Duplicate Sources in Projects,Building With Projects
17362@anchor{gnat_ugn/gnat_project_manager object-and-exec-directory}@anchor{15d}@anchor{gnat_ugn/gnat_project_manager id5}@anchor{15e}
17363@subsection Object and Exec Directory
17364
17365
17366The next step when writing a project is to indicate where the compiler should
17367put the object files. In fact, the compiler and other tools might create
17368several different kind of files (for GNAT, there is the object file and the ALI
17369file for instance). One of the important concepts in projects is that most
17370tools may consider source directories as read-only and do not attempt to create
17371new or temporary files there. Instead, all files are created in the object
17372directory. It is of course not true for project-aware IDEs, whose purpose it is
17373to create the source files.
17374
17375@geindex Object_Dir (GNAT Project Manager)
17376
17377The object directory is specified through the @strong{Object_Dir} attribute.
17378Its value is the path to the object directory, either absolute or
17379relative to the directory containing the project file. This
17380directory must already exist and be readable and writable, although
17381some tools have a switch to create the directory if needed (See
17382the switch @cite{-p} for @emph{gprbuild}).
17383
17384If the attribute @cite{Object_Dir} is not specified, it defaults to
17385the project directory, that is the directory containing the project file.
17386
17387For our example, we can specify the object dir in this way:
17388
17389@example
17390project Build is
17391   for Source_Dirs use ("common");
17392   for Object_Dir use "obj";   --  <<<<
17393end Build;
17394@end example
17395
17396As mentioned earlier, there is a single object directory per project. As a
17397result, if you have an existing system where the object files are spread across
17398several directories, you can either move all of them into the same directory if
17399you want to build it with a single project file, or study the section on
17400subsystems (see @ref{151,,Organizing Projects into Subsystems}) to see how each
17401separate object directory can be associated with one of the subsystems
17402constituting the application.
17403
17404When the @emph{linker} is called, it usually creates an executable. By
17405default, this executable is placed in the object directory of the project. It
17406might be convenient to store it in its own directory.
17407
17408@geindex Exec_Dir (GNAT Project Manager)
17409
17410This can be done through the @cite{Exec_Dir} attribute, which, like
17411@emph{Object_Dir} contains a single absolute or relative path and must point to
17412an existing and writable directory, unless you ask the tool to create it on
17413your behalf. When not specified, It defaults to the object directory and
17414therefore to the project file's directory if neither @emph{Object_Dir} nor
17415@emph{Exec_Dir} was specified.
17416
17417In the case of the example, let's place the executable in the root
17418of the hierarchy, ie the same directory as @code{build.gpr}. Hence
17419the project file is now
17420
17421@example
17422project Build is
17423   for Source_Dirs use ("common");
17424   for Object_Dir use "obj";
17425   for Exec_Dir use ".";  --   <<<<
17426end Build;
17427@end example
17428
17429@node Main Subprograms,Tools Options in Project Files,Object and Exec Directory,Building With Projects
17430@anchor{gnat_ugn/gnat_project_manager id6}@anchor{15f}@anchor{gnat_ugn/gnat_project_manager main-subprograms}@anchor{160}
17431@subsection Main Subprograms
17432
17433
17434In the previous section, executables were mentioned. The project manager needs
17435to be taught what they are. In a project file, an executable is indicated by
17436pointing to the source file of a main subprogram. In C this is the file that
17437contains the @cite{main} function, and in Ada the file that contains the main
17438unit.
17439
17440There can be any number of such main files within a given project, and thus
17441several executables can be built in the context of a single project file. Of
17442course, one given executable might not (and in fact will not) need all the
17443source files referenced by the project. As opposed to other build environments
17444such as @emph{makefile}, one does not need to specify the list of
17445dependencies of each executable, the project-aware builder knows enough of the
17446semantics of the languages to build and link only the necessary elements.
17447
17448@geindex Main (GNAT Project Manager)
17449
17450The list of main files is specified via the @strong{Main} attribute. It contains
17451a list of file names (no directories). If a project defines this
17452attribute, it is not necessary to identify  main files on the
17453command line when invoking a builder, and editors like
17454@emph{GPS} will be able to create extra menus to spawn or debug the
17455corresponding executables.
17456
17457@example
17458project Build is
17459   for Source_Dirs use ("common");
17460   for Object_Dir use "obj";
17461   for Exec_Dir use ".";
17462   for Main use ("proc.adb");  --   <<<<
17463end Build;
17464@end example
17465
17466If this attribute is defined in the project, then spawning the builder
17467with a command such as
17468
17469@example
17470gprbuild -Pbuild
17471@end example
17472
17473automatically builds all the executables corresponding to the files
17474listed in the @emph{Main} attribute. It is possible to specify one
17475or more executables on the command line to build a subset of them.
17476
17477@node Tools Options in Project Files,Compiling with Project Files,Main Subprograms,Building With Projects
17478@anchor{gnat_ugn/gnat_project_manager tools-options-in-project-files}@anchor{161}@anchor{gnat_ugn/gnat_project_manager id7}@anchor{162}
17479@subsection Tools Options in Project Files
17480
17481
17482We now have a project file that fully describes our environment, and can be
17483used to build the application with a simple @emph{gprbuild} command as seen
17484in the previous section. In fact, the empty project we showed immediately at
17485the beginning (with no attribute at all) could already fulfill that need if it
17486was put in the @code{common} directory.
17487
17488Of course, we might want more control. This section shows you how to specify
17489the compilation switches that the various tools involved in the building of the
17490executable should use.
17491
17492@geindex command line length (GNAT Project Manager)
17493
17494Since source names and locations are described in the project file, it is not
17495necessary to use switches on the command line for this purpose (switches such
17496as -I for gcc). This removes a major source of command line length overflow.
17497Clearly, the builders will have to communicate this information one way or
17498another to the underlying compilers and tools they call but they usually use
17499response files for this and thus are not subject to command line overflows.
17500
17501Several tools participate to the creation of an executable: the compiler
17502produces object files from the source files; the binder (in the Ada case)
17503creates a "source" file that takes care, among other things, of elaboration
17504issues and global variable initialization; and the linker gathers everything
17505into a single executable that users can execute. All these tools are known to
17506the project manager and will be called with user defined switches from the
17507project files. However, we need to introduce a new project file concept to
17508express the switches to be used for any of the tools involved in the build.
17509
17510@geindex project file packages (GNAT Project Manager)
17511
17512A project file is subdivided into zero or more @strong{packages}, each of which
17513contains the attributes specific to one tool (or one set of tools). Project
17514files use an Ada-like syntax for packages. Package names permitted in project
17515files are restricted to a predefined set (see @ref{156,,Packages}), and the contents
17516of packages are limited to a small set of constructs and attributes
17517(see @ref{155,,Attributes}).
17518
17519Our example project file can be extended with the following empty packages. At
17520this stage, they could all be omitted since they are empty, but they show which
17521packages would be involved in the build process.
17522
17523@example
17524project Build is
17525   for Source_Dirs use ("common");
17526   for Object_Dir use "obj";
17527   for Exec_Dir use ".";
17528   for Main use ("proc.adb");
17529
17530   package Builder is  --<<<  for gprbuild
17531   end Builder;
17532
17533   package Compiler is --<<<  for the compiler
17534   end Compiler;
17535
17536   package Binder is   --<<<  for the binder
17537   end Binder;
17538
17539   package Linker is   --<<<  for the linker
17540   end Linker;
17541end Build;
17542@end example
17543
17544Let's first examine the compiler switches. As stated in the initial description
17545of the example, we want to compile all files with @emph{-O2}. This is a
17546compiler switch, although it is usual, on the command line, to pass it to the
17547builder which then passes it to the compiler. It is recommended to use directly
17548the right package, which will make the setup easier to understand for other
17549people.
17550
17551Several attributes can be used to specify the switches:
17552
17553@geindex Default_Switches (GNAT Project Manager)
17554
17555@strong{Default_Switches}:
17556
17557@quotation
17558
17559This is the first mention in this manual of an @strong{indexed attribute}. When
17560this attribute is defined, one must supply an @emph{index} in the form of a
17561literal string.
17562In the case of @emph{Default_Switches}, the index is the name of the
17563language to which the switches apply (since a different compiler will
17564likely be used for each language, and each compiler has its own set of
17565switches). The value of the attribute is a list of switches.
17566
17567In this example, we want to compile all Ada source files with the switch
17568@emph{-O2}, and the resulting project file is as follows
17569(only the @cite{Compiler} package is shown):
17570
17571@example
17572package Compiler is
17573  for Default_Switches ("Ada") use ("-O2");
17574end Compiler;
17575@end example
17576@end quotation
17577
17578@geindex Switches (GNAT Project Manager)
17579
17580@strong{Switches}:
17581
17582@quotation
17583
17584In some cases, we might want to use specific switches
17585for one or more files. For instance, compiling @code{proc.adb} might not be
17586possible at high level of optimization because of a compiler issue.
17587In such a case, the @emph{Switches}
17588attribute (indexed on the file name) can be used and will override the
17589switches defined by @emph{Default_Switches}. Our project file would
17590become:
17591
17592@example
17593package Compiler is
17594   for Default_Switches ("Ada")
17595       use ("-O2");
17596   for Switches ("proc.adb")
17597       use ("-O0");
17598end Compiler;
17599@end example
17600
17601@cite{Switches} may take a pattern as an index, such as in:
17602
17603@example
17604package Compiler is
17605  for Default_Switches ("Ada")
17606      use ("-O2");
17607  for Switches ("pkg*")
17608      use ("-O0");
17609end Compiler;
17610@end example
17611
17612Sources @code{pkg.adb} and @code{pkg-child.adb} would be compiled with -O0,
17613not -O2.
17614
17615@cite{Switches} can also be given a language name as index instead of a file
17616name in which case it has the same semantics as @emph{Default_Switches}.
17617However, indexes with wild cards are never valid for language name.
17618@end quotation
17619
17620@geindex Local_Configuration_Pragmas (GNAT Project Manager)
17621
17622@strong{Local_Configuration_Pragmas}:
17623
17624@quotation
17625
17626This attribute may specify the path
17627of a file containing configuration pragmas for use by the Ada compiler,
17628such as @cite{pragma Restrictions (No_Tasking)}. These pragmas will be
17629used for all the sources of the project.
17630@end quotation
17631
17632The switches for the other tools are defined in a similar manner through the
17633@strong{Default_Switches} and @strong{Switches} attributes, respectively in the
17634@emph{Builder} package (for @emph{gprbuild}),
17635the @emph{Binder} package (binding Ada executables) and the @emph{Linker}
17636package (for linking executables).
17637
17638@node Compiling with Project Files,Executable File Names,Tools Options in Project Files,Building With Projects
17639@anchor{gnat_ugn/gnat_project_manager compiling-with-project-files}@anchor{163}@anchor{gnat_ugn/gnat_project_manager id8}@anchor{164}
17640@subsection Compiling with Project Files
17641
17642
17643Now that our project files are written, let's build our executable.
17644Here is the command we would use from the command line:
17645
17646@example
17647gprbuild -Pbuild
17648@end example
17649
17650This will automatically build the executables specified through the
17651@emph{Main} attribute: for each, it will compile or recompile the
17652sources for which the object file does not exist or is not up-to-date; it
17653will then run the binder; and finally run the linker to create the
17654executable itself.
17655
17656The @emph{gprbuild} builder, can automatically manage C files the
17657same way: create the file @code{utils.c} in the @code{common} directory,
17658set the attribute @emph{Languages} to @cite{"(Ada@comma{} C)"}, and re-run
17659
17660@example
17661gprbuild -Pbuild
17662@end example
17663
17664Gprbuild knows how to recompile the C files and will
17665recompile them only if one of their dependencies has changed. No direct
17666indication on how to build the various elements is given in the
17667project file, which describes the project properties rather than a
17668set of actions to be executed. Here is the invocation of
17669@emph{gprbuild} when building a multi-language program:
17670
17671@example
17672$ gprbuild -Pbuild
17673gcc -c proc.adb
17674gcc -c pack.adb
17675gcc -c utils.c
17676gprbind proc
17677...
17678gcc proc.o -o proc
17679@end example
17680
17681Notice the three steps described earlier:
17682
17683
17684@itemize *
17685
17686@item
17687The first three gcc commands correspond to the compilation phase.
17688
17689@item
17690The gprbind command corresponds to the post-compilation phase.
17691
17692@item
17693The last gcc command corresponds to the final link.
17694@end itemize
17695
17696@geindex -v option (for GPRbuild)
17697
17698The default output of GPRbuild's execution is kept reasonably simple and easy
17699to understand. In particular, some of the less frequently used commands are not
17700shown, and some parameters are abbreviated. So it is not possible to rerun the
17701effect of the @emph{gprbuild} command by cut-and-pasting its output.
17702GPRbuild's option @cite{-v} provides a much more verbose output which includes,
17703among other information, more complete compilation, post-compilation and link
17704commands.
17705
17706@node Executable File Names,Avoid Duplication With Variables,Compiling with Project Files,Building With Projects
17707@anchor{gnat_ugn/gnat_project_manager executable-file-names}@anchor{165}@anchor{gnat_ugn/gnat_project_manager id9}@anchor{166}
17708@subsection Executable File Names
17709
17710
17711@geindex Executable (GNAT Project Manager)
17712
17713By default, the executable name corresponding to a main file is
17714computed from the main source file name. Through the attribute
17715@strong{Builder.Executable}, it is possible to change this default.
17716
17717For instance, instead of building @emph{proc} (or @emph{proc.exe}
17718on Windows), we could configure our project file to build "proc1"
17719(resp proc1.exe) with the following addition:
17720
17721@example
17722project Build is
17723   ...  --  same as before
17724   package Builder is
17725      for Executable ("proc.adb") use "proc1";
17726   end Builder
17727end Build;
17728@end example
17729
17730@geindex Executable_Suffix (GNAT Project Manager)
17731
17732Attribute @strong{Executable_Suffix}, when specified, may change the suffix
17733of the executable files, when no attribute @cite{Executable} applies:
17734its value replaces the platform-specific executable suffix.
17735The default executable suffix is empty on UNIX and ".exe" on Windows.
17736
17737It is also possible to change the name of the produced executable by using the
17738command line switch @emph{-o}. When several mains are defined in the project,
17739it is not possible to use the @emph{-o} switch and the only way to change the
17740names of the executable is provided by Attributes @cite{Executable} and
17741@cite{Executable_Suffix}.
17742
17743@node Avoid Duplication With Variables,Naming Schemes,Executable File Names,Building With Projects
17744@anchor{gnat_ugn/gnat_project_manager id10}@anchor{167}@anchor{gnat_ugn/gnat_project_manager avoid-duplication-with-variables}@anchor{168}
17745@subsection Avoid Duplication With Variables
17746
17747
17748To illustrate some other project capabilities, here is a slightly more complex
17749project using similar sources and a main program in C:
17750
17751@example
17752project C_Main is
17753   for Languages    use ("Ada", "C");
17754   for Source_Dirs  use ("common");
17755   for Object_Dir   use  "obj";
17756   for Main         use ("main.c");
17757   package Compiler is
17758      C_Switches := ("-pedantic");
17759      for Default_Switches ("C")   use C_Switches;
17760      for Default_Switches ("Ada") use ("-gnaty");
17761      for Switches ("main.c") use C_Switches & ("-g");
17762   end Compiler;
17763end C_Main;
17764@end example
17765
17766This project has many similarities with the previous one.
17767As expected, its @cite{Main} attribute now refers to a C source.
17768The attribute @emph{Exec_Dir} is now omitted, thus the resulting
17769executable will be put in the directory @code{obj}.
17770
17771The most noticeable difference is the use of a variable in the
17772@emph{Compiler} package to store settings used in several attributes.
17773This avoids text duplication, and eases maintenance (a single place to
17774modify if we want to add new switches for C files). We will revisit
17775the use of variables in the context of scenarios (see @ref{14f,,Scenarios in Projects}).
17776
17777In this example, we see how the file @code{main.c} can be compiled with
17778the switches used for all the other C files, plus @emph{-g}.
17779In this specific situation the use of a variable could have been
17780replaced by a reference to the @cite{Default_Switches} attribute:
17781
17782@example
17783for Switches ("c_main.c") use Compiler'Default_Switches ("C") & ("-g");
17784@end example
17785
17786Note the tick (@emph{'}) used to refer to attributes defined in a package.
17787
17788Here is the output of the GPRbuild command using this project:
17789
17790@example
17791$ gprbuild -Pc_main
17792gcc -c -pedantic -g main.c
17793gcc -c -gnaty proc.adb
17794gcc -c -gnaty pack.adb
17795gcc -c -pedantic utils.c
17796gprbind main.bexch
17797...
17798gcc main.o -o main
17799@end example
17800
17801The default switches for Ada sources,
17802the default switches for C sources (in the compilation of @code{lib.c}),
17803and the specific switches for @code{main.c} have all been taken into
17804account.
17805
17806@node Naming Schemes,Installation,Avoid Duplication With Variables,Building With Projects
17807@anchor{gnat_ugn/gnat_project_manager id11}@anchor{169}@anchor{gnat_ugn/gnat_project_manager naming-schemes}@anchor{14e}
17808@subsection Naming Schemes
17809
17810
17811Sometimes an Ada software system is ported from one compilation environment to
17812another (say GNAT), and the file are not named using the default GNAT
17813conventions. Instead of changing all the file names, which for a variety of
17814reasons might not be possible, you can define the relevant file naming scheme
17815in the @strong{Naming} package of your project file.
17816
17817The naming scheme has two distinct goals for the project manager: it
17818allows finding of source files when searching in the source
17819directories, and given a source file name it makes it possible to guess
17820the associated language, and thus the compiler to use.
17821
17822Note that the use by the Ada compiler of pragmas Source_File_Name is not
17823supported when using project files. You must use the features described in this
17824paragraph. You can however specify other configuration pragmas.
17825
17826The following attributes can be defined in package @cite{Naming}:
17827
17828@geindex Casing (GNAT Project Manager)
17829
17830@strong{Casing}:
17831
17832@quotation
17833
17834Its value must be one of @cite{"lowercase"} (the default if
17835unspecified), @cite{"uppercase"} or @cite{"mixedcase"}. It describes the
17836casing of file names with regards to the Ada unit name. Given an Ada unit
17837My_Unit, the file name will respectively be @code{my_unit.adb} (lowercase),
17838@code{MY_UNIT.ADB} (uppercase) or @code{My_Unit.adb} (mixedcase).
17839On Windows, file names are case insensitive, so this attribute is
17840irrelevant.
17841@end quotation
17842
17843@geindex Dot_Replacement (GNAT Project Manager)
17844
17845@strong{Dot_Replacement}:
17846
17847@quotation
17848
17849This attribute specifies the string that should replace the "." in unit
17850names. Its default value is @cite{"-"} so that a unit
17851@cite{Parent.Child} is expected to be found in the file
17852@code{parent-child.adb}. The replacement string must satisfy the following
17853requirements to avoid ambiguities in the naming scheme:
17854
17855
17856@itemize *
17857
17858@item
17859It must not be empty
17860
17861@item
17862It cannot start or end with an alphanumeric character
17863
17864@item
17865It cannot be a single underscore
17866
17867@item
17868It cannot start with an underscore followed by an alphanumeric
17869
17870@item
17871It cannot contain a dot @cite{'.'} except if the entire string is @cite{"."}
17872@end itemize
17873@end quotation
17874
17875@geindex Spec_Suffix (GNAT Project Manager)
17876
17877@geindex Specification_Suffix (GNAT Project Manager)
17878
17879@strong{Spec_Suffix} and @strong{Specification_Suffix}:
17880
17881@quotation
17882
17883For Ada, these attributes give the suffix used in file names that contain
17884specifications. For other languages, they give the extension for files
17885that contain declaration (header files in C for instance). The attribute
17886is indexed on the language.
17887The two attributes are equivalent, but the latter is obsolescent.
17888
17889If the value of the attribute is the empty string, it indicates to the
17890Project Manager that the only specifications/header files for the language
17891are those specified with attributes @cite{Spec} or
17892@cite{Specification_Exceptions}.
17893
17894If @cite{Spec_Suffix ("Ada")} is not specified, then the default is
17895@cite{".ads"}.
17896
17897A non empty value must satisfy the following requirements:
17898
17899
17900@itemize *
17901
17902@item
17903It must include at least one dot
17904
17905@item
17906If @cite{Dot_Replacement} is a single dot, then it cannot include
17907more than one dot.
17908@end itemize
17909@end quotation
17910
17911@geindex Body_Suffix (GNAT Project Manager)
17912
17913@geindex Implementation_Suffix (GNAT Project Manager)
17914
17915@strong{Body_Suffix} and @strong{Implementation_Suffix}:
17916
17917@quotation
17918
17919These attributes give the extension used for file names that contain
17920code (bodies in Ada). They are indexed on the language. The second
17921version is obsolescent and fully replaced by the first attribute.
17922
17923For each language of a project, one of these two attributes need to be
17924specified, either in the project itself or in the configuration project file.
17925
17926If the value of the attribute is the empty string, it indicates to the
17927Project Manager that the only source files for the language
17928are those specified with attributes @cite{Body} or
17929@cite{Implementation_Exceptions}.
17930
17931These attributes must satisfy the same requirements as @cite{Spec_Suffix}.
17932In addition, they must be different from any of the values in
17933@cite{Spec_Suffix}.
17934If @cite{Body_Suffix ("Ada")} is not specified, then the default is
17935@cite{".adb"}.
17936
17937If @cite{Body_Suffix ("Ada")} and @cite{Spec_Suffix ("Ada")} end with the
17938same string, then a file name that ends with the longest of these two
17939suffixes will be a body if the longest suffix is @cite{Body_Suffix ("Ada")}
17940or a spec if the longest suffix is @cite{Spec_Suffix ("Ada")}.
17941
17942If the suffix does not start with a '.', a file with a name exactly equal to
17943the suffix will also be part of the project (for instance if you define the
17944suffix as @cite{Makefile.in}, a file called @code{Makefile.in} will be part
17945of the project. This capability is usually not interesting when building.
17946However, it might become useful when a project is also used to
17947find the list of source files in an editor, like the GNAT Programming System
17948(GPS).
17949@end quotation
17950
17951@geindex Separate_Suffix (GNAT Project Manager)
17952
17953@strong{Separate_Suffix}:
17954
17955@quotation
17956
17957This attribute is specific to Ada. It denotes the suffix used in file names
17958that contain separate bodies. If it is not specified, then it defaults to
17959same value as @cite{Body_Suffix ("Ada")}.
17960
17961The value of this attribute cannot be the empty string.
17962
17963Otherwise, the same rules apply as for the
17964@cite{Body_Suffix} attribute. The only accepted index is "Ada".
17965@end quotation
17966
17967@strong{Spec} or @strong{Specification}:
17968
17969@quotation
17970
17971@geindex Spec (GNAT Project Manager)
17972
17973@geindex Specification (GNAT Project Manager)
17974
17975This attribute @cite{Spec} can be used to define the source file name for a
17976given Ada compilation unit's spec. The index is the literal name of the Ada
17977unit (case insensitive). The value is the literal base name of the file that
17978contains this unit's spec (case sensitive or insensitive depending on the
17979operating system). This attribute allows the definition of exceptions to the
17980general naming scheme, in case some files do not follow the usual
17981convention.
17982
17983When a source file contains several units, the relative position of the unit
17984can be indicated. The first unit in the file is at position 1
17985
17986@example
17987for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
17988for Spec ("top") use "foo.a" at 1;
17989for Spec ("foo") use "foo.a" at 2;
17990@end example
17991@end quotation
17992
17993@geindex Body (GNAT Project Manager)
17994
17995@geindex Implementation (GNAT Project Manager)
17996
17997@strong{Body} or @strong{Implementation}:
17998
17999@quotation
18000
18001These attribute play the same role as @emph{Spec} for Ada bodies.
18002@end quotation
18003
18004@geindex Specification_Exceptions (GNAT Project Manager)
18005
18006@geindex Implementation_Exceptions (GNAT Project Manager)
18007
18008@strong{Specification_Exceptions} and @strong{Implementation_Exceptions}:
18009
18010@quotation
18011
18012These attributes define exceptions to the naming scheme for languages
18013other than Ada. They are indexed on the language name, and contain
18014a list of file names respectively for headers and source code.
18015@end quotation
18016
18017For example, the following package models the Apex file naming rules:
18018
18019@example
18020package Naming is
18021  for Casing               use "lowercase";
18022  for Dot_Replacement      use ".";
18023  for Spec_Suffix ("Ada")  use ".1.ada";
18024  for Body_Suffix ("Ada")  use ".2.ada";
18025end Naming;
18026@end example
18027
18028@node Installation,Distributed support,Naming Schemes,Building With Projects
18029@anchor{gnat_ugn/gnat_project_manager id12}@anchor{16a}@anchor{gnat_ugn/gnat_project_manager installation}@anchor{16b}
18030@subsection Installation
18031
18032
18033After building an application or a library it is often required to
18034install it into the development environment. For instance this step is
18035required if the library is to be used by another application.
18036The @emph{gprinstall} tool provides an easy way to install
18037libraries, executable or object code generated during the build. The
18038@strong{Install} package can be used to change the default locations.
18039
18040The following attributes can be defined in package @cite{Install}:
18041
18042@geindex Active (GNAT Project Manager)
18043
18044
18045@table @asis
18046
18047@item @strong{Active}
18048
18049Whether the project is to be installed, values are @cite{true}
18050(default) or @cite{false}.
18051@end table
18052
18053@geindex Artifacts (GNAT Project Manager)
18054
18055@strong{Artifacts}
18056
18057@quotation
18058
18059An array attribute to declare a set of files not part of the sources
18060to be installed. The array discriminant is the directory where the
18061file is to be installed. If a relative directory then Prefix (see
18062below) is prepended. Note also that if the same file name occurs
18063multiple time in the attribute list, the last one will be the one
18064installed.
18065@end quotation
18066
18067@geindex Prefix (GNAT Project Manager)
18068
18069@strong{Prefix}:
18070
18071@quotation
18072
18073Root directory for the installation.
18074@end quotation
18075
18076@strong{Exec_Subdir}
18077
18078@quotation
18079
18080Subdirectory of @strong{Prefix} where executables are to be
18081installed. Default is @strong{bin}.
18082@end quotation
18083
18084@strong{Lib_Subdir}
18085
18086@quotation
18087
18088Subdirectory of @strong{Prefix} where directory with the library or object
18089files is to be installed. Default is @strong{lib}.
18090@end quotation
18091
18092@strong{Sources_Subdir}
18093
18094@quotation
18095
18096Subdirectory of @strong{Prefix} where directory with sources is to be
18097installed. Default is @strong{include}.
18098@end quotation
18099
18100@strong{Project_Subdir}
18101
18102@quotation
18103
18104Subdirectory of @strong{Prefix} where the generated project file is to be
18105installed. Default is @strong{share/gpr}.
18106@end quotation
18107
18108@strong{Mode}
18109
18110@quotation
18111
18112The installation mode, it is either @strong{dev} (default) or @strong{usage}.
18113See @strong{gprbuild} user's guide for details.
18114@end quotation
18115
18116@strong{Install_Name}
18117
18118@quotation
18119
18120Specify the name to use for recording the installation. The default is
18121the project name without the extension.
18122@end quotation
18123
18124@node Distributed support,,Installation,Building With Projects
18125@anchor{gnat_ugn/gnat_project_manager id13}@anchor{16c}@anchor{gnat_ugn/gnat_project_manager distributed-support}@anchor{16d}
18126@subsection Distributed support
18127
18128
18129For large projects the compilation time can become a limitation in
18130the development cycle. To cope with that, GPRbuild supports
18131distributed compilation.
18132
18133The following attributes can be defined in package @cite{Remote}:
18134
18135@geindex Root_Dir (GNAT Project Manager)
18136
18137@strong{Root_Dir}:
18138
18139@quotation
18140
18141Root directory of the project's sources. The default value is the
18142project's directory.
18143@end quotation
18144
18145@node Organizing Projects into Subsystems,Scenarios in Projects,Building With Projects,GNAT Project Manager
18146@anchor{gnat_ugn/gnat_project_manager organizing-projects-into-subsystems}@anchor{151}@anchor{gnat_ugn/gnat_project_manager id14}@anchor{16e}
18147@section Organizing Projects into Subsystems
18148
18149
18150A @strong{subsystem} is a coherent part of the complete system to be built. It is
18151represented by a set of sources and one single object directory. A system can
18152be composed of a single subsystem when it is simple as we have seen in the
18153first section. Complex systems are usually composed of several interdependent
18154subsystems. A subsystem is dependent on another subsystem if knowledge of the
18155other one is required to build it, and in particular if visibility on some of
18156the sources of this other subsystem is required. Each subsystem is usually
18157represented by its own project file.
18158
18159In this section, the previous example is being extended. Let's assume some
18160sources of our @cite{Build} project depend on other sources.
18161For instance, when building a graphical interface, it is usual to depend upon
18162a graphical library toolkit such as GtkAda. Furthermore, we also need
18163sources from a logging module we had previously written.
18164
18165@menu
18166* Project Dependencies::
18167* Cyclic Project Dependencies::
18168* Sharing Between Projects::
18169* Global Attributes::
18170
18171@end menu
18172
18173@node Project Dependencies,Cyclic Project Dependencies,,Organizing Projects into Subsystems
18174@anchor{gnat_ugn/gnat_project_manager project-dependencies}@anchor{16f}@anchor{gnat_ugn/gnat_project_manager id15}@anchor{170}
18175@subsection Project Dependencies
18176
18177
18178GtkAda comes with its own project file (appropriately called
18179@code{gtkada.gpr}), and we will assume we have already built a project
18180called @code{logging.gpr} for the logging module. With the information provided
18181so far in @code{build.gpr}, building the application would fail with an error
18182indicating that the gtkada and logging units that are relied upon by the sources
18183of this project cannot be found.
18184
18185This is solved by adding the following @strong{with} clauses at the beginning of our
18186project:
18187
18188@example
18189with "gtkada.gpr";
18190with "a/b/logging.gpr";
18191project Build is
18192  ...  --  as before
18193end Build;
18194@end example
18195
18196@geindex Externally_Built (GNAT Project Manager)
18197
18198When such a project is compiled, @emph{gprbuild} will automatically check
18199the other projects and recompile their sources when needed. It will also
18200recompile the sources from @cite{Build} when needed, and finally create the
18201executable. In some cases, the implementation units needed to recompile a
18202project are not available, or come from some third party and you do not want to
18203recompile it yourself. In this case, set the attribute @strong{Externally_Built} to
18204"true", indicating to the builder that this project can be assumed to be
18205up-to-date, and should not be considered for recompilation. In Ada, if the
18206sources of this externally built project were compiled with another version of
18207the compiler or with incompatible options, the binder will issue an error.
18208
18209The project's @emph{with} clause has several effects. It provides source
18210visibility between projects during the compilation process. It also guarantees
18211that the necessary object files from @cite{Logging} and @cite{GtkAda} are
18212available when linking @cite{Build}.
18213
18214As can be seen in this example, the syntax for importing projects is similar
18215to the syntax for importing compilation units in Ada. However, project files
18216use literal strings instead of names, and the @emph{with} clause identifies
18217project files rather than packages.
18218
18219Each literal string after @emph{with} is the path
18220(absolute or relative) to a project file. The @cite{.gpr} extension is
18221optional, although we recommend adding it. If no extension is specified,
18222and no project file with the @code{.gpr} extension is found, then
18223the file is searched for exactly as written in the @emph{with} clause,
18224that is with no extension.
18225
18226As mentioned above, the path after a @emph{with} has to be a literal
18227string, and you cannot use concatenation, or lookup the value of external
18228variables to change the directories from which a project is loaded.
18229A solution if you need something like this is to use aggregate projects
18230(see @ref{171,,Aggregate Projects}).
18231
18232@geindex project path (GNAT Project Manager)
18233
18234When a relative path or a base name is used, the
18235project files are searched relative to each of the directories in the
18236@strong{project path}. This path includes all the directories found with the
18237following algorithm, in this order; the first matching file is used:
18238
18239
18240@itemize *
18241
18242@item
18243First, the file is searched relative to the directory that contains the
18244current project file.
18245
18246@geindex GPR_PROJECT_PATH_FILE (GNAT Project Manager)
18247
18248@geindex GPR_PROJECT_PATH (GNAT Project Manager)
18249
18250@geindex ADA_PROJECT_PATH (GNAT Project Manager)
18251
18252@item
18253Then it is searched relative to all the directories specified in the
18254environment variables @strong{GPR_PROJECT_PATH_FILE},
18255@strong{GPR_PROJECT_PATH} and @strong{ADA_PROJECT_PATH} (in that order) if they exist.
18256The value of @strong{GPR_PROJECT_PATH_FILE}, when defined, is the path name of
18257a text file that contains project directory path names, one per line.
18258@strong{GPR_PROJECT_PATH} and @strong{ADA_PROJECT_PATH}, when defined, contain
18259project directory path names separated by directory separators.
18260@strong{ADA_PROJECT_PATH} is used for compatibility, it is recommended to
18261use @strong{GPR_PROJECT_PATH_FILE} or @strong{GPR_PROJECT_PATH}.
18262
18263@item
18264Finally, it is searched relative to the default project directories.
18265Such directories depend on the tool used. The locations searched in the
18266specified order are:
18267
18268
18269@itemize *
18270
18271@item
18272@code{<prefix>/<target>/lib/gnat} if option @emph{--target} is specified
18273
18274@item
18275@code{<prefix>/<target>/share/gpr} if option @emph{--target} is specified
18276
18277@item
18278@code{<prefix>/share/gpr/}
18279
18280@item
18281@code{<prefix>/lib/gnat/}
18282@end itemize
18283
18284In our example, @code{gtkada.gpr} is found in the predefined directory if
18285it was installed at the same root as GNAT.
18286@end itemize
18287
18288Some tools also support extending the project path from the command line,
18289generally through the @emph{-aP}. You can see the value of the project
18290path by using the @emph{gnatls -v} command.
18291
18292Any symbolic link will be fully resolved in the directory of the
18293importing project file before the imported project file is examined.
18294
18295Any source file in the imported project can be used by the sources of the
18296importing project, transitively.
18297Thus if @cite{A} imports @cite{B}, which imports @cite{C}, the sources of
18298@cite{A} may depend on the sources of @cite{C}, even if @cite{A} does not
18299import @cite{C} explicitly. However, this is not recommended, because if
18300and when @cite{B} ceases to import @cite{C}, some sources in @cite{A} will
18301no longer compile. @emph{gprbuild} has a switch @emph{--no-indirect-imports}
18302that will report such indirect dependencies.
18303
18304@cartouche
18305@quotation Note
18306One very important aspect of a project hierarchy is that
18307@strong{a given source can only belong to one project} (otherwise the project manager
18308would not know which settings apply to it and when to recompile it). It means
18309that different project files do not usually share source directories or
18310when they do, they need to specify precisely which project owns which sources
18311using attribute @cite{Source_Files} or equivalent. By contrast, 2 projects
18312can each own a source with the same base file name as long as they live in
18313different directories. The latter is not true for Ada Sources because of the
18314correlation between source files and Ada units.
18315@end quotation
18316@end cartouche
18317
18318@node Cyclic Project Dependencies,Sharing Between Projects,Project Dependencies,Organizing Projects into Subsystems
18319@anchor{gnat_ugn/gnat_project_manager id16}@anchor{172}@anchor{gnat_ugn/gnat_project_manager cyclic-project-dependencies}@anchor{173}
18320@subsection Cyclic Project Dependencies
18321
18322
18323Cyclic dependencies are mostly forbidden:
18324if @cite{A} imports @cite{B} (directly or indirectly) then @cite{B}
18325is not allowed to import @cite{A}. However, there are cases when cyclic
18326dependencies would be beneficial. For these cases, another form of import
18327between projects exists: the @strong{limited with}.  A project @cite{A} that
18328imports a project @cite{B} with a straight @emph{with} may also be imported,
18329directly or indirectly, by @cite{B} through a @cite{limited with}.
18330
18331The difference between straight @emph{with} and @cite{limited with} is that
18332the name of a project imported with a @cite{limited with} cannot be used in the
18333project importing it. In particular, its packages cannot be renamed and
18334its variables cannot be referred to.
18335
18336@example
18337with "b.gpr";
18338with "c.gpr";
18339project A is
18340    for Exec_Dir use B'Exec_Dir; -- ok
18341end A;
18342
18343limited with "a.gpr";   --  Cyclic dependency: A -> B -> A
18344project B is
18345   for Exec_Dir use A'Exec_Dir; -- not ok
18346end B;
18347
18348with "d.gpr";
18349project C is
18350end C;
18351
18352limited with "a.gpr";  --  Cyclic dependency: A -> C -> D -> A
18353project D is
18354   for Exec_Dir use A'Exec_Dir; -- not ok
18355end D;
18356@end example
18357
18358@node Sharing Between Projects,Global Attributes,Cyclic Project Dependencies,Organizing Projects into Subsystems
18359@anchor{gnat_ugn/gnat_project_manager sharing-between-projects}@anchor{174}@anchor{gnat_ugn/gnat_project_manager id17}@anchor{175}
18360@subsection Sharing Between Projects
18361
18362
18363When building an application, it is common to have similar needs in several of
18364the projects corresponding to the subsystems under construction. For instance,
18365they will all have the same compilation switches.
18366
18367As seen before (see @ref{161,,Tools Options in Project Files}), setting compilation
18368switches for all sources of a subsystem is simple: it is just a matter of
18369adding a @cite{Compiler.Default_Switches} attribute to each project files with
18370the same value. Of course, that means duplication of data, and both places need
18371to be changed in order to recompile the whole application with different
18372switches. It can become a real problem if there are many subsystems and thus
18373many project files to edit.
18374
18375There are two main approaches to avoiding this duplication:
18376
18377
18378@itemize *
18379
18380@item
18381Since @code{build.gpr} imports @code{logging.gpr}, we could change it
18382to reference the attribute in Logging, either through a package renaming,
18383or by referencing the attribute. The following example shows both cases:
18384
18385@example
18386project Logging is
18387   package Compiler is
18388      for Switches ("Ada")
18389          use ("-O2");
18390   end Compiler;
18391   package Binder is
18392      for Switches ("Ada")
18393          use ("-E");
18394   end Binder;
18395end Logging;
18396
18397with "logging.gpr";
18398project Build is
18399   package Compiler renames Logging.Compiler;
18400   package Binder is
18401      for Switches ("Ada") use Logging.Binder'Switches ("Ada");
18402   end Binder;
18403end Build;
18404@end example
18405
18406The solution used for @cite{Compiler} gets the same value for all
18407attributes of the package, but you cannot modify anything from the
18408package (adding extra switches or some exceptions). The second
18409version is more flexible, but more verbose.
18410
18411If you need to refer to the value of a variable in an imported
18412project, rather than an attribute, the syntax is similar but uses
18413a "." rather than an apostrophe. For instance:
18414
18415@example
18416with "imported";
18417project Main is
18418   Var1 := Imported.Var;
18419end Main;
18420@end example
18421
18422@item
18423The second approach is to define the switches in a third project.
18424That project is set up without any sources (so that, as opposed to
18425the first example, none of the project plays a special role), and
18426will only be used to define the attributes. Such a project is
18427typically called @code{shared.gpr}.
18428
18429@example
18430abstract project Shared is
18431   for Source_Files use ();   --  no sources
18432   package Compiler is
18433      for Switches ("Ada")
18434          use ("-O2");
18435   end Compiler;
18436end Shared;
18437
18438with "shared.gpr";
18439project Logging is
18440   package Compiler renames Shared.Compiler;
18441end Logging;
18442
18443with "shared.gpr";
18444project Build is
18445   package Compiler renames Shared.Compiler;
18446end Build;
18447@end example
18448
18449As for the first example, we could have chosen to set the attributes
18450one by one rather than to rename a package. The reason we explicitly
18451indicate that @cite{Shared} has no sources is so that it can be created
18452in any directory and we are sure it shares no sources with @cite{Build}
18453or @cite{Logging}, which of course would be invalid.
18454
18455@geindex project qualifier (GNAT Project Manager)
18456
18457Note the additional use of the @strong{abstract} qualifier in @code{shared.gpr}.
18458This qualifier is optional, but helps convey the message that we do not
18459intend this project to have sources (see @ref{176,,Qualified Projects} for
18460more qualifiers).
18461@end itemize
18462
18463@node Global Attributes,,Sharing Between Projects,Organizing Projects into Subsystems
18464@anchor{gnat_ugn/gnat_project_manager global-attributes}@anchor{177}@anchor{gnat_ugn/gnat_project_manager id18}@anchor{178}
18465@subsection Global Attributes
18466
18467
18468We have already seen many examples of attributes used to specify a special
18469option of one of the tools involved in the build process. Most of those
18470attributes are project specific. That it to say, they only affect the invocation
18471of tools on the sources of the project where they are defined.
18472
18473There are a few additional attributes that apply to all projects in a
18474hierarchy as long as they are defined on the "main" project.
18475The main project is the project explicitly mentioned on the command-line.
18476The project hierarchy is the "with"-closure of the main project.
18477
18478Here is a list of commonly used global attributes:
18479
18480@geindex Global_Configuration_Pragmas (GNAT Project Manager)
18481
18482@strong{Builder.Global_Configuration_Pragmas}:
18483
18484@quotation
18485
18486This attribute points to a file that contains configuration pragmas
18487to use when building executables. These pragmas apply for all
18488executables built from this project hierarchy. As we have seen before,
18489additional pragmas can be specified on a per-project basis by setting the
18490@cite{Compiler.Local_Configuration_Pragmas} attribute.
18491@end quotation
18492
18493@geindex Global_Compilation_Switches (GNAT Project Manager)
18494
18495@strong{Builder.Global_Compilation_Switches}:
18496
18497@quotation
18498
18499This attribute is a list of compiler switches to use when compiling any
18500source file in the project hierarchy. These switches are used in addition
18501to the ones defined in the @cite{Compiler} package, which only apply to
18502the sources of the corresponding project. This attribute is indexed on
18503the name of the language.
18504@end quotation
18505
18506Using such global capabilities is convenient. It can also lead to unexpected
18507behavior. Especially when several subsystems are shared among different main
18508projects and the different global attributes are not
18509compatible. Note that using aggregate projects can be a safer and more powerful
18510replacement to global attributes.
18511
18512@node Scenarios in Projects,Library Projects,Organizing Projects into Subsystems,GNAT Project Manager
18513@anchor{gnat_ugn/gnat_project_manager id19}@anchor{179}@anchor{gnat_ugn/gnat_project_manager scenarios-in-projects}@anchor{14f}
18514@section Scenarios in Projects
18515
18516
18517Various aspects of the projects can be modified based on @strong{scenarios}. These
18518are user-defined modes that change the behavior of a project. Typical
18519examples are the setup of platform-specific compiler options, or the use of
18520a debug and a release mode (the former would activate the generation of debug
18521information, while the second will focus on improving code optimization).
18522
18523Let's enhance our example to support debug and release modes. The issue is to
18524let the user choose what kind of system he is building: use @emph{-g} as
18525compiler switches in debug mode and @emph{-O2} in release mode. We will also
18526set up the projects so that we do not share the same object directory in both
18527modes; otherwise switching from one to the other might trigger more
18528recompilations than needed or mix objects from the two modes.
18529
18530One naive approach is to create two different project files, say
18531@code{build_debug.gpr} and @code{build_release.gpr}, that set the appropriate
18532attributes as explained in previous sections. This solution does not scale
18533well, because in the presence of multiple projects depending on each other, you
18534will also have to duplicate the complete hierarchy and adapt the project files
18535to point to the right copies.
18536
18537@geindex scenarios (GNAT Project Manager)
18538
18539Instead, project files support the notion of scenarios controlled
18540by external values. Such values can come from several sources (in decreasing
18541order of priority):
18542
18543@geindex -X (usage with GNAT Project Manager)
18544
18545
18546@table @asis
18547
18548@item @strong{Command line}:
18549
18550When launching @emph{gprbuild}, the user can pass
18551extra @emph{-X} switches to define the external value. In
18552our case, the command line might look like
18553
18554@example
18555gprbuild -Pbuild.gpr -Xmode=release
18556@end example
18557
18558@item @strong{Environment variables}:
18559
18560When the external value does not come from the command line, it can come from
18561the value of environment variables of the appropriate name.
18562In our case, if an environment variable called "mode"
18563exists, its value will be taken into account.
18564@end table
18565
18566@geindex external (GNAT Project Manager)
18567
18568@strong{External function second parameter}.
18569
18570We now need to get that value in the project. The general form is to use
18571the predefined function @strong{external} which returns the current value of
18572the external. For instance, we could set up the object directory to point to
18573either @code{obj/debug} or @code{obj/release} by changing our project to
18574
18575@example
18576project Build is
18577    for Object_Dir use "obj/" & external ("mode", "debug");
18578    ... --  as before
18579end Build;
18580@end example
18581
18582The second parameter to @cite{external} is optional, and is the default
18583value to use if "mode" is not set from the command line or the environment.
18584
18585In order to set the switches according to the different scenarios, other
18586constructs have to be introduced such as typed variables and case constructions.
18587
18588@geindex typed variable (GNAT Project Manager)
18589
18590@geindex case construction (GNAT Project Manager)
18591
18592A @strong{typed variable} is a variable that
18593can take only a limited number of values, similar to an enumeration in Ada.
18594Such a variable can then be used in a @strong{case construction} and create conditional
18595sections in the project. The following example shows how this can be done:
18596
18597@example
18598project Build is
18599   type Mode_Type is ("debug", "release");  --  all possible values
18600   Mode : Mode_Type := external ("mode", "debug"); -- a typed variable
18601
18602   package Compiler is
18603      case Mode is
18604         when "debug" =>
18605            for Switches ("Ada")
18606                use ("-g");
18607         when "release" =>
18608            for Switches ("Ada")
18609                use ("-O2");
18610      end case;
18611   end Compiler;
18612end Build;
18613@end example
18614
18615The project has suddenly grown in size, but has become much more flexible.
18616@cite{Mode_Type} defines the only valid values for the @cite{mode} variable. If
18617any other value is read from the environment, an error is reported and the
18618project is considered as invalid.
18619
18620The @cite{Mode} variable is initialized with an external value
18621defaulting to @cite{"debug"}. This default could be omitted and that would
18622force the user to define the value. Finally, we can use a case construction to set the
18623switches depending on the scenario the user has chosen.
18624
18625Most aspects of the projects can depend on scenarios. The notable exception
18626are project dependencies (@emph{with} clauses), which cannot depend on a scenario.
18627
18628Scenarios work the same way with @strong{project hierarchies}: you can either
18629duplicate a variable similar to @cite{Mode} in each of the project (as long
18630as the first argument to @cite{external} is always the same and the type is
18631the same), or simply set the variable in the @code{shared.gpr} project
18632(see @ref{174,,Sharing Between Projects}).
18633
18634@node Library Projects,Project Extension,Scenarios in Projects,GNAT Project Manager
18635@anchor{gnat_ugn/gnat_project_manager library-projects}@anchor{8a}@anchor{gnat_ugn/gnat_project_manager id20}@anchor{17a}
18636@section Library Projects
18637
18638
18639So far, we have seen examples of projects that create executables. However,
18640it is also possible to create libraries instead. A @strong{library} is a specific
18641type of subsystem where, for convenience, objects are grouped together
18642using system-specific means such as archives or windows DLLs.
18643
18644Library projects provide a system- and language-independent way of building
18645both @strong{static} and @strong{dynamic} libraries. They also support the concept of
18646@strong{standalone libraries} (SAL) which offer two significant properties: the
18647elaboration (e.g. initialization) of the library is either automatic or
18648very simple; a change in the
18649implementation part of the library implies minimal post-compilation actions on
18650the complete system and potentially no action at all for the rest of the
18651system in the case of dynamic SALs.
18652
18653There is a restriction on shared library projects: by default, they are only
18654allowed to import other shared library projects. They are not allowed to
18655import non library projects or static library projects.
18656
18657The GNAT Project Manager takes complete care of the library build, rebuild and
18658installation tasks, including recompilation of the source files for which
18659objects do not exist or are not up to date, assembly of the library archive, and
18660installation of the library (i.e., copying associated source, object and
18661@code{ALI} files to the specified location).
18662
18663@menu
18664* Building Libraries::
18665* Using Library Projects::
18666* Stand-alone Library Projects::
18667* Installing a library with project files::
18668
18669@end menu
18670
18671@node Building Libraries,Using Library Projects,,Library Projects
18672@anchor{gnat_ugn/gnat_project_manager id21}@anchor{17b}@anchor{gnat_ugn/gnat_project_manager building-libraries}@anchor{17c}
18673@subsection Building Libraries
18674
18675
18676Let's enhance our example and transform the @cite{logging} subsystem into a
18677library.  In order to do so, a few changes need to be made to
18678@code{logging.gpr}.  Some attributes need to be defined: at least
18679@cite{Library_Name} and @cite{Library_Dir}; in addition, some other attributes
18680can be used to specify specific aspects of the library. For readability, it is
18681also recommended (although not mandatory), to use the qualifier @cite{library}
18682in front of the @cite{project} keyword.
18683
18684@geindex Library_Name (GNAT Project Manager)
18685
18686@strong{Library_Name}:
18687
18688@quotation
18689
18690This attribute is the name of the library to be built. There is no
18691restriction on the name of a library imposed by the project manager, except
18692for stand-alone libraries whose names must follow the syntax of Ada
18693identifiers; however, there may be system-specific restrictions on the name.
18694In general, it is recommended to stick to alphanumeric characters (and
18695possibly single underscores) to help portability.
18696@end quotation
18697
18698@geindex Library_Dir (GNAT Project Manager)
18699
18700@strong{Library_Dir}:
18701
18702@quotation
18703
18704This attribute  is the path (absolute or relative) of the directory where
18705the library is to be installed. In the process of building a library,
18706the sources are compiled, the object files end up  in the explicit or
18707implicit @cite{Object_Dir} directory. When all sources of a library
18708are compiled, some of the compilation artifacts, including the library itself,
18709are copied to the library_dir directory. This directory must exist and be
18710writable. It must also be different from the object directory so that cleanup
18711activities in the Library_Dir do not affect recompilation needs.
18712@end quotation
18713
18714Here is the new version of @code{logging.gpr} that makes it a library:
18715
18716@example
18717library project Logging is          --  "library" is optional
18718   for Library_Name use "logging";  --  will create "liblogging.a" on Unix
18719   for Object_Dir   use "obj";
18720   for Library_Dir  use "lib";      --  different from object_dir
18721end Logging;
18722@end example
18723
18724Once the above two attributes are defined, the library project is valid and
18725is enough for building a library with default characteristics.
18726Other library-related attributes can be used to change the defaults:
18727
18728@geindex Library_Kind (GNAT Project Manager)
18729
18730@strong{Library_Kind}:
18731
18732@quotation
18733
18734The value of this attribute must be either @cite{"static"}, @cite{"dynamic"} or
18735@cite{"relocatable"} (the latter is a synonym for dynamic). It indicates
18736which kind of library should be built (the default is to build a
18737static library, that is an archive of object files that can potentially
18738be linked into a static executable). When the library is set to be dynamic,
18739a separate image is created that will be loaded independently, usually
18740at the start of the main program execution. Support for dynamic libraries is
18741very platform specific, for instance on Windows it takes the form of a DLL
18742while on GNU/Linux, it is a dynamic elf image whose suffix is usually
18743@code{.so}. Library project files, on the other hand, can be written in
18744a platform independent way so that the same project file can be used to build
18745a library on different operating systems.
18746
18747If you need to build both a static and a dynamic library, it is recommended
18748to use two different object directories, since in some cases some extra code
18749needs to be generated for the latter. For such cases, one can either define
18750two different project files, or a single one that uses scenarios to indicate
18751the various kinds of library to be built and their corresponding object_dir.
18752@end quotation
18753
18754@geindex Library_ALI_Dir (GNAT Project Manager)
18755
18756@strong{Library_ALI_Dir}:
18757
18758@quotation
18759
18760This attribute may be specified to indicate the directory where the ALI
18761files of the library are installed. By default, they are copied into the
18762@cite{Library_Dir} directory, but as for the executables where we have a
18763separate @cite{Exec_Dir} attribute, you might want to put them in a separate
18764directory since there can be hundreds of them. The same restrictions as for
18765the @cite{Library_Dir} attribute apply.
18766@end quotation
18767
18768@geindex Library_Version (GNAT Project Manager)
18769
18770@strong{Library_Version}:
18771
18772@quotation
18773
18774This attribute is platform dependent, and has no effect on Windows.
18775On Unix, it is used only for dynamic libraries as the internal
18776name of the library (the @cite{"soname"}). If the library file name (built
18777from the @cite{Library_Name}) is different from the @cite{Library_Version},
18778then the library file will be a symbolic link to the actual file whose name
18779will be @cite{Library_Version}. This follows the usual installation schemes
18780for dynamic libraries on many Unix systems.
18781
18782@example
18783project Logging is
18784   Version := "1";
18785   for Library_Dir use "lib";
18786   for Library_Name use "logging";
18787   for Library_Kind use "dynamic";
18788   for Library_Version use "liblogging.so." & Version;
18789end Logging;
18790@end example
18791
18792After the compilation, the directory @code{lib} will contain both a
18793@code{libdummy.so.1} library and a symbolic link to it called
18794@code{libdummy.so}.
18795@end quotation
18796
18797@geindex Library_GCC (GNAT Project Manager)
18798
18799@strong{Library_GCC}:
18800
18801@quotation
18802
18803This attribute is the name of the tool to use instead of "gcc" to link shared
18804libraries. A common use of this attribute is to define a wrapper script that
18805accomplishes specific actions before calling gcc (which itself calls the
18806linker to build the library image).
18807@end quotation
18808
18809@geindex Library_Options (GNAT Project Manager)
18810
18811@strong{Library_Options}:
18812
18813@quotation
18814
18815This attribute may be used to specify additional switches (last switches)
18816when linking a shared library.
18817
18818It may also be used to add foreign object files to a static library.
18819Each string in Library_Options is an absolute or relative path of an object
18820file. When a relative path, it is relative to the object directory.
18821@end quotation
18822
18823@geindex Leading_Library_Options (GNAT Project Manager)
18824
18825@strong{Leading_Library_Options}:
18826
18827@quotation
18828
18829This attribute, that is taken into account only by @emph{gprbuild}, may be
18830used to specified leading options (first switches) when linking a shared
18831library.
18832@end quotation
18833
18834@geindex Linker_Options (GNAT Project Manager)
18835
18836@strong{Linker.Linker_Options}:
18837
18838@quotation
18839
18840This attribute specifies additional switches to be given to the linker when
18841linking an executable. It is ignored when defined in the main project and
18842taken into account in all other projects that are imported directly or
18843indirectly. These switches complement the @cite{Linker.Switches}
18844defined in the main project. This is useful when a particular subsystem
18845depends on an external library: adding this dependency as a
18846@cite{Linker_Options} in the project of the subsystem is more convenient than
18847adding it to all the @cite{Linker.Switches} of the main projects that depend
18848upon this subsystem.
18849@end quotation
18850
18851@node Using Library Projects,Stand-alone Library Projects,Building Libraries,Library Projects
18852@anchor{gnat_ugn/gnat_project_manager id22}@anchor{17d}@anchor{gnat_ugn/gnat_project_manager using-library-projects}@anchor{17e}
18853@subsection Using Library Projects
18854
18855
18856When the builder detects that a project file is a library project file, it
18857recompiles all sources of the project that need recompilation and rebuild the
18858library if any of the sources have been recompiled. It then groups all object
18859files into a single file, which is a shared or a static library. This library
18860can later on be linked with multiple executables. Note that the use
18861of shard libraries reduces the size of the final executable and can also reduce
18862the memory footprint at execution time when the library is shared among several
18863executables.
18864
18865@emph{gprbuild also allows to build **multi-language libraries*} when specifying
18866sources from multiple languages.
18867
18868A non-library project can import a library project. When the builder is invoked
18869on the former, the library of the latter is only rebuilt when absolutely
18870necessary. For instance, if a unit of the library is not up-to-date but none of
18871the executables need this unit, then the unit is not recompiled and the library
18872is not reassembled.  For instance, let's assume in our example that logging has
18873the following sources: @code{log1.ads}, @code{log1.adb}, @code{log2.ads} and
18874@code{log2.adb}. If @code{log1.adb} has been modified, then the library
18875@code{liblogging} will be rebuilt when compiling all the sources of
18876@cite{Build} only if @code{proc.ads}, @code{pack.ads} or @code{pack.adb}
18877include a @cite{"with Log1"}.
18878
18879To ensure that all the sources in the @cite{Logging} library are
18880up to date, and that all the sources of @cite{Build} are also up to date,
18881the following two commands need to be used:
18882
18883@example
18884gprbuild -Plogging.gpr
18885gprbuild -Pbuild.gpr
18886@end example
18887
18888All @code{ALI} files will also be copied from the object directory to the
18889library directory. To build executables, @emph{gprbuild} will use the
18890library rather than the individual object files.
18891
18892Library projects can also be useful to describe a library that needs to be used
18893but, for some reason, cannot be rebuilt. For instance, it is the case when some
18894of the library sources are not available. Such library projects need to use the
18895@cite{Externally_Built} attribute as in the example below:
18896
18897@example
18898library project Extern_Lib is
18899   for Languages    use ("Ada", "C");
18900   for Source_Dirs  use ("lib_src");
18901   for Library_Dir  use "lib2";
18902   for Library_Kind use "dynamic";
18903   for Library_Name use "l2";
18904   for Externally_Built use "true";  --  <<<<
18905end Extern_Lib;
18906@end example
18907
18908In the case of externally built libraries, the @cite{Object_Dir}
18909attribute does not need to be specified because it will never be
18910used.
18911
18912The main effect of using such an externally built library project is mostly to
18913affect the linker command in order to reference the desired library. It can
18914also be achieved by using @cite{Linker.Linker_Options} or @cite{Linker.Switches}
18915in the project corresponding to the subsystem needing this external library.
18916This latter method is more straightforward in simple cases but when several
18917subsystems depend upon the same external library, finding the proper place
18918for the @cite{Linker.Linker_Options} might not be easy and if it is
18919not placed properly, the final link command is likely to present ordering issues.
18920In such a situation, it is better to use the externally built library project
18921so that all other subsystems depending on it can declare this dependency thanks
18922to a project @emph{with} clause, which in turn will trigger the builder to find
18923the proper order of libraries in the final link command.
18924
18925@node Stand-alone Library Projects,Installing a library with project files,Using Library Projects,Library Projects
18926@anchor{gnat_ugn/gnat_project_manager id23}@anchor{17f}@anchor{gnat_ugn/gnat_project_manager stand-alone-library-projects}@anchor{97}
18927@subsection Stand-alone Library Projects
18928
18929
18930@geindex standalone libraries (usage with GNAT Project Manager)
18931
18932A @strong{stand-alone library} is a library that contains the necessary code to
18933elaborate the Ada units that are included in the library. A stand-alone
18934library is a convenient way to add an Ada subsystem to a more global system
18935whose main is not in Ada since it makes the elaboration of the Ada part mostly
18936transparent. However, stand-alone libraries are also useful when the main is in
18937Ada: they provide a means for minimizing relinking & redeployment of complex
18938systems when localized changes are made.
18939
18940The name of a stand-alone library, specified with attribute
18941@cite{Library_Name}, must have the syntax of an Ada identifier.
18942
18943The most prominent characteristic of a stand-alone library is that it offers a
18944distinction between interface units and implementation units. Only the former
18945are visible to units outside the library. A stand-alone library project is thus
18946characterised by a third attribute, usually @strong{Library_Interface}, in addition
18947to the two attributes that make a project a Library Project
18948(@cite{Library_Name} and @cite{Library_Dir}). This third attribute may also be
18949@strong{Interfaces}. @strong{Library_Interface} only works when the interface is in Ada
18950and takes a list of units as parameter. @strong{Interfaces} works for any supported
18951language and takes a list of sources as parameter.
18952
18953@geindex Library_Interface (GNAT Project Manager)
18954
18955@strong{Library_Interface}:
18956
18957@quotation
18958
18959This attribute defines an explicit subset of the units of the project. Units
18960from projects importing this library project may only "with" units whose
18961sources are listed in the @cite{Library_Interface}. Other sources are
18962considered implementation units.
18963
18964@example
18965for Library_Dir use "lib";
18966for Library_Name use "logging";
18967for Library_Interface use ("lib1", "lib2");  --  unit names
18968@end example
18969@end quotation
18970
18971@strong{Interfaces}
18972
18973@quotation
18974
18975This attribute defines an explicit subset of the source files of a project.
18976Sources from projects importing this project, can only depend on sources from
18977this subset. This attribute can be used on non library projects. It can also
18978be used as a replacement for attribute @cite{Library_Interface}, in which
18979case, units have to be replaced by source files. For multi-language library
18980projects, it is the only way to make the project a Stand-Alone Library project
18981whose interface is not purely Ada.
18982@end quotation
18983
18984@geindex Library_Standalone (GNAT Project Manager)
18985
18986@strong{Library_Standalone}:
18987
18988@quotation
18989
18990This attribute defines the kind of standalone library to
18991build. Values are either @cite{standard} (the default), @cite{no} or
18992@cite{encapsulated}. When @cite{standard} is used the code to elaborate and
18993finalize the library is embedded, when @cite{encapsulated} is used the
18994library can furthermore depend only on static libraries (including
18995the GNAT runtime). This attribute can be set to @cite{no} to make it clear
18996that the library should not be standalone in which case the
18997@cite{Library_Interface} should not defined. Note that this attribute
18998only applies to shared libraries, so @cite{Library_Kind} must be set
18999to @cite{dynamic}.
19000
19001@example
19002for Library_Dir use "lib";
19003for Library_Name use "logging";
19004for Library_Kind use "dynamic";
19005for Library_Interface use ("lib1", "lib2");  --  unit names
19006for Library_Standalone use "encapsulated";
19007@end example
19008@end quotation
19009
19010In order to include the elaboration code in the stand-alone library, the binder
19011is invoked on the closure of the library units creating a package whose name
19012depends on the library name (b~logging.ads/b in the example).
19013This binder-generated package includes @strong{initialization} and @strong{finalization}
19014procedures whose names depend on the library name (@cite{logginginit} and
19015@cite{loggingfinal} in the example). The object corresponding to this package is
19016included in the library.
19017
19018@geindex Library_Auto_Init (GNAT Project Manager)
19019
19020@strong{Library_Auto_Init}:
19021
19022@quotation
19023
19024A dynamic stand-alone Library is automatically initialized
19025if automatic initialization of Stand-alone Libraries is supported on the
19026platform and if attribute @strong{Library_Auto_Init} is not specified or
19027is specified with the value "true". A static Stand-alone Library is never
19028automatically initialized. Specifying "false" for this attribute
19029prevents automatic initialization.
19030
19031When a non-automatically initialized stand-alone library is used in an
19032executable, its initialization procedure must be called before any service of
19033the library is used. When the main subprogram is in Ada, it may mean that the
19034initialization procedure has to be called during elaboration of another
19035package.
19036@end quotation
19037
19038@geindex Library_Dir (GNAT Project Manager)
19039
19040@strong{Library_Dir}:
19041
19042@quotation
19043
19044For a stand-alone library, only the @code{ALI} files of the interface units
19045(those that are listed in attribute @cite{Library_Interface}) are copied to
19046the library directory. As a consequence, only the interface units may be
19047imported from Ada units outside of the library. If other units are imported,
19048the binding phase will fail.
19049@end quotation
19050
19051@strong{Binder.Default_Switches}:
19052
19053@quotation
19054
19055When a stand-alone library is bound, the switches that are specified in
19056the attribute @strong{Binder.Default_Switches ("Ada")} are
19057used in the call to @emph{gnatbind}.
19058@end quotation
19059
19060@geindex Library_Src_Dir (GNAT Project Manager)
19061
19062@strong{Library_Src_Dir}:
19063
19064@quotation
19065
19066This attribute defines the location (absolute or relative to the project
19067directory) where the sources of the interface units are copied at
19068installation time.
19069These sources includes the specs of the interface units along with the
19070closure of sources necessary to compile them successfully. That may include
19071bodies and subunits, when pragmas @cite{Inline} are used, or when there are
19072generic units in specs. This directory cannot point to the object directory
19073or one of the source directories, but it can point to the library directory,
19074which is the default value for this attribute.
19075@end quotation
19076
19077@geindex Library_Symbol_Policy (GNAT Project Manager)
19078
19079@strong{Library_Symbol_Policy}:
19080
19081@quotation
19082
19083This attribute controls the export of symbols and, on some platforms (like
19084VMS) that have the notions of major and minor IDs built in the library
19085files, it controls the setting of these IDs. It is not supported on all
19086platforms (where it will just have no effect). It may have one of the
19087following values:
19088
19089
19090@itemize *
19091
19092@item
19093@cite{"autonomous"} or @cite{"default"}: exported symbols are not controlled
19094
19095@item
19096@cite{"compliant"}: if attribute @strong{Library_Reference_Symbol_File}
19097is not defined, then it is equivalent to policy "autonomous". If there
19098are exported symbols in the reference symbol file that are not in the
19099object files of the interfaces, the major ID of the library is increased.
19100If there are symbols in the object files of the interfaces that are not
19101in the reference symbol file, these symbols are put at the end of the list
19102in the newly created symbol file and the minor ID is increased.
19103
19104@item
19105@cite{"controlled"}: the attribute @strong{Library_Reference_Symbol_File} must be
19106defined. The library will fail to build if the exported symbols in the
19107object files of the interfaces do not match exactly the symbol in the
19108symbol file.
19109
19110@item
19111@cite{"restricted"}: The attribute @strong{Library_Symbol_File} must be defined.
19112The library will fail to build if there are symbols in the symbol file that
19113are not in the exported symbols of the object files of the interfaces.
19114Additional symbols in the object files are not added to the symbol file.
19115
19116@item
19117@cite{"direct"}: The attribute @strong{Library_Symbol_File} must be defined and
19118must designate an existing file in the object directory. This symbol file
19119is passed directly to the underlying linker without any symbol processing.
19120@end itemize
19121@end quotation
19122
19123@geindex Library_Reference_Symbol_File (GNAT Project Manager)
19124
19125@strong{Library_Reference_Symbol_File}
19126
19127@quotation
19128
19129This attribute may define the path name of a reference symbol file that is
19130read when the symbol policy is either "compliant" or "controlled", on
19131platforms that support symbol control, such as VMS, when building a
19132stand-alone library. The path may be an absolute path or a path relative
19133to the project directory.
19134@end quotation
19135
19136@geindex Library_Symbol_File (GNAT Project Manager)
19137
19138@strong{Library_Symbol_File}
19139
19140@quotation
19141
19142This attribute may define the name of the symbol file to be created when
19143building a stand-alone library when the symbol policy is either "compliant",
19144"controlled" or "restricted", on platforms that support symbol control,
19145such as VMS. When symbol policy is "direct", then a file with this name
19146must exist in the object directory.
19147@end quotation
19148
19149@node Installing a library with project files,,Stand-alone Library Projects,Library Projects
19150@anchor{gnat_ugn/gnat_project_manager installing-a-library-with-project-files}@anchor{8d}@anchor{gnat_ugn/gnat_project_manager id24}@anchor{180}
19151@subsection Installing a library with project files
19152
19153
19154When using project files, a usable version of the library is created in the
19155directory specified by the @cite{Library_Dir} attribute of the library
19156project file. Thus no further action is needed in order to make use of
19157the libraries that are built as part of the general application build.
19158
19159You may want to install a library in a context different from where the library
19160is built. This situation arises with third party suppliers, who may want
19161to distribute a library in binary form where the user is not expected to be
19162able to recompile the library. The simplest option in this case is to provide
19163a project file slightly different from the one used to build the library, by
19164using the @cite{externally_built} attribute. See @ref{17e,,Using Library Projects}
19165
19166Another option is to use @emph{gprinstall} to install the library in a
19167different context than the build location. @emph{gprinstall} automatically
19168generates a project to use this library, and also copies the minimum set of
19169sources needed to use the library to the install location.
19170@ref{16b,,Installation}
19171
19172@node Project Extension,Aggregate Projects,Library Projects,GNAT Project Manager
19173@anchor{gnat_ugn/gnat_project_manager id25}@anchor{181}@anchor{gnat_ugn/gnat_project_manager project-extension}@anchor{152}
19174@section Project Extension
19175
19176
19177During development of a large system, it is sometimes necessary to use
19178modified versions of some of the source files, without changing the original
19179sources. This can be achieved through the @strong{project extension} facility.
19180
19181Suppose for instance that our example @cite{Build} project is built every night
19182for the whole team, in some shared directory. A developer usually needs to work
19183on a small part of the system, and might not want to have a copy of all the
19184sources and all the object files (mostly because that would require too much
19185disk space, time to recompile everything). He prefers to be able to override
19186some of the source files in his directory, while taking advantage of all the
19187object files generated at night.
19188
19189Another example can be taken from large software systems, where it is common to have
19190multiple implementations of a common interface; in Ada terms, multiple
19191versions of a package body for the same spec.  For example, one implementation
19192might be safe for use in tasking programs, while another might be used only
19193in sequential applications.  This can be modeled in GNAT using the concept
19194of @emph{project extension}.  If one project (the 'child') @emph{extends}
19195another project (the 'parent') then by default all source files of the
19196parent project are inherited by the child, but the child project can
19197override any of the parent's source files with new versions, and can also
19198add new files or remove unnecessary ones.
19199This facility is the project analog of a type extension in
19200object-oriented programming.  Project hierarchies are permitted (an extending
19201project may itself be extended), and a project that
19202extends a project can also import other projects.
19203
19204A third example is that of using project extensions to provide different
19205versions of the same system. For instance, assume that a @cite{Common}
19206project is used by two development branches. One of the branches has now
19207been frozen, and no further change can be done to it or to @cite{Common}.
19208However, the other development branch still needs evolution of @cite{Common}.
19209Project extensions provide a flexible solution to create a new version
19210of a subsystem while sharing and reusing as much as possible from the original
19211one.
19212
19213A project extension implicitly inherits all the sources and objects from the
19214project it extends. It is possible to create a new version of some of the
19215sources in one of the additional source directories of the extending
19216project. Those new versions hide the original versions. Adding new sources or
19217removing existing ones is also possible. Here is an example on how to extend
19218the project @cite{Build} from previous examples:
19219
19220@example
19221project Work extends "../bld/build.gpr" is
19222end Work;
19223@end example
19224
19225The project after @strong{extends} is the one being extended. As usual, it can be
19226specified using an absolute path, or a path relative to any of the directories
19227in the project path (see @ref{16f,,Project Dependencies}). This project does not
19228specify source or object directories, so the default values for these
19229attributes will be used that is to say the current directory (where project
19230@cite{Work} is placed). We can compile that project with
19231
19232@example
19233gprbuild -Pwork
19234@end example
19235
19236If no sources have been placed in the current directory, this command
19237won't do anything, since this project does not change the
19238sources it inherited from @cite{Build}, therefore all the object files
19239in @cite{Build} and its dependencies are still valid and are reused
19240automatically.
19241
19242Suppose we now want to supply an alternate version of @code{pack.adb} but use
19243the existing versions of @code{pack.ads} and @code{proc.adb}.  We can create
19244the new file in Work's current directory (likely by copying the one from the
19245@cite{Build} project and making changes to it. If new packages are needed at
19246the same time, we simply create new files in the source directory of the
19247extending project.
19248
19249When we recompile, @emph{gprbuild} will now automatically recompile
19250this file (thus creating @code{pack.o} in the current directory) and
19251any file that depends on it (thus creating @code{proc.o}). Finally, the
19252executable is also linked locally.
19253
19254Note that we could have obtained the desired behavior using project import
19255rather than project inheritance. A @cite{base} project would contain the
19256sources for @code{pack.ads} and @code{proc.adb}, and @cite{Work} would
19257import @cite{base} and add @code{pack.adb}. In this scenario,  @cite{base}
19258cannot contain the original version of @code{pack.adb} otherwise there would be
192592 versions of the same unit in the closure of the project and this is not
19260allowed. Generally speaking, it is not recommended to put the spec and the
19261body of a unit in different projects since this affects their autonomy and
19262reusability.
19263
19264In a project file that extends another project, it is possible to
19265indicate that an inherited source is @strong{not part} of the sources of the
19266extending project. This is necessary sometimes when a package spec has
19267been overridden and no longer requires a body: in this case, it is
19268necessary to indicate that the inherited body is not part of the sources
19269of the project, otherwise there will be a compilation error
19270when compiling the spec.
19271
19272@geindex Excluded_Source_Files (GNAT Project Manager)
19273
19274@geindex Excluded_Source_List_File (GNAT Project Manager)
19275
19276For that purpose, the attribute @strong{Excluded_Source_Files} is used.
19277Its value is a list of file names.
19278It is also possible to use attribute @cite{Excluded_Source_List_File}.
19279Its value is the path of a text file containing one file name per
19280line.
19281
19282@example
19283project Work extends "../bld/build.gpr" is
19284   for Source_Files use ("pack.ads");
19285   --  New spec of Pkg does not need a completion
19286   for Excluded_Source_Files use ("pack.adb");
19287end Work;
19288@end example
19289
19290All packages that are not declared in the extending project are inherited from
19291the project being extended, with their attributes, with the exception of
19292@cite{Linker'Linker_Options} which is never inherited. In particular, an
19293extending project retains all the switches specified in the project being
19294extended.
19295
19296At the project level, if they are not declared in the extending project, some
19297attributes are inherited from the project being extended. They are:
19298@cite{Languages}, @cite{Main} (for a root non library project) and
19299@cite{Library_Name} (for a project extending a library project).
19300
19301@menu
19302* Project Hierarchy Extension::
19303
19304@end menu
19305
19306@node Project Hierarchy Extension,,,Project Extension
19307@anchor{gnat_ugn/gnat_project_manager project-hierarchy-extension}@anchor{182}@anchor{gnat_ugn/gnat_project_manager id26}@anchor{183}
19308@subsection Project Hierarchy Extension
19309
19310
19311One of the fundamental restrictions in project extension is the following:
19312@strong{A project is not allowed to import directly or indirectly at the same time an extending project and one of its ancestors}.
19313
19314For example, consider the following hierarchy of projects.
19315
19316@example
19317a.gpr  contains package A1
19318b.gpr, imports a.gpr and contains B1, which depends on A1
19319c.gpr, imports b.gpr and contains C1, which depends on B1
19320@end example
19321
19322If we want to locally extend the packages @cite{A1} and @cite{C1}, we need to
19323create several extending projects:
19324
19325@example
19326a_ext.gpr which extends a.gpr, and overrides A1
19327b_ext.gpr which extends b.gpr and imports a_ext.gpr
19328c_ext.gpr which extends c.gpr, imports b_ext.gpr and overrides C1
19329@end example
19330
19331@example
19332project A_Ext extends "a.gpr" is
19333   for Source_Files use ("a1.adb", "a1.ads");
19334end A_Ext;
19335
19336with "a_ext.gpr";
19337project B_Ext extends "b.gpr" is
19338end B_Ext;
19339
19340with "b_ext.gpr";
19341project C_Ext extends "c.gpr" is
19342   for Source_Files use ("c1.adb");
19343end C_Ext;
19344@end example
19345
19346The extension @code{b_ext.gpr} is required, even though we are not overriding
19347any of the sources of @code{b.gpr} because otherwise @code{c_expr.gpr} would
19348import @code{b.gpr} which itself knows nothing about @code{a_ext.gpr}.
19349
19350@geindex extends all (GNAT Project Manager)
19351
19352When extending a large system spanning multiple projects, it is often
19353inconvenient to extend every project in the hierarchy that is impacted by a
19354small change introduced in a low layer. In such cases, it is possible to create
19355an @strong{implicit extension} of an entire hierarchy using @strong{extends all}
19356relationship.
19357
19358When the project is extended using @cite{extends all} inheritance, all projects
19359that are imported by it, both directly and indirectly, are considered virtually
19360extended. That is, the project manager creates implicit projects
19361that extend every project in the hierarchy; all these implicit projects do not
19362control sources on their own and use the object directory of
19363the "extending all" project.
19364
19365It is possible to explicitly extend one or more projects in the hierarchy
19366in order to modify the sources. These extending projects must be imported by
19367the "extending all" project, which will replace the corresponding virtual
19368projects with the explicit ones.
19369
19370When building such a project hierarchy extension, the project manager will
19371ensure that both modified sources and sources in implicit extending projects
19372that depend on them are recompiled.
19373
19374Thus, in our example we could create the following projects instead:
19375
19376@example
19377a_ext.gpr, extends a.gpr and overrides A1
19378c_ext.gpr, "extends all" c.gpr, imports a_ext.gpr and overrides C1
19379@end example
19380
19381@example
19382project A_Ext extends "a.gpr" is
19383   for Source_Files use ("a1.adb", "a1.ads");
19384end A_Ext;
19385
19386with "a_ext.gpr";
19387project C_Ext extends all "c.gpr" is
19388  for Source_Files use ("c1.adb");
19389end C_Ext;
19390@end example
19391
19392When building project @code{c_ext.gpr}, the entire modified project space is
19393considered for recompilation, including the sources of @code{b.gpr} that are
19394impacted by the changes in @cite{A1} and @cite{C1}.
19395
19396@node Aggregate Projects,Aggregate Library Projects,Project Extension,GNAT Project Manager
19397@anchor{gnat_ugn/gnat_project_manager aggregate-projects}@anchor{171}@anchor{gnat_ugn/gnat_project_manager id27}@anchor{184}
19398@section Aggregate Projects
19399
19400
19401Aggregate projects are an extension of the project paradigm, and are
19402meant to solve a few specific use cases that cannot be solved directly
19403using standard projects. This section will go over a few of these use
19404cases to try to explain what you can use aggregate projects for.
19405
19406@menu
19407* Building all main programs from a single project tree::
19408* Building a set of projects with a single command::
19409* Define a build environment::
19410* Performance improvements in builder::
19411* Syntax of aggregate projects::
19412* package Builder in aggregate projects::
19413
19414@end menu
19415
19416@node Building all main programs from a single project tree,Building a set of projects with a single command,,Aggregate Projects
19417@anchor{gnat_ugn/gnat_project_manager id28}@anchor{185}@anchor{gnat_ugn/gnat_project_manager building-all-main-programs-from-a-single-project-tree}@anchor{186}
19418@subsection Building all main programs from a single project tree
19419
19420
19421Most often, an application is organized into modules and submodules,
19422which are very conveniently represented as a project tree or graph
19423(the root project A @emph{with}s the projects for each modules (say B and C),
19424which in turn @emph{with} projects for submodules.
19425
19426Very often, modules will build their own executables (for testing
19427purposes for instance), or libraries (for easier reuse in various
19428contexts).
19429
19430However, if you build your project through @emph{gprbuild}, using a syntax similar to
19431
19432@example
19433gprbuild -PA.gpr
19434@end example
19435
19436this will only rebuild the main programs of project A, not those of the
19437imported projects B and C. Therefore you have to spawn several
19438@emph{gprbuild} commands, one per project, to build all executables.
19439This is a little inconvenient, but more importantly is inefficient
19440because @emph{gprbuild} needs to do duplicate work to ensure that sources are
19441up-to-date, and cannot easily compile things in parallel when using
19442the -j switch.
19443
19444Also libraries are always rebuilt when building a project.
19445
19446You could therefore define an aggregate project Agg that groups A, B
19447and C. Then, when you build with
19448
19449@example
19450gprbuild -PAgg.gpr
19451@end example
19452
19453this will build all mains from A, B and C.
19454
19455@example
19456aggregate project Agg is
19457   for Project_Files use ("a.gpr", "b.gpr", "c.gpr");
19458end Agg;
19459@end example
19460
19461If B or C do not define any main program (through their Main
19462attribute), all their sources are built. When you do not group them
19463in the aggregate project, only those sources that are needed by A
19464will be built.
19465
19466If you add a main to a project P not already explicitly referenced in the
19467aggregate project, you will need to add "p.gpr" in the list of project
19468files for the aggregate project, or the main will not be built when
19469building the aggregate project.
19470
19471@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
19472@anchor{gnat_ugn/gnat_project_manager building-a-set-of-projects-with-a-single-command}@anchor{187}@anchor{gnat_ugn/gnat_project_manager id29}@anchor{188}
19473@subsection Building a set of projects with a single command
19474
19475
19476One other case is when you have multiple applications and libraries
19477that are built independently from each other (but can be built in
19478parallel). For instance, you have a project tree rooted at A, and
19479another one (which might share some subprojects) rooted at B.
19480
19481Using only @emph{gprbuild}, you could do
19482
19483@example
19484gprbuild -PA.gpr
19485gprbuild -PB.gpr
19486@end example
19487
19488to build both. But again, @emph{gprbuild} has to do some duplicate work for
19489those files that are shared between the two, and cannot truly build
19490things in parallel efficiently.
19491
19492If the two projects are really independent, share no sources other
19493than through a common subproject, and have no source files with a
19494common basename, you could create a project C that imports A and
19495B. But these restrictions are often too strong, and one has to build
19496them independently. An aggregate project does not have these
19497limitations and can aggregate two project trees that have common
19498sources.
19499
19500This scenario is particularly useful in environments like VxWorks 653
19501where the applications running in the multiple partitions can be built
19502in parallel through a single @emph{gprbuild} command. This also works nicely
19503with Annex E.
19504
19505@node Define a build environment,Performance improvements in builder,Building a set of projects with a single command,Aggregate Projects
19506@anchor{gnat_ugn/gnat_project_manager id30}@anchor{189}@anchor{gnat_ugn/gnat_project_manager define-a-build-environment}@anchor{18a}
19507@subsection Define a build environment
19508
19509
19510The environment variables at the time you launch @emph{gprbuild}
19511will influence the view these tools have of the project
19512(PATH to find the compiler, ADA_PROJECT_PATH or GPR_PROJECT_PATH to find the
19513projects, environment variables that are referenced in project files
19514through the "external" built-in function, ...). Several command line switches
19515can be used to override those (-X or -aP), but on some systems and
19516with some projects, this might make the command line too long, and on
19517all systems often make it hard to read.
19518
19519An aggregate project can be used to set the environment for all
19520projects built through that aggregate. One of the nice aspects is that
19521you can put the aggregate project under configuration management, and
19522make sure all your user have a consistent environment when
19523building. The syntax looks like
19524
19525@example
19526aggregate project Agg is
19527   for Project_Files use ("A.gpr", "B.gpr");
19528   for Project_Path use ("../dir1", "../dir1/dir2");
19529   for External ("BUILD") use "PRODUCTION";
19530
19531   package Builder is
19532      for Global_Compilation_Switches ("Ada") use ("-g");
19533   end Builder;
19534end Agg;
19535@end example
19536
19537One of the often requested features in projects is to be able to
19538reference external variables in @emph{with} declarations, as in
19539
19540@example
19541with external("SETUP") & "path/prj.gpr";   --  ILLEGAL
19542project MyProject is
19543   ...
19544end MyProject;
19545@end example
19546
19547For various reasons, this is not allowed. But using aggregate projects provide
19548an elegant solution. For instance, you could use a project file like:
19549
19550@example
19551aggregate project Agg is
19552    for Project_Path use (external("SETUP") & "path");
19553    for Project_Files use ("myproject.gpr");
19554end Agg;
19555
19556with "prj.gpr";  --  searched on Agg'Project_Path
19557project MyProject is
19558   ...
19559end MyProject;
19560@end example
19561
19562@node Performance improvements in builder,Syntax of aggregate projects,Define a build environment,Aggregate Projects
19563@anchor{gnat_ugn/gnat_project_manager performance-improvements-in-builder}@anchor{18b}@anchor{gnat_ugn/gnat_project_manager id31}@anchor{18c}
19564@subsection Performance improvements in builder
19565
19566
19567The loading of aggregate projects is optimized in @emph{gprbuild},
19568so that all files are searched for only once on the disk
19569(thus reducing the number of system calls and contributing to faster
19570compilation times, especially on systems with sources on remote
19571servers). As part of the loading, @emph{gprbuild}
19572computes how and where a source file should be compiled, and even if it is
19573found several times in the aggregated projects it will be compiled only
19574once.
19575
19576Since there is no ambiguity as to which switches should be used, files
19577can be compiled in parallel (through the usual -j switch) and this can
19578be done while maximizing the use of CPUs (compared to launching
19579multiple @emph{gprbuild} commands in parallel).
19580
19581@node Syntax of aggregate projects,package Builder in aggregate projects,Performance improvements in builder,Aggregate Projects
19582@anchor{gnat_ugn/gnat_project_manager id32}@anchor{18d}@anchor{gnat_ugn/gnat_project_manager syntax-of-aggregate-projects}@anchor{18e}
19583@subsection Syntax of aggregate projects
19584
19585
19586An aggregate project follows the general syntax of project files. The
19587recommended extension is still @code{.gpr}. However, a special
19588@cite{aggregate} qualifier must be put before the keyword
19589@cite{project}.
19590
19591An aggregate project cannot @emph{with} any other project (standard or
19592aggregate), except an abstract project which can be used to share attribute
19593values. Also, aggregate projects cannot be extended or imported though a
19594@emph{with} clause by any other project. Building other aggregate projects from
19595an aggregate project is done through the Project_Files attribute (see below).
19596
19597An aggregate project does not have any source files directly (only
19598through other standard projects). Therefore a number of the standard
19599attributes and packages are forbidden in an aggregate project. Here is the
19600(non exhaustive) list:
19601
19602
19603@itemize *
19604
19605@item
19606Languages
19607
19608@item
19609Source_Files, Source_List_File and other attributes dealing with
19610list of sources.
19611
19612@item
19613Source_Dirs, Exec_Dir and Object_Dir
19614
19615@item
19616Library_Dir, Library_Name and other library-related attributes
19617
19618@item
19619Main
19620
19621@item
19622Roots
19623
19624@item
19625Externally_Built
19626
19627@item
19628Inherit_Source_Path
19629
19630@item
19631Excluded_Source_Dirs
19632
19633@item
19634Locally_Removed_Files
19635
19636@item
19637Excluded_Source_Files
19638
19639@item
19640Excluded_Source_List_File
19641
19642@item
19643Interfaces
19644@end itemize
19645
19646The only package that is authorized (albeit optional) is
19647Builder. Other packages (in particular Compiler, Binder and Linker)
19648are forbidden.
19649
19650The following three attributes can be used only in an aggregate project:
19651
19652@geindex Project_Files (GNAT Project Manager)
19653
19654@strong{Project_Files}:
19655
19656@quotation
19657
19658This attribute is compulsory (or else we are not aggregating any project,
19659and thus not doing anything). It specifies a list of @code{.gpr} files
19660that are grouped in the aggregate. The list may be empty. The project
19661files can be either other aggregate projects, or standard projects. When
19662grouping standard projects, you can have both the root of a project tree
19663(and you do not need to specify all its imported projects), and any project
19664within the tree.
19665
19666Basically, the idea is to specify all those projects that have
19667main programs you want to build and link, or libraries you want to
19668build. You can even specify projects that do not use the Main
19669attribute nor the @cite{Library_*} attributes, and the result will be to
19670build all their source files (not just the ones needed by other
19671projects).
19672
19673The file can include paths (absolute or relative). Paths are relative to
19674the location of the aggregate project file itself (if you use a base name,
19675we expect to find the .gpr file in the same directory as the aggregate
19676project file). The environment variables @cite{ADA_PROJECT_PATH},
19677@cite{GPR_PROJECT_PATH} and @cite{GPR_PROJECT_PATH_FILE} are not used to find
19678the project files. The extension @code{.gpr} is mandatory, since this attribute
19679contains file names, not project names.
19680
19681Paths can also include the @cite{"*"} and @cite{"**"} globbing patterns. The
19682latter indicates that any subdirectory (recursively) will be
19683searched for matching files. The latter (@cite{"**"}) can only occur at the
19684last position in the directory part (ie @cite{"a/**/*.gpr"} is supported, but
19685not @cite{"**/a/*.gpr"}). Starting the pattern with @cite{"**"} is equivalent
19686to starting with @cite{"./**"}.
19687
19688For now, the pattern @cite{"*"} is only allowed in the filename part, not
19689in the directory part. This is mostly for efficiency reasons to limit the
19690number of system calls that are needed.
19691
19692Here are a few valid examples:
19693
19694@example
19695for Project_Files use ("a.gpr", "subdir/b.gpr");
19696--  two specific projects relative to the directory of agg.gpr
19697
19698for Project_Files use ("/.gpr");
19699--  all projects recursively
19700@end example
19701@end quotation
19702
19703@geindex Project_Path (GNAT Project Manager)
19704
19705@strong{Project_Path}:
19706
19707@quotation
19708
19709This attribute can be used to specify a list of directories in
19710which to look for project files in @emph{with} declarations.
19711
19712When you specify a project in Project_Files (say @cite{x/y/a.gpr}), and
19713@cite{a.gpr} imports a project @cite{b.gpr}, only @cite{b.gpr} is searched in
19714the project path. @cite{a.gpr} must be exactly at
19715@cite{<dir of the aggregate>/x/y/a.gpr}.
19716
19717This attribute, however, does not affect the search for the aggregated
19718project files specified with @cite{Project_Files}.
19719
19720Each aggregate project has its own @cite{Project_Path} (that is if
19721@cite{agg1.gpr} includes @cite{agg2.gpr}, they can potentially both have a
19722different @cite{Project_Path}).
19723
19724This project path is defined as the concatenation, in that order, of:
19725
19726
19727@itemize *
19728
19729@item
19730the current directory;
19731
19732@item
19733followed by the command line -aP switches;
19734
19735@item
19736then the directories from the GPR_PROJECT_PATH and ADA_PROJECT_PATH environment
19737variables;
19738
19739@item
19740then the directories from the Project_Path attribute;
19741
19742@item
19743and finally the predefined directories.
19744@end itemize
19745
19746In the example above, agg2.gpr's project path is not influenced by
19747the attribute agg1'Project_Path, nor is agg1 influenced by
19748agg2'Project_Path.
19749
19750This can potentially lead to errors. Consider the following example:
19751
19752@example
19753--
19754--  +---------------+                  +----------------+
19755--  | Agg1.gpr      |-=--includes--=-->| Agg2.gpr       |
19756--  |  'project_path|                  |  'project_path |
19757--  |               |                  |                |
19758--  +---------------+                  +----------------+
19759--        :                                   :
19760--        includes                        includes
19761--        :                                   :
19762--        v                                   v
19763--    +-------+                          +---------+
19764--    | P.gpr |<---------- withs --------|  Q.gpr  |
19765--    +-------+---------\                +---------+
19766--        |             |
19767--        withs         |
19768--        |             |
19769--        v             v
19770--    +-------+      +---------+
19771--    | R.gpr |      | R'.gpr  |
19772--    +-------+      +---------+
19773@end example
19774
19775When looking for p.gpr, both aggregates find the same physical file on
19776the disk. However, it might happen that with their different project
19777paths, both aggregate projects would in fact find a different r.gpr.
19778Since we have a common project (p.gpr) "with"ing two different r.gpr,
19779this will be reported as an error by the builder.
19780
19781Directories are relative to the location of the aggregate project file.
19782
19783Example:
19784
19785@example
19786for Project_Path use ("/usr/local/gpr", "gpr/");
19787@end example
19788@end quotation
19789
19790@geindex External (GNAT Project Manager)
19791
19792@strong{External}:
19793
19794@quotation
19795
19796This attribute can be used to set the value of environment
19797variables as retrieved through the @cite{external} function
19798in projects. It does not affect the environment variables
19799themselves (so for instance you cannot use it to change the value
19800of your PATH as seen from the spawned compiler).
19801
19802This attribute affects the external values as seen in the rest of
19803the aggregate project, and in the aggregated projects.
19804
19805The exact value of external a variable comes from one of three
19806sources (each level overrides the previous levels):
19807
19808
19809@itemize *
19810
19811@item
19812An External attribute in aggregate project, for instance
19813@cite{for External ("BUILD_MODE") use "DEBUG"};
19814
19815@item
19816Environment variables.
19817These override the value given by the attribute, so that
19818users can override the value set in the (presumably shared
19819with others team members) aggregate project.
19820
19821@item
19822The -X command line switch to @emph{gprbuild}.
19823This always takes precedence.
19824@end itemize
19825
19826This attribute is only taken into account in the main aggregate
19827project (i.e. the one specified on the command line to @emph{gprbuild}),
19828and ignored in other aggregate projects. It is invalid
19829in standard projects.
19830The goal is to have a consistent value in all
19831projects that are built through the aggregate, which would not
19832be the case in the diamond case: A groups the aggregate
19833projects B and C, which both (either directly or indirectly)
19834build the project P. If B and C could set different values for
19835the environment variables, we would have two different views of
19836P, which in particular might impact the list of source files in P.
19837@end quotation
19838
19839@node package Builder in aggregate projects,,Syntax of aggregate projects,Aggregate Projects
19840@anchor{gnat_ugn/gnat_project_manager package-builder-in-aggregate-projects}@anchor{18f}@anchor{gnat_ugn/gnat_project_manager id33}@anchor{190}
19841@subsection package Builder in aggregate projects
19842
19843
19844As mentioned above, only the package Builder can be specified in
19845an aggregate project. In this package, only the following attributes
19846are valid:
19847
19848@geindex Switches (GNAT Project Manager)
19849
19850@strong{Switches}:
19851
19852@quotation
19853
19854This attribute gives the list of switches to use for @emph{gprbuild}.
19855Because no mains can be specified for aggregate projects, the only possible
19856index for attribute @cite{Switches} is @cite{others}. All other indexes will
19857be ignored.
19858
19859Example:
19860
19861@example
19862for Switches (others) use ("-v", "-k", "-j8");
19863@end example
19864
19865These switches are only read from the main aggregate project (the
19866one passed on the command line), and ignored in all other aggregate
19867projects or projects.
19868
19869It can only contain builder switches, not compiler switches.
19870@end quotation
19871
19872@geindex Global_Compilation_Switches (GNAT Project Manager)
19873
19874@strong{Global_Compilation_Switches}
19875
19876@quotation
19877
19878This attribute gives the list of compiler switches for the various
19879languages. For instance,
19880
19881@example
19882for Global_Compilation_Switches ("Ada") use ("O1", "-g");
19883for Global_Compilation_Switches ("C")   use ("-O2");
19884@end example
19885
19886This attribute is only taken into account in the aggregate project
19887specified on the command line, not in other aggregate projects.
19888
19889In the projects grouped by that aggregate, the attribute
19890Builder.Global_Compilation_Switches is also ignored. However, the
19891attribute Compiler.Default_Switches will be taken into account (but
19892that of the aggregate have higher priority). The attribute
19893Compiler.Switches is also taken into account and can be used to
19894override the switches for a specific file. As a result, it always
19895has priority.
19896
19897The rules are meant to avoid ambiguities when compiling. For
19898instance, aggregate project Agg groups the projects A and B, that
19899both depend on C. Here is an extra for all of these projects:
19900
19901@example
19902aggregate project Agg is
19903    for Project_Files use ("a.gpr", "b.gpr");
19904    package Builder is
19905       for Global_Compilation_Switches ("Ada") use ("-O2");
19906    end Builder;
19907end Agg;
19908
19909with "c.gpr";
19910project A is
19911    package Builder is
19912       for Global_Compilation_Switches ("Ada") use ("-O1");
19913       --  ignored
19914    end Builder;
19915
19916    package Compiler is
19917       for Default_Switches ("Ada")
19918           use ("-O1", "-g");
19919       for Switches ("a_file1.adb")
19920           use ("-O0");
19921    end Compiler;
19922end A;
19923
19924with "c.gpr";
19925project B is
19926    package Compiler is
19927       for Default_Switches ("Ada") use ("-O0");
19928    end Compiler;
19929end B;
19930
19931project C is
19932    package Compiler is
19933       for Default_Switches ("Ada")
19934           use ("-O3",
19935                "-gnatn");
19936       for Switches ("c_file1.adb")
19937           use ("-O0", "-g");
19938    end Compiler;
19939end C;
19940@end example
19941
19942then the following switches are used:
19943
19944
19945@itemize *
19946
19947@item
19948all files from project A except a_file1.adb are compiled
19949with "-O2 -g", since the aggregate project has priority.
19950
19951@item
19952the file a_file1.adb is compiled with
19953"-O0", since the Compiler.Switches has priority
19954
19955@item
19956all files from project B are compiled with
19957"-O2", since the aggregate project has priority
19958
19959@item
19960all files from C are compiled with "-O2 -gnatn", except for
19961c_file1.adb which is compiled with "-O0 -g"
19962@end itemize
19963
19964Even though C is seen through two paths (through A and through
19965B), the switches used by the compiler are unambiguous.
19966@end quotation
19967
19968@geindex Global_Configuration_Pragmas (GNAT Project Manager)
19969
19970@strong{Global_Configuration_Pragmas}
19971
19972@quotation
19973
19974This attribute can be used to specify a file containing
19975configuration pragmas, to be passed to the Ada compiler.  Since we
19976ignore the package Builder in other aggregate projects and projects,
19977only those pragmas defined in the main aggregate project will be
19978taken into account.
19979
19980Projects can locally add to those by using the
19981@cite{Compiler.Local_Configuration_Pragmas} attribute if they need.
19982@end quotation
19983
19984@geindex Global_Config_File (GNAT Project Manager)
19985
19986@strong{Global_Config_File}
19987
19988@quotation
19989
19990This attribute, indexed with a language name, can be used to specify a config
19991when compiling sources of the language. For Ada, these files are configuration
19992pragmas files.
19993@end quotation
19994
19995For projects that are built through the aggregate, the package Builder
19996is ignored, except for the Executable attribute which specifies the
19997name of the executables resulting from the link of the main programs, and
19998for the Executable_Suffix.
19999
20000@node Aggregate Library Projects,Project File Reference,Aggregate Projects,GNAT Project Manager
20001@anchor{gnat_ugn/gnat_project_manager id34}@anchor{191}@anchor{gnat_ugn/gnat_project_manager aggregate-library-projects}@anchor{192}
20002@section Aggregate Library Projects
20003
20004
20005Aggregate library projects make it possible to build a single library
20006using object files built using other standard or library
20007projects. This gives the flexibility to describe an application as
20008having multiple modules (a GUI, database access, ...) using different
20009project files (so possibly built with different compiler options) and
20010yet create a single library (static or relocatable) out of the
20011corresponding object files.
20012
20013@menu
20014* Building aggregate library projects::
20015* Syntax of aggregate library projects::
20016
20017@end menu
20018
20019@node Building aggregate library projects,Syntax of aggregate library projects,,Aggregate Library Projects
20020@anchor{gnat_ugn/gnat_project_manager building-aggregate-library-projects}@anchor{193}@anchor{gnat_ugn/gnat_project_manager id35}@anchor{194}
20021@subsection Building aggregate library projects
20022
20023
20024For example, we can define an aggregate project Agg that groups A, B
20025and C:
20026
20027@example
20028aggregate library project Agg is
20029   for Project_Files use ("a.gpr", "b.gpr", "c.gpr");
20030   for Library_Name use ("agg");
20031   for Library_Dir use ("lagg");
20032end Agg;
20033@end example
20034
20035Then, when you build with:
20036
20037@example
20038gprbuild agg.gpr
20039@end example
20040
20041This will build all units from projects A, B and C and will create a
20042static library named @code{libagg.a} in the @code{lagg}
20043directory. An aggregate library project has the same set of
20044restriction as a standard library project.
20045
20046Note that a shared aggregate library project cannot aggregate a
20047static library project. In platforms where a compiler option is
20048required to create relocatable object files, a Builder package in the
20049aggregate library project may be used:
20050
20051@example
20052aggregate library project Agg is
20053   for Project_Files use ("a.gpr", "b.gpr", "c.gpr");
20054   for Library_Name use ("agg");
20055   for Library_Dir use ("lagg");
20056   for Library_Kind use "relocatable";
20057
20058   package Builder is
20059      for Global_Compilation_Switches ("Ada") use ("-fPIC");
20060   end Builder;
20061end Agg;
20062@end example
20063
20064With the above aggregate library Builder package, the @cite{-fPIC}
20065option will be passed to the compiler when building any source code
20066from projects @code{a.gpr}, @code{b.gpr} and @code{c.gpr}.
20067
20068@node Syntax of aggregate library projects,,Building aggregate library projects,Aggregate Library Projects
20069@anchor{gnat_ugn/gnat_project_manager syntax-of-aggregate-library-projects}@anchor{195}@anchor{gnat_ugn/gnat_project_manager id36}@anchor{196}
20070@subsection Syntax of aggregate library projects
20071
20072
20073An aggregate library project follows the general syntax of project
20074files. The recommended extension is still @code{.gpr}. However, a special
20075@cite{aggregate library} qualifier must be put before the keyword
20076@cite{project}.
20077
20078An aggregate library project cannot @emph{with} any other project
20079(standard or aggregate), except an abstract project which can be used
20080to share attribute values.
20081
20082An aggregate library project does not have any source files directly (only
20083through other standard projects). Therefore a number of the standard
20084attributes and packages are forbidden in an aggregate library
20085project. Here is the (non exhaustive) list:
20086
20087
20088@itemize *
20089
20090@item
20091Languages
20092
20093@item
20094Source_Files, Source_List_File and other attributes dealing with
20095list of sources.
20096
20097@item
20098Source_Dirs, Exec_Dir and Object_Dir
20099
20100@item
20101Main
20102
20103@item
20104Roots
20105
20106@item
20107Externally_Built
20108
20109@item
20110Inherit_Source_Path
20111
20112@item
20113Excluded_Source_Dirs
20114
20115@item
20116Locally_Removed_Files
20117
20118@item
20119Excluded_Source_Files
20120
20121@item
20122Excluded_Source_List_File
20123
20124@item
20125Interfaces
20126@end itemize
20127
20128The only package that is authorized (albeit optional) is Builder.
20129
20130The Project_Files attribute (See @ref{171,,Aggregate Projects}) is used to
20131described the aggregated projects whose object files have to be
20132included into the aggregate library. The environment variables
20133@cite{ADA_PROJECT_PATH}, @cite{GPR_PROJECT_PATH} and
20134@cite{GPR_PROJECT_PATH_FILE} are not used to find the project files.
20135
20136@node Project File Reference,,Aggregate Library Projects,GNAT Project Manager
20137@anchor{gnat_ugn/gnat_project_manager id37}@anchor{197}@anchor{gnat_ugn/gnat_project_manager project-file-reference}@anchor{150}
20138@section Project File Reference
20139
20140
20141This section describes the syntactic structure of project files, the various
20142constructs that can be used. Finally, it ends with a summary of all available
20143attributes.
20144
20145@menu
20146* Project Declaration::
20147* Qualified Projects::
20148* Declarations::
20149* Packages::
20150* Expressions::
20151* External Values::
20152* Typed String Declaration::
20153* Variables::
20154* Case Constructions::
20155* Attributes::
20156
20157@end menu
20158
20159@node Project Declaration,Qualified Projects,,Project File Reference
20160@anchor{gnat_ugn/gnat_project_manager id38}@anchor{198}@anchor{gnat_ugn/gnat_project_manager project-declaration}@anchor{199}
20161@subsection Project Declaration
20162
20163
20164Project files have an Ada-like syntax. The minimal project file is:
20165
20166@example
20167project Empty is
20168end Empty;
20169@end example
20170
20171The identifier @cite{Empty} is the name of the project.
20172This project name must be present after the reserved
20173word @cite{end} at the end of the project file, followed by a semi-colon.
20174
20175@strong{Identifiers} (i.e., the user-defined names such as project or variable names)
20176have the same syntax as Ada identifiers: they must start with a letter,
20177and be followed by zero or more letters, digits or underscore characters;
20178it is also illegal to have two underscores next to each other. Identifiers
20179are always case-insensitive ("Name" is the same as "name").
20180
20181@example
20182simple_name ::= identifier
20183name        ::= simple_name @{ . simple_name @}
20184@end example
20185
20186@strong{Strings} are used for values of attributes or as indexes for these
20187attributes. They are in general case sensitive, except when noted
20188otherwise (in particular, strings representing file names will be case
20189insensitive on some systems, so that "file.adb" and "File.adb" both
20190represent the same file).
20191
20192@strong{Reserved words} are the same as for standard Ada 95, and cannot
20193be used for identifiers. In particular, the following words are currently
20194used in project files, but others could be added later on. In bold are the
20195extra reserved words in project files:
20196@code{all}, @code{at}, @code{case}, @code{end}, @code{for}, @code{is}, @code{limited},
20197@code{null}, @code{others}, @code{package}, @code{renames}, @code{type}, @code{use}, @code{when},
20198@code{with}, @strong{extends}, @strong{external}, @strong{project}.
20199
20200@strong{Comments} in project files have the same syntax as in Ada, two consecutive
20201hyphens through the end of the line.
20202
20203A project may be an @strong{independent project}, entirely defined by a single
20204project file. Any source file in an independent project depends only
20205on the predefined library and other source files in the same project.
20206But a project may also depend on other projects, either by importing them
20207through @strong{with clauses}, or by @strong{extending} at most one other project. Both
20208types of dependency can be used in the same project.
20209
20210A path name denotes a project file. It can be absolute or relative.
20211An absolute path name includes a sequence of directories, in the syntax of
20212the host operating system, that identifies uniquely the project file in the
20213file system. A relative path name identifies the project file, relative
20214to the directory that contains the current project, or relative to a
20215directory listed in the environment variables ADA_PROJECT_PATH and
20216GPR_PROJECT_PATH. Path names are case sensitive if file names in the host
20217operating system are case sensitive. As a special case, the directory
20218separator can always be "/" even on Windows systems, so that project files
20219can be made portable across architectures.
20220The syntax of the environment variables ADA_PROJECT_PATH and
20221GPR_PROJECT_PATH is a list of directory names separated by colons on UNIX and
20222semicolons on Windows.
20223
20224A given project name can appear only once in a context clause.
20225
20226It is illegal for a project imported by a context clause to refer, directly
20227or indirectly, to the project in which this context clause appears (the
20228dependency graph cannot contain cycles), except when one of the with clauses
20229in the cycle is a @strong{limited with}.
20230
20231@example
20232with "other_project.gpr";
20233project My_Project extends "extended.gpr" is
20234end My_Project;
20235@end example
20236
20237These dependencies form a @strong{directed graph}, potentially cyclic when using
20238@strong{limited with}. The subgraph reflecting the @strong{extends} relations is a tree.
20239
20240A project's @strong{immediate sources} are the source files directly defined by
20241that project, either implicitly by residing in the project source directories,
20242or explicitly through any of the source-related attributes.
20243More generally, a project's @strong{sources} are the immediate sources of the
20244project together with the immediate sources (unless overridden) of any project
20245on which it depends directly or indirectly.
20246
20247A @strong{project hierarchy} can be created, where projects are children of
20248other projects. The name of such a child project must be @cite{Parent.Child},
20249where @cite{Parent} is the name of the parent project. In particular, this
20250makes all @emph{with} clauses of the parent project automatically visible
20251in the child project.
20252
20253@example
20254project        ::= context_clause project_declaration
20255
20256context_clause ::= @{with_clause@}
20257with_clause    ::= *with* path_name @{ , path_name @} ;
20258path_name      ::= string_literal
20259
20260project_declaration ::= simple_project_declaration | project_extension
20261simple_project_declaration ::=
20262  project <project_>name is
20263    @{declarative_item@}
20264  end <project_>simple_name;
20265@end example
20266
20267@node Qualified Projects,Declarations,Project Declaration,Project File Reference
20268@anchor{gnat_ugn/gnat_project_manager qualified-projects}@anchor{176}@anchor{gnat_ugn/gnat_project_manager id39}@anchor{19a}
20269@subsection Qualified Projects
20270
20271
20272Before the reserved @cite{project}, there may be one or two @strong{qualifiers}, that
20273is identifiers or reserved words, to qualify the project.
20274The current list of qualifiers is:
20275
20276
20277@table @asis
20278
20279@item @strong{abstract}:
20280
20281Qualifies a project with no sources.
20282Such a   project must either have no declaration of attributes @cite{Source_Dirs},
20283@cite{Source_Files}, @cite{Languages} or @cite{Source_List_File}, or one of
20284@cite{Source_Dirs}, @cite{Source_Files}, or @cite{Languages} must be declared
20285as empty. If it extends another project, the project it extends must also be a
20286qualified abstract project.
20287
20288@item @strong{standard}:
20289
20290A standard project is a non library project with sources.
20291This is the default (implicit) qualifier.
20292
20293@item @strong{aggregate}:
20294
20295A project whose sources are aggregated from other project files.
20296
20297@item @strong{aggregate library}:
20298
20299A library whose sources are aggregated from other project
20300or library project files.
20301
20302@item @strong{library}:
20303
20304A library project must declare both attributes
20305Library_Name` and @cite{Library_Dir}.
20306
20307@item @strong{configuration}:
20308
20309A configuration project cannot be in a project tree.
20310It describes compilers and other tools to @emph{gprbuild}.
20311@end table
20312
20313@node Declarations,Packages,Qualified Projects,Project File Reference
20314@anchor{gnat_ugn/gnat_project_manager declarations}@anchor{19b}@anchor{gnat_ugn/gnat_project_manager id40}@anchor{19c}
20315@subsection Declarations
20316
20317
20318Declarations introduce new entities that denote types, variables, attributes,
20319and packages. Some declarations can only appear immediately within a project
20320declaration. Others can appear within a project or within a package.
20321
20322@example
20323declarative_item ::= simple_declarative_item
20324  | typed_string_declaration
20325  | package_declaration
20326
20327simple_declarative_item ::= variable_declaration
20328  | typed_variable_declaration
20329  | attribute_declaration
20330  | case_construction
20331  | empty_declaration
20332
20333empty_declaration ::= *null* ;
20334@end example
20335
20336An empty declaration is allowed anywhere a declaration is allowed. It has
20337no effect.
20338
20339@node Packages,Expressions,Declarations,Project File Reference
20340@anchor{gnat_ugn/gnat_project_manager packages}@anchor{156}@anchor{gnat_ugn/gnat_project_manager id41}@anchor{19d}
20341@subsection Packages
20342
20343
20344A project file may contain @strong{packages}, that group attributes (typically
20345all the attributes that are used by one of the GNAT tools).
20346
20347A package with a given name may only appear once in a project file.
20348The following packages are currently supported in project files
20349(See @ref{155,,Attributes} for the list of attributes that each can contain).
20350
20351
20352@table @asis
20353
20354@item @emph{Binder}
20355
20356This package specifies characteristics useful when invoking the binder either
20357directly via the @emph{gnat} driver or when using @emph{gprbuild}.
20358See @ref{160,,Main Subprograms}.
20359
20360@item @emph{Builder}
20361
20362This package specifies the compilation options used when building an
20363executable or a library for a project. Most of the options should be
20364set in one of @cite{Compiler}, @cite{Binder} or @cite{Linker} packages,
20365but there are some general options that should be defined in this
20366package. See @ref{160,,Main Subprograms}, and @ref{165,,Executable File Names} in
20367particular.
20368@end table
20369
20370
20371
20372@table @asis
20373
20374@item @emph{Clean}
20375
20376This package specifies the options used when cleaning a project or a project
20377tree using the tools @emph{gnatclean} or @emph{gprclean}.
20378
20379@item @emph{Compiler}
20380
20381This package specifies the compilation options used by the compiler for
20382each languages. See @ref{161,,Tools Options in Project Files}.
20383
20384@item @emph{Cross_Reference}
20385
20386This package specifies the options used when calling the library tool
20387@emph{gnatxref} via the @emph{gnat} driver. Its attributes
20388@strong{Default_Switches} and @strong{Switches} have the same semantics as for the
20389package @cite{Builder}.
20390@end table
20391
20392
20393
20394@table @asis
20395
20396@item @emph{Finder}
20397
20398This package specifies the options used when calling the search tool
20399@emph{gnatfind} via the @emph{gnat} driver. Its attributes
20400@strong{Default_Switches} and @strong{Switches} have the same semantics as for the
20401package @cite{Builder}.
20402
20403@item @emph{Gnatls}
20404
20405This package specifies the options to use when invoking @emph{gnatls}
20406via the @emph{gnat} driver.
20407@end table
20408
20409
20410
20411@table @asis
20412
20413@item @emph{IDE}
20414
20415This package specifies the options used when starting an integrated
20416development environment, for instance @emph{GPS} or @emph{Gnatbench}.
20417
20418@item @emph{Install}
20419
20420This package specifies the options used when installing a project
20421with @emph{gprinstall}. See @ref{16b,,Installation}.
20422
20423@item @emph{Linker}
20424
20425This package specifies the options used by the linker.
20426See @ref{160,,Main Subprograms}.
20427@end table
20428
20429
20430
20431@table @asis
20432
20433@item @emph{Naming}
20434
20435@quotation
20436
20437This package specifies the naming conventions that apply
20438to the source files in a project. In particular, these conventions are
20439used to automatically find all source files in the source directories,
20440or given a file name to find out its language for proper processing.
20441See @ref{14e,,Naming Schemes}.
20442@end quotation
20443
20444
20445@item @emph{Remote}
20446
20447This package is used by @emph{gprbuild} to describe how distributed
20448compilation should be done.
20449
20450@item @emph{Stack}
20451
20452This package specifies the options used when calling the tool
20453@emph{gnatstack} via the @emph{gnat} driver. Its attributes
20454@strong{Default_Switches} and @strong{Switches} have the same semantics as for the
20455package @cite{Builder}.
20456
20457@item @emph{Synchronize}
20458
20459This package specifies the options used when calling the tool
20460@emph{gnatsync} via the @emph{gnat} driver.
20461@end table
20462
20463In its simplest form, a package may be empty:
20464
20465@example
20466project Simple is
20467  package Builder is
20468  end Builder;
20469end Simple;
20470@end example
20471
20472A package may contain @strong{attribute declarations},
20473@strong{variable declarations} and @strong{case constructions}, as will be
20474described below.
20475
20476When there is ambiguity between a project name and a package name,
20477the name always designates the project. To avoid possible confusion, it is
20478always a good idea to avoid naming a project with one of the
20479names allowed for packages or any name that starts with @cite{gnat}.
20480
20481A package can also be defined by a @strong{renaming declaration}. The new package
20482renames a package declared in a different project file, and has the same
20483attributes as the package it renames. The name of the renamed package
20484must be the same as the name of the renaming package. The project must
20485contain a package declaration with this name, and the project
20486must appear in the context clause of the current project, or be its parent
20487project. It is not possible to add or override attributes to the renaming
20488project. If you need to do so, you should use an @strong{extending declaration}
20489(see below).
20490
20491Packages that are renamed in other project files often come from project files
20492that have no sources: they are just used as templates. Any modification in the
20493template will be reflected automatically in all the project files that rename
20494a package from the template. This is a very common way to share settings
20495between projects.
20496
20497Finally, a package can also be defined by an @strong{extending declaration}. This is
20498similar to a @strong{renaming declaration}, except that it is possible to add or
20499override attributes.
20500
20501@example
20502package_declaration ::= package_spec | package_renaming | package_extension
20503package_spec ::=
20504  package <package_>simple_name is
20505    @{simple_declarative_item@}
20506  end package_identifier ;
20507package_renaming ::==
20508  package <package_>simple_name renames <project_>simple_name.package_identifier ;
20509package_extension ::==
20510  package <package_>simple_name extends <project_>simple_name.package_identifier is
20511    @{simple_declarative_item@}
20512  end package_identifier ;
20513@end example
20514
20515@node Expressions,External Values,Packages,Project File Reference
20516@anchor{gnat_ugn/gnat_project_manager expressions}@anchor{19e}@anchor{gnat_ugn/gnat_project_manager id42}@anchor{19f}
20517@subsection Expressions
20518
20519
20520An expression is any value that can be assigned to an attribute or a
20521variable. It is either a literal value, or a construct requiring runtime
20522computation by the project manager. In a project file, the computed value of
20523an expression is either a string or a list of strings.
20524
20525A string value is one of:
20526
20527
20528@itemize *
20529
20530@item
20531A literal string, for instance @cite{"comm/my_proj.gpr"}
20532
20533@item
20534The name of a variable that evaluates to a string (see @ref{158,,Variables})
20535
20536@item
20537The name of an attribute that evaluates to a string (see @ref{155,,Attributes})
20538
20539@item
20540An external reference (see @ref{157,,External Values})
20541
20542@item
20543A concatenation of the above, as in @cite{"prefix_" & Var}.
20544@end itemize
20545
20546A list of strings is one of the following:
20547
20548
20549@itemize *
20550
20551@item
20552A parenthesized comma-separated list of zero or more string expressions, for
20553instance @cite{(File_Name@comma{} "gnat.adc"@comma{} File_Name & ".orig")} or @cite{()}.
20554
20555@item
20556The name of a variable that evaluates to a list of strings
20557
20558@item
20559The name of an attribute that evaluates to a list of strings
20560
20561@item
20562A concatenation of a list of strings and a string (as defined above), for
20563instance @cite{("A"@comma{} "B") & "C"}
20564
20565@item
20566A concatenation of two lists of strings
20567@end itemize
20568
20569The following is the grammar for expressions
20570
20571@example
20572string_literal ::= "@{string_element@}"  --  Same as Ada
20573string_expression ::= string_literal
20574    | *variable_*name
20575    | external_value
20576    | attribute_reference
20577    | ( string_expression @{ & string_expression @} )
20578string_list  ::= ( string_expression @{ , string_expression @} )
20579   | *string_variable*_name
20580   | *string_*attribute_reference
20581term ::= string_expression | string_list
20582expression ::= term @{ & term @}     --  Concatenation
20583@end example
20584
20585Concatenation involves strings and list of strings. As soon as a list of
20586strings is involved, the result of the concatenation is a list of strings. The
20587following Ada declarations show the existing operators:
20588
20589@example
20590function "&" (X : String;      Y : String)      return String;
20591function "&" (X : String_List; Y : String)      return String_List;
20592function "&" (X : String_List; Y : String_List) return String_List;
20593@end example
20594
20595Here are some specific examples:
20596
20597@example
20598List := () & File_Name; --  One string in this list
20599List2 := List & (File_Name & ".orig"); -- Two strings
20600Big_List := List & Lists2;  --  Three strings
20601Illegal := "gnat.adc" & List2;  --  Illegal, must start with list
20602@end example
20603
20604@node External Values,Typed String Declaration,Expressions,Project File Reference
20605@anchor{gnat_ugn/gnat_project_manager external-values}@anchor{157}@anchor{gnat_ugn/gnat_project_manager id43}@anchor{1a0}
20606@subsection External Values
20607
20608
20609An external value is an expression whose value is obtained from the command
20610that invoked the processing of the current project file (typically a
20611@emph{gprbuild} command).
20612
20613There are two kinds of external values, one that returns a single string, and
20614one that returns a string list.
20615
20616The syntax of a single string external value is:
20617
20618@example
20619external_value ::= *external* ( string_literal [, string_literal] )
20620@end example
20621
20622The first string_literal is the string to be used on the command line or
20623in the environment to specify the external value. The second string_literal,
20624if present, is the default to use if there is no specification for this
20625external value either on the command line or in the environment.
20626
20627Typically, the external value will either exist in the
20628environment variables
20629or be specified on the command line through the
20630@code{-X@emph{vbl}=@emph{value}} switch. If both
20631are specified, then the command line value is used, so that a user can more
20632easily override the value.
20633
20634The function @cite{external} always returns a string. It is an error if the
20635value was not found in the environment and no default was specified in the
20636call to @cite{external}.
20637
20638An external reference may be part of a string expression or of a string
20639list expression, and can therefore appear in a variable declaration or
20640an attribute declaration.
20641
20642Most of the time, this construct is used to initialize typed variables, which
20643are then used in @strong{case} constructions to control the value assigned to
20644attributes in various scenarios. Thus such variables are often called
20645@strong{scenario variables}.
20646
20647The syntax for a string list external value is:
20648
20649@example
20650external_value ::= *external_as_list* ( string_literal , string_literal )
20651@end example
20652
20653The first string_literal is the string to be used on the command line or
20654in the environment to specify the external value. The second string_literal is
20655the separator between each component of the string list.
20656
20657If the external value does not exist in the environment or on the command line,
20658the result is an empty list. This is also the case, if the separator is an
20659empty string or if the external value is only one separator.
20660
20661Any separator at the beginning or at the end of the external value is
20662discarded. Then, if there is no separator in the external value, the result is
20663a string list with only one string. Otherwise, any string between the beginning
20664and the first separator, between two consecutive separators and between the
20665last separator and the end are components of the string list.
20666
20667@example
20668*external_as_list* ("SWITCHES", ",")
20669@end example
20670
20671If the external value is "-O2,-g",
20672the result is ("-O2", "-g").
20673
20674If the external value is ",-O2,-g,",
20675the result is also ("-O2", "-g").
20676
20677if the external value is "-gnatv",
20678the result is ("-gnatv").
20679
20680If the external value is ",,", the result is ("").
20681
20682If the external value is ",", the result is (), the empty string list.
20683
20684@node Typed String Declaration,Variables,External Values,Project File Reference
20685@anchor{gnat_ugn/gnat_project_manager id44}@anchor{1a1}@anchor{gnat_ugn/gnat_project_manager typed-string-declaration}@anchor{1a2}
20686@subsection Typed String Declaration
20687
20688
20689A @strong{type declaration} introduces a discrete set of string literals.
20690If a string variable is declared to have this type, its value
20691is restricted to the given set of literals. These are the only named
20692types in project files. A string type may only be declared at the project
20693level, not inside a package.
20694
20695@example
20696typed_string_declaration ::=
20697  *type* *<typed_string_>*_simple_name *is* ( string_literal @{, string_literal@} );
20698@end example
20699
20700The string literals in the list are case sensitive and must all be different.
20701They may include any graphic characters allowed in Ada, including spaces.
20702Here is an example of a string type declaration:
20703
20704@example
20705type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
20706@end example
20707
20708Variables of a string type are called @strong{typed variables}; all other
20709variables are called @strong{untyped variables}. Typed variables are
20710particularly useful in @cite{case} constructions, to support conditional
20711attribute declarations. (See @ref{1a3,,Case Constructions}).
20712
20713A string type may be referenced by its name if it has been declared in the same
20714project file, or by an expanded name whose prefix is the name of the project
20715in which it is declared.
20716
20717@node Variables,Case Constructions,Typed String Declaration,Project File Reference
20718@anchor{gnat_ugn/gnat_project_manager variables}@anchor{158}@anchor{gnat_ugn/gnat_project_manager id45}@anchor{1a4}
20719@subsection Variables
20720
20721
20722@strong{Variables} store values (strings or list of strings) and can appear
20723as part of an expression. The declaration of a variable creates the
20724variable and assigns the value of the expression to it. The name of the
20725variable is available immediately after the assignment symbol, if you
20726need to reuse its old value to compute the new value. Before the completion
20727of its first declaration, the value of a variable defaults to the empty
20728string ("").
20729
20730A @strong{typed} variable can be used as part of a @strong{case} expression to
20731compute the value, but it can only be declared once in the project file,
20732so that all case constructions see the same value for the variable. This
20733provides more consistency and makes the project easier to understand.
20734The syntax for its declaration is identical to the Ada syntax for an
20735object declaration. In effect, a typed variable acts as a constant.
20736
20737An @strong{untyped} variable can be declared and overridden multiple times
20738within the same project. It is declared implicitly through an Ada
20739assignment. The first declaration establishes the kind of the variable
20740(string or list of strings) and successive declarations must respect
20741the initial kind. Assignments are executed in the order in which they
20742appear, so the new value replaces the old one and any subsequent reference
20743to the variable uses the new value.
20744
20745A variable may be declared at the project file level, or within a package.
20746
20747@example
20748typed_variable_declaration ::=
20749  *<typed_variable_>*simple_name : *<typed_string_>*name := string_expression;
20750
20751variable_declaration ::= *<variable_>*simple_name := expression;
20752@end example
20753
20754Here are some examples of variable declarations:
20755
20756@example
20757This_OS : OS := external ("OS"); --  a typed variable declaration
20758That_OS := "GNU/Linux";          --  an untyped variable declaration
20759
20760Name      := "readme.txt";
20761Save_Name := Name & ".saved";
20762
20763Empty_List := ();
20764List_With_One_Element := ("-gnaty");
20765List_With_Two_Elements := List_With_One_Element & "-gnatg";
20766Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada");
20767@end example
20768
20769A @strong{variable reference} may take several forms:
20770
20771
20772@itemize *
20773
20774@item
20775The simple variable name, for a variable in the current package (if any)
20776or in the current project
20777
20778@item
20779An expanded name, whose prefix is a context name.
20780@end itemize
20781
20782A @strong{context} may be one of the following:
20783
20784
20785@itemize *
20786
20787@item
20788The name of an existing package in the current project
20789
20790@item
20791The name of an imported project of the current project
20792
20793@item
20794The name of an ancestor project (i.e., a project extended by the current
20795project, either directly or indirectly)
20796
20797@item
20798An expanded name whose prefix is an imported/parent project name, and
20799whose selector is a package name in that project.
20800@end itemize
20801
20802@node Case Constructions,Attributes,Variables,Project File Reference
20803@anchor{gnat_ugn/gnat_project_manager id46}@anchor{1a5}@anchor{gnat_ugn/gnat_project_manager case-constructions}@anchor{1a3}
20804@subsection Case Constructions
20805
20806
20807A @strong{case} construction is used in a project file to effect conditional
20808behavior. Through this construction, you can set the value of attributes
20809and variables depending on the value previously assigned to a typed
20810variable.
20811
20812All choices in a choice list must be distinct. Unlike Ada, the choice
20813lists of all alternatives do not need to include all values of the type.
20814An @cite{others} choice must appear last in the list of alternatives.
20815
20816The syntax of a @cite{case} construction is based on the Ada case construction
20817(although the @cite{null} declaration for empty alternatives is optional).
20818
20819The case expression must be a string variable, either typed or not, whose value
20820is often given by an external reference (see @ref{157,,External Values}).
20821
20822Each alternative starts with the reserved word @cite{when}, either a list of
20823literal strings separated by the @cite{"|"} character or the reserved word
20824@cite{others}, and the @cite{"=>"} token.
20825When the case expression is a typed string variable, each literal string must
20826belong to the string type that is the type of the case variable.
20827After each @cite{=>}, there are zero or more declarations.  The only
20828declarations allowed in a case construction are other case constructions,
20829attribute declarations and variable declarations. String type declarations and
20830package declarations are not allowed. Variable declarations are restricted to
20831variables that have already been declared before the case construction.
20832
20833@example
20834case_construction ::=
20835  *case* *<variable_>*name *is* @{case_item@} *end case* ;
20836
20837case_item ::=
20838  *when* discrete_choice_list =>
20839    @{case_declaration
20840      | attribute_declaration
20841      | variable_declaration
20842      | empty_declaration@}
20843
20844discrete_choice_list ::= string_literal @{| string_literal@} | *others*
20845@end example
20846
20847Here is a typical example, with a typed string variable:
20848
20849@example
20850project MyProj is
20851   type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
20852   OS : OS_Type := external ("OS", "GNU/Linux");
20853
20854   package Compiler is
20855     case OS is
20856       when "GNU/Linux" | "Unix" =>
20857         for Switches ("Ada")
20858             use ("-gnath");
20859       when "NT" =>
20860         for Switches ("Ada")
20861             use ("-gnatP");
20862       when others =>
20863         null;
20864     end case;
20865   end Compiler;
20866end MyProj;
20867@end example
20868
20869@node Attributes,,Case Constructions,Project File Reference
20870@anchor{gnat_ugn/gnat_project_manager id47}@anchor{1a6}@anchor{gnat_ugn/gnat_project_manager attributes}@anchor{155}
20871@subsection Attributes
20872
20873
20874A project (and its packages) may have @strong{attributes} that define
20875the project's properties.  Some attributes have values that are strings;
20876others have values that are string lists.
20877
20878@example
20879attribute_declaration ::=
20880   simple_attribute_declaration | indexed_attribute_declaration
20881
20882simple_attribute_declaration ::= *for* attribute_designator *use* expression ;
20883
20884indexed_attribute_declaration ::=
20885  *for* *<indexed_attribute_>*simple_name ( string_literal) *use* expression ;
20886
20887attribute_designator ::=
20888  *<simple_attribute_>*simple_name
20889  | *<indexed_attribute_>*simple_name ( string_literal )
20890@end example
20891
20892There are two categories of attributes: @strong{simple attributes}
20893and @strong{indexed attributes}.
20894Each simple attribute has a default value: the empty string (for string
20895attributes) and the empty list (for string list attributes).
20896An attribute declaration defines a new value for an attribute, and overrides
20897the previous value. The syntax of a simple attribute declaration is similar to
20898that of an attribute definition clause in Ada.
20899
20900Some attributes are indexed. These attributes are mappings whose
20901domain is a set of strings. They are declared one association
20902at a time, by specifying a point in the domain and the corresponding image
20903of the attribute.
20904Like untyped variables and simple attributes, indexed attributes
20905may be declared several times. Each declaration supplies a new value for the
20906attribute, and replaces the previous setting.
20907
20908Here are some examples of attribute declarations:
20909
20910@example
20911--  simple attributes
20912for Object_Dir use "objects";
20913for Source_Dirs use ("units", "test/drivers");
20914
20915--  indexed attributes
20916for Body ("main") use "Main.ada";
20917for Switches ("main.ada")
20918    use ("-v", "-gnatv");
20919for Switches ("main.ada") use Builder'Switches ("main.ada") & "-g";
20920
20921--  indexed attributes copy (from package Builder in project Default)
20922--  The package name must always be specified, even if it is the current
20923--  package.
20924for Default_Switches use Default.Builder'Default_Switches;
20925@end example
20926
20927Attributes references may appear anywhere in expressions, and are used
20928to retrieve the value previously assigned to the attribute. If an attribute
20929has not been set in a given package or project, its value defaults to the
20930empty string or the empty list, with some exceptions.
20931
20932@example
20933attribute_reference ::=
20934  attribute_prefix ' *<simple_attribute>_*simple_name [ (string_literal) ]
20935attribute_prefix ::= *project*
20936  | *<project_>*simple_name
20937  | package_identifier
20938  | *<project_>*simple_name . package_identifier
20939@end example
20940
20941Examples are:
20942
20943@example
20944<project>'Object_Dir
20945Naming'Dot_Replacement
20946Imported_Project'Source_Dirs
20947Imported_Project.Naming'Casing
20948Builder'Default_Switches ("Ada")
20949@end example
20950
20951The exceptions to the empty defaults are:
20952
20953
20954@itemize *
20955
20956@item
20957Object_Dir: default is "."
20958
20959@item
20960Exec_Dir: default is 'Object_Dir, that is the value of attribute
20961Object_Dir in the same project, declared or defaulted.
20962
20963@item
20964Source_Dirs: default is (".")
20965@end itemize
20966
20967The prefix of an attribute may be:
20968
20969
20970@itemize *
20971
20972@item
20973@cite{project} for an attribute of the current project
20974
20975@item
20976The name of an existing package of the current project
20977
20978@item
20979The name of an imported project
20980
20981@item
20982The name of a parent project that is extended by the current project
20983
20984@item
20985An expanded name whose prefix is imported/parent project name,
20986and whose selector is a package name
20987@end itemize
20988
20989In the following sections, all predefined attributes are succinctly described,
20990first the project level attributes, that is those attributes that are not in a
20991package, then the attributes in the different packages.
20992
20993It is possible for different tools to dynamically create new packages with
20994attributes, or new attributes in predefined packages. These attributes are
20995not documented here.
20996
20997The attributes under Configuration headings are usually found only in
20998configuration project files.
20999
21000The characteristics of each attribute are indicated as follows:
21001
21002
21003@itemize *
21004
21005@item
21006@strong{Type of value}
21007
21008The value of an attribute may be a single string, indicated by the word
21009"single", or a string list, indicated by the word "list".
21010
21011@item
21012@strong{Read-only}
21013
21014When the attribute is read-only, that is when it is not allowed to declare
21015the attribute, this is indicated by the words "read-only".
21016
21017@item
21018@strong{Optional index}
21019
21020If it is allowed in the value of the attribute (both single and list) to have
21021an optional index, this is indicated by the words "optional index".
21022
21023@item
21024@strong{Indexed attribute}
21025
21026When it is an indexed attribute, this is indicated by the word "indexed".
21027
21028@item
21029@strong{Case-sensitivity of the index}
21030
21031For an indexed attribute, if the index is case-insensitive, this is indicated
21032by the words "case-insensitive index".
21033
21034@item
21035@strong{File name index}
21036
21037For an indexed attribute, when the index is a file name, this is indicated by
21038the words "file name index". The index may or may not be case-sensitive,
21039depending on the platform.
21040
21041@item
21042@strong{others allowed in index}
21043
21044For an indexed attribute, if it is allowed to use @strong{others} as the index,
21045this is indicated by the words "others allowed".
21046
21047When @strong{others} is used as the index of an indexed attribute, the value of
21048the attribute indexed by @strong{others} is used when no other index would apply.
21049@end itemize
21050
21051@menu
21052* Project Level Attributes::
21053* Package Binder Attributes::
21054* Package Builder Attributes::
21055* Package Clean Attributes::
21056* Package Compiler Attributes::
21057* Package Cross_Reference Attributes::
21058* Package Finder Attributes::
21059* Package gnatls Attributes::
21060* Package IDE Attributes::
21061* Package Install Attributes::
21062* Package Linker Attributes::
21063* Package Naming Attributes::
21064* Package Remote Attributes::
21065* Package Stack Attributes::
21066* Package Synchronize Attributes::
21067
21068@end menu
21069
21070@node Project Level Attributes,Package Binder Attributes,,Attributes
21071@anchor{gnat_ugn/gnat_project_manager project-level-attributes}@anchor{1a7}@anchor{gnat_ugn/gnat_project_manager id48}@anchor{1a8}
21072@subsubsection Project Level Attributes
21073
21074
21075
21076@itemize *
21077
21078@item
21079@strong{General}
21080
21081
21082@itemize *
21083
21084@item
21085@strong{Name}: single, read-only
21086
21087The name of the project.
21088
21089@item
21090@strong{Project_Dir}: single, read-only
21091
21092The path name of the project directory.
21093
21094@item
21095@strong{Main}: list, optional index
21096
21097The list of main sources for the executables.
21098
21099@item
21100@strong{Languages}: list
21101
21102The list of languages of the sources of the project.
21103
21104@item
21105@strong{Roots}: list, indexed, file name index
21106
21107The index is the file name of an executable source. Indicates the list of units
21108from the main project that need to be bound and linked with their closures
21109with the executable. The index is either a file name, a language name or "*".
21110The roots for an executable source are those in @strong{Roots} with an index that
21111is the executable source file name, if declared. Otherwise, they are those in
21112@strong{Roots} with an index that is the language name of the executable source,
21113if present. Otherwise, they are those in @strong{Roots ("*")}, if declared. If none
21114of these three possibilities are declared, then there are no roots for the
21115executable source.
21116
21117@item
21118@strong{Externally_Built}: single
21119
21120Indicates if the project is externally built.
21121Only case-insensitive values allowed are "true" and "false", the default.
21122@end itemize
21123
21124@item
21125@strong{Directories}
21126
21127
21128@itemize *
21129
21130@item
21131@strong{Object_Dir}: single
21132
21133Indicates the object directory for the project.
21134
21135@item
21136@strong{Exec_Dir}: single
21137
21138Indicates the exec directory for the project, that is the directory where the
21139executables are.
21140
21141@item
21142@strong{Source_Dirs}: list
21143
21144The list of source directories of the project.
21145
21146@item
21147@strong{Inherit_Source_Path}: list, indexed, case-insensitive index
21148
21149Index is a language name. Value is a list of language names. Indicates that
21150in the source search path of the index language the source directories of
21151the languages in the list should be included.
21152
21153Example:
21154
21155@example
21156for Inherit_Source_Path ("C++") use ("C");
21157@end example
21158
21159@item
21160@strong{Exclude_Source_Dirs}: list
21161
21162The list of directories that are included in Source_Dirs but are not source
21163directories of the project.
21164
21165@item
21166@strong{Ignore_Source_Sub_Dirs}: list
21167
21168Value is a list of simple names for subdirectories that are removed from the
21169list of source directories, including theur subdirectories.
21170@end itemize
21171
21172@item
21173@strong{Source Files}
21174
21175
21176@itemize *
21177
21178@item
21179@strong{Source_Files}: list
21180
21181Value is a list of source file simple names.
21182
21183@item
21184@strong{Locally_Removed_Files}: list
21185
21186Obsolescent. Equivalent to Excluded_Source_Files.
21187
21188@item
21189@strong{Excluded_Source_Files}: list
21190
21191Value is a list of simple file names that are not sources of the project.
21192Allows to remove sources that are inherited or found in the source directories
21193and that match the naming scheme.
21194
21195@item
21196@strong{Source_List_File}: single
21197
21198Value is a text file name that contains a list of source file simple names,
21199one on each line.
21200
21201@item
21202@strong{Excluded_Source_List_File}: single
21203
21204Value is a text file name that contains a list of file simple names that
21205are not sources of the project.
21206
21207@item
21208@strong{Interfaces}: list
21209
21210Value is a list of file names that constitutes the interfaces of the project.
21211@end itemize
21212
21213@item
21214@strong{Aggregate Projects}
21215
21216
21217@itemize *
21218
21219@item
21220@strong{Project_Files}: list
21221
21222Value is the list of aggregated projects.
21223
21224@item
21225@strong{Project_Path}: list
21226
21227Value is a list of directories that are added to the project search path when
21228looking for the aggregated projects.
21229
21230@item
21231@strong{External}: single, indexed
21232
21233Index is the name of an external reference. Value is the value of the
21234external reference to be used when parsing the aggregated projects.
21235@end itemize
21236
21237@item
21238@strong{Libraries}
21239
21240
21241@itemize *
21242
21243@item
21244@strong{Library_Dir}: single
21245
21246Value is the name of the library directory. This attribute needs to be
21247declared for each library project.
21248
21249@item
21250@strong{Library_Name}: single
21251
21252Value is the name of the library. This attribute needs to be declared or
21253inherited for each library project.
21254
21255@item
21256@strong{Library_Kind}: single
21257
21258Specifies the kind of library: static library (archive) or shared library.
21259Case-insensitive values must be one of "static" for archives (the default) or
21260"dynamic" or "relocatable" for shared libraries.
21261
21262@item
21263@strong{Library_Version}: single
21264
21265Value is the name of the library file.
21266
21267@item
21268@strong{Library_Interface}: list
21269
21270Value is the list of unit names that constitutes the interfaces
21271of a Stand-Alone Library project.
21272
21273@item
21274@strong{Library_Standalone}: single
21275
21276Specifies if a Stand-Alone Library (SAL) is encapsulated or not.
21277Only authorized case-insensitive values are "standard" for non encapsulated
21278SALs, "encapsulated" for encapsulated SALs or "no" for non SAL library project.
21279
21280@item
21281@strong{Library_Encapsulated_Options}: list
21282
21283Value is a list of options that need to be used when linking an encapsulated
21284Stand-Alone Library.
21285
21286@item
21287@strong{Library_Encapsulated_Supported}: single
21288
21289Indicates if encapsulated Stand-Alone Libraries are supported. Only
21290authorized case-insensitive values are "true" and "false" (the default).
21291
21292@item
21293@strong{Library_Auto_Init}: single
21294
21295Indicates if a Stand-Alone Library is auto-initialized. Only authorized
21296case-insentive values are "true" and "false".
21297
21298@item
21299@strong{Leading_Library_Options}: list
21300
21301Value is a list of options that are to be used at the beginning of
21302the command line when linking a shared library.
21303
21304@item
21305@strong{Library_Options}: list
21306
21307Value is a list of options that are to be used when linking a shared library.
21308
21309@item
21310@strong{Library_Rpath_Options}: list, indexed, case-insensitive index
21311
21312Index is a language name. Value is a list of options for an invocation of the
21313compiler of the language. This invocation is done for a shared library project
21314with sources of the language. The output of the invocation is the path name
21315of a shared library file. The directory name is to be put in the run path
21316option switch when linking the shared library for the project.
21317
21318@item
21319@strong{Library_Src_Dir}: single
21320
21321Value is the name of the directory where copies of the sources of the
21322interfaces of a Stand-Alone Library are to be copied.
21323
21324@item
21325@strong{Library_ALI_Dir}: single
21326
21327Value is the name of the directory where the ALI files of the interfaces
21328of a Stand-Alone Library are to be copied. When this attribute is not declared,
21329the directory is the library directory.
21330
21331@item
21332@strong{Library_gcc}: single
21333
21334Obsolescent attribute. Specify the linker driver used to link a shared library.
21335Use instead attribute Linker'Driver.
21336
21337@item
21338@strong{Library_Symbol_File}: single
21339
21340Value is the name of the library symbol file.
21341
21342@item
21343@strong{Library_Symbol_Policy}: single
21344
21345Indicates the symbol policy kind. Only authorized case-insensitive values are
21346"autonomous", "default", "compliant", "controlled" or "direct".
21347
21348@item
21349@strong{Library_Reference_Symbol_File}: single
21350
21351Value is the name of the reference symbol file.
21352@end itemize
21353
21354@item
21355@strong{Configuration - General}
21356
21357
21358@itemize *
21359
21360@item
21361@strong{Default_Language}: single
21362
21363Value is the case-insensitive name of the language of a project when attribute
21364Languages is not specified.
21365
21366@item
21367@strong{Run_Path_Option}: list
21368
21369Value is the list of switches to be used when specifying the run path option
21370in an executable.
21371
21372@item
21373@strong{Run_Path_Origin}: single
21374
21375Value is the the string that may replace the path name of the executable
21376directory in the run path options.
21377
21378@item
21379@strong{Separate_Run_Path_Options}: single
21380
21381Indicates if there may be several run path options specified when linking an
21382executable. Only authorized case-insensitive values are "true" or "false" (the
21383default).
21384
21385@item
21386@strong{Toolchain_Version}: single, indexed, case-insensitive index
21387
21388Index is a language name. Specify the version of a toolchain for a language.
21389
21390@item
21391@strong{Toolchain_Description}: single, indexed, case-insensitive index
21392
21393Obsolescent. No longer used.
21394
21395@item
21396@strong{Object_Generated}: single, indexed, case-insensitive index
21397
21398Index is a language name. Indicates if invoking the compiler for a language
21399produces an object file. Only authorized case-insensitive values are "false"
21400and "true" (the default).
21401
21402@item
21403@strong{Objects_Linked}: single, indexed, case-insensitive index
21404
21405Index is a language name. Indicates if the object files created by the compiler
21406for a language need to be linked in the executable. Only authorized
21407case-insensitive values are "false" and "true" (the default).
21408
21409@item
21410@strong{Target}: single
21411
21412Value is the name of the target platform. Taken into account only in the main
21413project.
21414
21415Note that when the target is specified on the command line (usually with
21416a switch --target=), the value of attribute reference 'Target is the one
21417specified on the command line.
21418
21419@item
21420@strong{Runtime}: single, indexed, case-insensitive index
21421
21422Index is a language name. Indicates the runtime directory that is to be used
21423when using the compiler of the language. Taken into account only in the main
21424project.
21425
21426Note that when the runtime is specified for a language on the command line
21427(usually with a switch --RTS), the value of attribute reference 'Runtime
21428for this language is the one specified on the command line.
21429@end itemize
21430
21431@item
21432@strong{Configuration - Libraries}
21433
21434
21435@itemize *
21436
21437@item
21438@strong{Library_Builder}: single
21439
21440Value is the path name of the application that is to be used to build
21441libraries. Usually the path name of "gprlib".
21442
21443@item
21444@strong{Library_Support}: single
21445
21446Indicates the level of support of libraries. Only authorized case-insensitive
21447values are "static_only", "full" or "none" (the default).
21448@end itemize
21449
21450@item
21451@strong{Configuration - Archives}
21452
21453
21454@itemize *
21455
21456@item
21457@strong{Archive_Builder}: list
21458
21459Value is the name of the application to be used to create a static library
21460(archive), followed by the options to be used.
21461
21462@item
21463@strong{Archive_Builder_Append_Option}: list
21464
21465Value is the list of options to be used when invoking the archive builder
21466to add project files into an archive.
21467
21468@item
21469@strong{Archive_Indexer}: list
21470
21471Value is the name of the archive indexer, followed by the required options.
21472
21473@item
21474@strong{Archive_Suffix}: single
21475
21476Value is the extension of archives. When not declared, the extension is ".a".
21477
21478@item
21479@strong{Library_Partial_Linker}: list
21480
21481Value is the name of the partial linker executable, followed by the required
21482options.
21483@end itemize
21484
21485@item
21486@strong{Configuration - Shared Libraries}
21487
21488
21489@itemize *
21490
21491@item
21492@strong{Shared_Library_Prefix}: single
21493
21494Value is the prefix in the name of shared library files. When not declared,
21495the prefix is "lib".
21496
21497@item
21498@strong{Shared_Library_Suffix}: single
21499
21500Value is the the extension of the name of shared library files. When not
21501declared, the extension is ".so".
21502
21503@item
21504@strong{Symbolic_Link_Supported}: single
21505
21506Indicates if symbolic links are supported on the platform. Only authorized
21507case-insensitive values are "true" and "false" (the default).
21508
21509@item
21510@strong{Library_Major_Minor_Id_Supported}: single
21511
21512Indicates if major and minor ids for shared library names are supported on
21513the platform. Only authorized case-insensitive values are "true" and "false"
21514(the default).
21515
21516@item
21517@strong{Library_Auto_Init_Supported}: single
21518
21519Indicates if auto-initialization of Stand-Alone Libraries is supported. Only
21520authorized case-insensitive values are "true" and "false" (the default).
21521
21522@item
21523@strong{Shared_Library_Minimum_Switches}: list
21524
21525Value is the list of required switches when linking a shared library.
21526
21527@item
21528@strong{Library_Version_Switches}: list
21529
21530Value is the list of switches to specify a internal name for a shared library.
21531
21532@item
21533@strong{Library_Install_Name_Option}: single
21534
21535Value is the name of the option that needs to be used, concatenated with the
21536path name of the library file, when linking a shared library.
21537
21538@item
21539@strong{Runtime_Library_Dir}: single, indexed, case-insensitive index
21540
21541Index is a language name. Value is the path name of the directory where the
21542runtime libraries are located.
21543
21544@item
21545@strong{Runtime_Source_Dir}: single, indexed, case-insensitive index
21546
21547Index is a language name. Value is the path name of the directory where the
21548sources of runtime libraries are located.
21549@end itemize
21550@end itemize
21551
21552@node Package Binder Attributes,Package Builder Attributes,Project Level Attributes,Attributes
21553@anchor{gnat_ugn/gnat_project_manager package-binder-attributes}@anchor{1a9}@anchor{gnat_ugn/gnat_project_manager id49}@anchor{1aa}
21554@subsubsection Package Binder Attributes
21555
21556
21557
21558@itemize *
21559
21560@item
21561@strong{General}
21562
21563
21564@itemize *
21565
21566@item
21567@strong{Default_Switches}: list, indexed, case-insensitive index
21568
21569Index is a language name. Value is the list of switches to be used when binding
21570code of the language, if there is no applicable attribute Switches.
21571
21572@item
21573@strong{Switches}: list, optional index, indexed,
21574case-insensitive index, others allowed
21575
21576Index is either a language name or a source file name. Value is the list of
21577switches to be used when binding code. Index is either the source file name
21578of the executable to be bound or the language name of the code to be bound.
21579@end itemize
21580
21581@item
21582@strong{Configuration - Binding}
21583
21584
21585@itemize *
21586
21587@item
21588@strong{Driver}: single, indexed, case-insensitive index
21589
21590Index is a language name. Value is the name of the application to be used when
21591binding code of the language.
21592
21593@item
21594@strong{Required_Switches}: list, indexed, case-insensitive index
21595
21596Index is a language name. Value is the list of the required switches to be
21597used when binding code of the language.
21598
21599@item
21600@strong{Prefix}: single, indexed, case-insensitive index
21601
21602Index is a language name. Value is a prefix to be used for the binder exchange
21603file name for the language. Used to have different binder exchange file names
21604when binding different languages.
21605
21606@item
21607@strong{Objects_Path}: single,indexed, case-insensitive index
21608
21609Index is a language name. Value is the name of the environment variable that
21610contains the path for the object directories.
21611
21612@item
21613@strong{Object_Path_File}: single,indexed, case-insensitive index
21614
21615Index is a language name. Value is the name of the environment variable. The
21616value of the environment variable is the path name of a text file that
21617contains the list of object directories.
21618@end itemize
21619@end itemize
21620
21621@node Package Builder Attributes,Package Clean Attributes,Package Binder Attributes,Attributes
21622@anchor{gnat_ugn/gnat_project_manager package-builder-attributes}@anchor{1ab}@anchor{gnat_ugn/gnat_project_manager id50}@anchor{1ac}
21623@subsubsection Package Builder Attributes
21624
21625
21626
21627@itemize *
21628
21629@item
21630@strong{Default_Switches}: list, indexed, case-insensitive index
21631
21632Index is a language name. Value is the list of builder switches to be used when
21633building an executable of the language, if there is no applicable attribute
21634Switches.
21635
21636@item
21637@strong{Switches}: list, optional index, indexed, case-insensitive index,
21638others allowed
21639
21640Index is either a language name or a source file name. Value is the list of
21641builder switches to be used when building an executable. Index is either the
21642source file name of the executable to be built or its language name.
21643
21644@item
21645@strong{Global_Compilation_Switches}: list, optional index, indexed,
21646case-insensitive index
21647
21648Index is either a language name or a source file name. Value is the list of
21649compilation switches to be used when building an executable. Index is either
21650the source file name of the executable to be built or its language name.
21651
21652@item
21653@strong{Executable}: single, indexed, case-insensitive index
21654
21655Index is an executable source file name. Value is the simple file name of the
21656executable to be built.
21657
21658@item
21659@strong{Executable_Suffix}: single
21660
21661Value is the extension of the file names of executable. When not specified,
21662the extension is the default extension of executables on the platform.
21663
21664@item
21665@strong{Global_Configuration_Pragmas}: single
21666
21667Value is the file name of a configuration pragmas file that is specified to
21668the Ada compiler when compiling any Ada source in the project tree.
21669
21670@item
21671@strong{Global_Config_File}: single, indexed, case-insensitive index
21672
21673Index is a language name. Value is the file name of a configuration file that
21674is specified to the compiler when compiling any source of the language in the
21675project tree.
21676@end itemize
21677
21678
21679@node Package Clean Attributes,Package Compiler Attributes,Package Builder Attributes,Attributes
21680@anchor{gnat_ugn/gnat_project_manager package-clean-attributes}@anchor{1ad}@anchor{gnat_ugn/gnat_project_manager id52}@anchor{1ae}
21681@subsubsection Package Clean Attributes
21682
21683
21684
21685@itemize *
21686
21687@item
21688@strong{Switches}: list
21689
21690Value is a list of switches to be used by the cleaning application.
21691
21692@item
21693@strong{Source_Artifact_Extensions}: list, indexed, case-insensitive index
21694
21695Index is a language names. Value is the list of extensions for file names
21696derived from object file names that need to be cleaned in the object
21697directory of the project.
21698
21699@item
21700@strong{Object_Artifact_Extensions}: list, indexed, case-insensitive index
21701
21702Index is a language names. Value is the list of extensions for file names
21703derived from source file names that need to be cleaned in the object
21704directory of the project.
21705
21706@item
21707@strong{Artifacts_In_Object_Dir}: single
21708
21709Value is a list of file names expressed as regular expressions that are to be
21710deleted by gprclean in the object directory of the project.
21711
21712@item
21713@strong{Artifacts_In_Exec_Dir}: single
21714
21715Value is list of file names expressed as regular expressions that are to be
21716deleted by gprclean in the exec directory of the main project.
21717@end itemize
21718
21719@node Package Compiler Attributes,Package Cross_Reference Attributes,Package Clean Attributes,Attributes
21720@anchor{gnat_ugn/gnat_project_manager id53}@anchor{1af}@anchor{gnat_ugn/gnat_project_manager package-compiler-attributes}@anchor{1b0}
21721@subsubsection Package Compiler Attributes
21722
21723
21724
21725@itemize *
21726
21727@item
21728@strong{General}
21729
21730
21731@itemize *
21732
21733@item
21734@strong{Default_Switches}: list, indexed, case-insensitive index
21735
21736Index is a language name. Value is a list of switches to be used when invoking
21737the compiler for the language for a source of the project, if there is no
21738applicable attribute Switches.
21739
21740@item
21741@strong{Switches}: list, optional index, indexed, case-insensitive index,
21742others allowed
21743
21744Index is a source file name or a language name. Value is the list of switches
21745to be used when invoking the compiler for the source or for its language.
21746
21747@item
21748@strong{Local_Configuration_Pragmas}: single
21749
21750Value is the file name of a configuration pragmas file that is specified to
21751the Ada compiler when compiling any Ada source in the project.
21752
21753@item
21754@strong{Local_Config_File}: single, indexed, case-insensitive index
21755
21756Index is a language name. Value is the file name of a configuration file that
21757is specified to the compiler when compiling any source of the language in the
21758project.
21759@end itemize
21760
21761@item
21762@strong{Configuration - Compiling}
21763
21764
21765@itemize *
21766
21767@item
21768@strong{Driver}: single, indexed, case-insensitive index
21769
21770Index is a language name. Value is the name of the executable for the compiler
21771of the language.
21772
21773@item
21774@strong{Language_Kind}: single, indexed, case-insensitive index
21775
21776Index is a language name. Indicates the kind of the language, either file based
21777or unit based. Only authorized case-insensitive values are "unit_based" and
21778"file_based" (the default).
21779
21780@item
21781@strong{Dependency_Kind}: single, indexed, case-insensitive index
21782
21783Index is a language name. Indicates how the dependencies are handled for the
21784language. Only authorized case-insensitive values are "makefile", "ali_file",
21785"ali_closure" or "none" (the default).
21786
21787@item
21788@strong{Required_Switches}: list, indexed, case-insensitive index
21789
21790Equivalent to attribute Leading_Required_Switches.
21791
21792@item
21793@strong{Leading_Required_Switches}: list, indexed, case-insensitive index
21794
21795Index is a language name. Value is the list of the minimum switches to be used
21796at the beginning of the command line when invoking the compiler for the
21797language.
21798
21799@item
21800@strong{Trailing_Required_Switches}: list, indexed, case-insensitive index
21801
21802Index is a language name. Value is the list of the minimum switches to be used
21803at the end of the command line when invoking the compiler for the language.
21804
21805@item
21806@strong{PIC_Option}: list, indexed, case-insensitive index
21807
21808Index is a language name. Value is the list of switches to be used when
21809compiling a source of the language when the project is a shared library
21810project.
21811
21812@item
21813@strong{Path_Syntax}: single, indexed, case-insensitive index
21814
21815Index is a language name. Value is the kind of path syntax to be used when
21816invoking the compiler for the language. Only authorized case-insensitive
21817values are "canonical" and "host" (the default).
21818
21819@item
21820@strong{Source_File_Switches}: single, indexed, case-insensitive index
21821
21822Index is a language name. Value is a list of switches to be used just before
21823the path name of the source to compile when invoking the compiler for a source
21824of the language.
21825
21826@item
21827@strong{Object_File_Suffix}: single, indexed, case-insensitive index
21828
21829Index is a language name. Value is the extension of the object files created
21830by the compiler of the language. When not specified, the extension is the
21831default one for the platform.
21832
21833@item
21834@strong{Object_File_Switches}: list, indexed, case-insensitive index
21835
21836Index is a language name. Value is the list of switches to be used by the
21837compiler of the language to specify the path name of the object file. When not
21838specified, the switch used is "-o".
21839
21840@item
21841@strong{Multi_Unit_Switches}: list, indexed, case-insensitive index
21842
21843Index is a language name. Value is the list of switches to be used to compile
21844a unit in a multi unit source of the language. The index of the unit in the
21845source is concatenated with the last switches in the list.
21846
21847@item
21848@strong{Multi_Unit_Object_Separator}: single, indexed, case-insensitive index
21849
21850Index is a language name. Value is the string to be used in the object file
21851name before the index of the unit, when compiling a unit in a multi unit source
21852of the language.
21853@end itemize
21854
21855@item
21856@strong{Configuration - Mapping Files}
21857
21858
21859@itemize *
21860
21861@item
21862@strong{Mapping_File_Switches}: list, indexed, case-insensitive index
21863
21864Index is a language name. Value is the list of switches to be used to specify
21865a mapping file when invoking the compiler for a source of the language.
21866
21867@item
21868@strong{Mapping_Spec_Suffix}: single, indexed, case-insensitive index
21869
21870Index is a language name. Value is the suffix to be used in a mapping file
21871to indicate that the source is a spec.
21872
21873@item
21874@strong{Mapping_Body_Suffix}: single, indexed, case-insensitive index
21875
21876Index is a language name. Value is the suffix to be used in a mapping file
21877to indicate that the source is a body.
21878@end itemize
21879
21880@item
21881@strong{Configuration - Config Files}
21882
21883
21884@itemize *
21885
21886@item
21887@strong{Config_File_Switches}: list: single, indexed, case-insensitive index
21888
21889Index is a language name. Value is the list of switches to specify to the
21890compiler of the language a configuration file.
21891
21892@item
21893@strong{Config_Body_File_Name}: single, indexed, case-insensitive index
21894
21895Index is a language name. Value is the template to be used to indicate a
21896configuration specific to a body of the language in a configuration
21897file.
21898
21899@item
21900@strong{Config_Body_File_Name_Index}: single, indexed, case-insensitive index
21901
21902Index is a language name. Value is the template to be used to indicate a
21903configuration specific to the body a unit in a multi unit source of the
21904language in a configuration file.
21905
21906@item
21907@strong{Config_Body_File_Name_Pattern}: single, indexed,
21908case-insensitive index
21909
21910Index is a language name. Value is the template to be used to indicate a
21911configuration for all bodies of the languages in a configuration file.
21912
21913@item
21914@strong{Config_Spec_File_Name}: single, indexed, case-insensitive index
21915
21916Index is a language name. Value is the template to be used to indicate a
21917configuration specific to a spec of the language in a configuration
21918file.
21919
21920@item
21921@strong{Config_Spec_File_Name_Index}: single, indexed, case-insensitive index
21922
21923Index is a language name. Value is the template to be used to indicate a
21924configuration specific to the spec a unit in a multi unit source of the
21925language in a configuration file.
21926
21927@item
21928@strong{Config_Spec_File_Name_Pattern}: single, indexed,
21929case-insensitive index
21930
21931Index is a language name. Value is the template to be used to indicate a
21932configuration for all specs of the languages in a configuration file.
21933
21934@item
21935@strong{Config_File_Unique}: single, indexed, case-insensitive index
21936
21937Index is a language name. Indicates if there should be only one configuration
21938file specified to the compiler of the language. Only authorized
21939case-insensitive values are "true" and "false" (the default).
21940@end itemize
21941
21942@item
21943@strong{Configuration - Dependencies}
21944
21945
21946@itemize *
21947
21948@item
21949@strong{Dependency_Switches}: list, indexed, case-insensitive index
21950
21951Index is a language name. Value is the list of switches to be used to specify
21952to the compiler the dependency file when the dependency kind of the language is
21953file based, and when Dependency_Driver is not specified for the language.
21954
21955@item
21956@strong{Dependency_Driver}: list, indexed, case-insensitive index
21957
21958Index is a language name. Value is the name of the executable to be used to
21959create the dependency file for a source of the language, followed by the
21960required switches.
21961@end itemize
21962
21963@item
21964@strong{Configuration - Search Paths}
21965
21966
21967@itemize *
21968
21969@item
21970@strong{Include_Switches}: list, indexed, case-insensitive index
21971
21972Index is a language name. Value is the list of switches to specify to the
21973compiler of the language to indicate a directory to look for sources.
21974
21975@item
21976@strong{Include_Path}: single, indexed, case-insensitive index
21977
21978Index is a language name. Value is the name of an environment variable that
21979contains the path of all the directories that the compiler of the language
21980may search for sources.
21981
21982@item
21983@strong{Include_Path_File}: single, indexed, case-insensitive index
21984
21985Index is a language name. Value is the name of an environment variable the
21986value of which is the path name of a text file that contains the directories
21987that the compiler of the language may search for sources.
21988
21989@item
21990@strong{Object_Path_Switches}: list, indexed, case-insensitive index
21991
21992Index is a language name. Value is the list of switches to specify to the
21993compiler of the language the name of a text file that contains the list of
21994object directories. When this attribute is not declared, the text file is
21995not created.
21996@end itemize
21997@end itemize
21998
21999@node Package Cross_Reference Attributes,Package Finder Attributes,Package Compiler Attributes,Attributes
22000@anchor{gnat_ugn/gnat_project_manager id54}@anchor{1b1}@anchor{gnat_ugn/gnat_project_manager package-cross-reference-attributes}@anchor{1b2}
22001@subsubsection Package Cross_Reference Attributes
22002
22003
22004
22005@itemize *
22006
22007@item
22008@strong{Default_Switches}: list, indexed, case-insensitive index
22009
22010Index is a language name. Value is a list of switches to be used when invoking
22011@cite{gnatxref} for a source of the language, if there is no applicable
22012attribute Switches.
22013
22014@item
22015@strong{Switches}: list, optional index, indexed, case-insensitive index,
22016others allowed
22017
22018Index is a source file name. Value is the list of switches to be used when
22019invoking @cite{gnatxref} for the source.
22020@end itemize
22021
22022
22023@node Package Finder Attributes,Package gnatls Attributes,Package Cross_Reference Attributes,Attributes
22024@anchor{gnat_ugn/gnat_project_manager id56}@anchor{1b3}@anchor{gnat_ugn/gnat_project_manager package-finder-attributes}@anchor{1b4}
22025@subsubsection Package Finder Attributes
22026
22027
22028
22029@itemize *
22030
22031@item
22032@strong{Default_Switches}: list, indexed, case-insensitive index
22033
22034Index is a language name. Value is a list of switches to be used when invoking
22035@cite{gnatfind} for a source of the language, if there is no applicable
22036attribute Switches.
22037
22038@item
22039@strong{Switches}: list, optional index, indexed, case-insensitive index,
22040others allowed
22041
22042Index is a source file name. Value is the list of switches to be used when
22043invoking @cite{gnatfind} for the source.
22044@end itemize
22045
22046@node Package gnatls Attributes,Package IDE Attributes,Package Finder Attributes,Attributes
22047@anchor{gnat_ugn/gnat_project_manager package-gnatls-attributes}@anchor{1b5}@anchor{gnat_ugn/gnat_project_manager id57}@anchor{1b6}
22048@subsubsection Package gnatls Attributes
22049
22050
22051
22052@itemize *
22053
22054@item
22055@strong{Switches}: list
22056
22057Value is a list of switches to be used when invoking @cite{gnatls}.
22058@end itemize
22059
22060
22061@node Package IDE Attributes,Package Install Attributes,Package gnatls Attributes,Attributes
22062@anchor{gnat_ugn/gnat_project_manager id58}@anchor{1b7}@anchor{gnat_ugn/gnat_project_manager package-ide-attributes}@anchor{1b8}
22063@subsubsection Package IDE Attributes
22064
22065
22066
22067@itemize *
22068
22069@item
22070@strong{Default_Switches}: list, indexed
22071
22072Index is the name of an external tool that the GNAT Programming System (GPS)
22073is supporting. Value is a list of switches to use when invoking that tool.
22074
22075@item
22076@strong{Remote_Host}: single
22077
22078Value is a string that designates the remote host in a cross-compilation
22079environment, to be used for remote compilation and debugging. This attribute
22080should not be specified when running on the local machine.
22081
22082@item
22083@strong{Program_Host}: single
22084
22085Value is a string that specifies the name of IP address of the embedded target
22086in a cross-compilation environment, on which the program should execute.
22087
22088@item
22089@strong{Communication_Protocol}: single
22090
22091Value is the name of the protocol to use to communicate with the target
22092in a cross-compilation environment, for example @cite{"wtx"} or
22093@cite{"vxworks"}.
22094
22095@item
22096@strong{Compiler_Command}: single, indexed, case-insensitive index
22097
22098Index is a language Name. Value is a string that denotes the command to be
22099used to invoke the compiler. For historical reasons, the value of
22100@cite{Compiler_Command ("Ada")} is expected to be a reference to @emph{gnatmake} or
22101@emph{cross-gnatmake}.
22102
22103@item
22104@strong{Debugger_Command}: single
22105
22106Value is a string that specifies the name of the debugger to be used, such as
22107gdb, powerpc-wrs-vxworks-gdb or gdb-4.
22108
22109@item
22110@strong{gnatlist}: single
22111
22112Value is a string that specifies the name of the @emph{gnatls} utility
22113to be used to retrieve information about the predefined path; for example,
22114@cite{"gnatls"}, @cite{"powerpc-wrs-vxworks-gnatls"}.
22115
22116@item
22117@strong{VCS_Kind}: single
22118
22119Value is a string used to specify the Version Control System (VCS) to be used
22120for this project, for example "Subversion", "ClearCase". If the
22121value is set to "Auto", the IDE will try to detect the actual VCS used
22122on the list of supported ones.
22123
22124@item
22125@strong{VCS_File_Check}: single
22126
22127Value is a string that specifies the command used by the VCS to check
22128the validity of a file, either when the user explicitly asks for a check,
22129or as a sanity check before doing the check-in.
22130
22131@item
22132@strong{VCS_Log_Check}: single
22133
22134Value is a string that specifies the command used by the VCS to check
22135the validity of a log file.
22136
22137@item
22138@strong{Documentation_Dir}: single
22139
22140Value is the directory used to generate the documentation of source code.
22141@end itemize
22142
22143@node Package Install Attributes,Package Linker Attributes,Package IDE Attributes,Attributes
22144@anchor{gnat_ugn/gnat_project_manager package-install-attributes}@anchor{1b9}@anchor{gnat_ugn/gnat_project_manager id59}@anchor{1ba}
22145@subsubsection Package Install Attributes
22146
22147
22148
22149@itemize *
22150
22151@item
22152@strong{Artifacts}: list, indexed
22153
22154An array attribute to declare a set of files not part of the sources
22155to be installed. The array discriminant is the directory where the
22156file is to be installed. If a relative directory then Prefix (see
22157below) is prepended. Note also that if the same file name occurs
22158multiple time in the attribute list, the last one will be the one
22159installed.
22160
22161@item
22162@strong{Prefix}: single
22163
22164Value is the install destination directory.
22165
22166@item
22167@strong{Sources_Subdir}: single
22168
22169Value is the sources directory or subdirectory of Prefix.
22170
22171@item
22172@strong{Exec_Subdir}: single
22173
22174Value is the executables directory or subdirectory of Prefix.
22175
22176@item
22177@strong{Lib_Subdir}: single
22178
22179Value is library directory or subdirectory of Prefix.
22180
22181@item
22182@strong{Project_Subdir}: single
22183
22184Value is the project directory or subdirectory of Prefix.
22185
22186@item
22187@strong{Active}: single
22188
22189Indicates that the project is to be installed or not. Case-insensitive value
22190"false" means that the project is not to be installed, all other values mean
22191that the project is to be installed.
22192
22193@item
22194@strong{Mode}: single
22195
22196Value is the installation mode, it is either @strong{dev} (default) or @strong{usage}.
22197
22198@item
22199@strong{Install_Name}: single
22200
22201Specify the name to use for recording the installation. The default is
22202the project name without the extension.
22203@end itemize
22204
22205@node Package Linker Attributes,Package Naming Attributes,Package Install Attributes,Attributes
22206@anchor{gnat_ugn/gnat_project_manager id60}@anchor{1bb}@anchor{gnat_ugn/gnat_project_manager package-linker-attributes}@anchor{1bc}
22207@subsubsection Package Linker Attributes
22208
22209
22210
22211@itemize *
22212
22213@item
22214@strong{General}
22215
22216
22217@itemize *
22218
22219@item
22220@strong{Required_Switches}: list
22221
22222Value is a list of switches that are required when invoking the linker to link
22223an executable.
22224
22225@item
22226@strong{Default_Switches}: list, indexed, case-insensitive index
22227
22228Index is a language name. Value is a list of switches for the linker when
22229linking an executable for a main source of the language, when there is no
22230applicable Switches.
22231
22232@item
22233@strong{Leading_Switches}: list, optional index, indexed,
22234case-insensitive index, others allowed
22235
22236Index is a source file name or a language name. Value is the list of switches
22237to be used at the beginning of the command line when invoking the linker to
22238build an executable for the source or for its language.
22239
22240@item
22241@strong{Switches}: list, optional index, indexed, case-insensitive index,
22242others allowed
22243
22244Index is a source file name or a language name. Value is the list of switches
22245to be used when invoking the linker to build an executable for the source or
22246for its language.
22247
22248@item
22249@strong{Trailing_Switches}: list, optional index, indexed,
22250case-insensitive index, others allowed
22251
22252Index is a source file name or a language name. Value is the list of switches
22253to be used at the end of the command line when invoking the linker to
22254build an executable for the source or for its language. These switches may
22255override the Required_Switches.
22256
22257@item
22258@strong{Linker_Options}: list
22259
22260Value is a list of switches/options that are to be added when linking an
22261executable from a project importing the current project directly or indirectly.
22262Linker_Options are not used when linking an executable from the current
22263project.
22264
22265@item
22266@strong{Map_File_Option}: single
22267
22268Value is the switch to specify the map file name that the linker needs to
22269create.
22270@end itemize
22271
22272@item
22273@strong{Configuration - Linking}
22274
22275
22276@itemize *
22277
22278@item
22279@strong{Driver}: single
22280
22281Value is the name of the linker executable.
22282@end itemize
22283
22284@item
22285@strong{Configuration - Response Files}
22286
22287
22288@itemize *
22289
22290@item
22291@strong{Max_Command_Line_Length}: single
22292
22293Value is the maximum number of character in the command line when invoking
22294the linker to link an executable.
22295
22296@item
22297@strong{Response_File_Format}: single
22298
22299Indicates the kind of response file to create when the length of the linking
22300command line is too large. Only authorized case-insensitive values are "none",
22301"gnu", "object_list", "gcc_gnu", "gcc_option_list" and "gcc_object_list".
22302
22303@item
22304@strong{Response_File_Switches}: list
22305
22306Value is the list of switches to specify a response file to the linker.
22307@end itemize
22308@end itemize
22309
22310@c only PRO or GPL
22311@c
22312@c .. _Package_Metrics_Attribute:
22313@c
22314@c Package Metrics Attribute
22315@c ^^^^^^^^^^^^^^^^^^^^^^^^^
22316@c
22317@c * **Default_Switches**: list, indexed, case-insensitive index
22318@c
22319@c   Index is a language name. Value is a list of switches to be used when invoking
22320@c   `gnatmetric` for a source of the language, if there is no applicable
22321@c   attribute Switches.
22322@c
22323@c * **Switches**: list, optional index, indexed, case-insensitive index,
22324@c   others allowed
22325@c
22326@c   Index is a source file name. Value is the list of switches to be used when
22327@c   invoking `gnatmetric` for the source.
22328
22329@node Package Naming Attributes,Package Remote Attributes,Package Linker Attributes,Attributes
22330@anchor{gnat_ugn/gnat_project_manager package-naming-attributes}@anchor{1bd}@anchor{gnat_ugn/gnat_project_manager id61}@anchor{1be}
22331@subsubsection Package Naming Attributes
22332
22333
22334
22335@itemize *
22336
22337@item
22338@strong{Specification_Suffix}: single, indexed, case-insensitive index
22339
22340Equivalent to attribute Spec_Suffix.
22341
22342@item
22343@strong{Spec_Suffix}: single, indexed, case-insensitive index
22344
22345Index is a language name. Value is the extension of file names for specs of
22346the language.
22347
22348@item
22349@strong{Implementation_Suffix}: single, indexed, case-insensitive index
22350
22351Equivalent to attribute Body_Suffix.
22352
22353@item
22354@strong{Body_Suffix}: single, indexed, case-insensitive index
22355
22356Index is a language name. Value is the extension of file names for bodies of
22357the language.
22358
22359@item
22360@strong{Separate_Suffix}: single
22361
22362Value is the extension of file names for subunits of Ada.
22363
22364@item
22365@strong{Casing}: single
22366
22367Indicates the casing of sources of the Ada language. Only authorized
22368case-insensitive values are "lowercase", "uppercase" and "mixedcase".
22369
22370@item
22371@strong{Dot_Replacement}: single
22372
22373Value is the string that replace the dot of unit names in the source file names
22374of the Ada language.
22375
22376@item
22377@strong{Specification}: single, optional index, indexed,
22378case-insensitive index
22379
22380Equivalent to attribute Spec.
22381
22382@item
22383@strong{Spec}: single, optional index, indexed, case-insensitive index
22384
22385Index is a unit name. Value is the file name of the spec of the unit.
22386
22387@item
22388@strong{Implementation}: single, optional index, indexed,
22389case-insensitive index
22390
22391Equivalent to attribute Body.
22392
22393@item
22394@strong{Body}: single, optional index, indexed, case-insensitive index
22395
22396Index is a unit name. Value is the file name of the body of the unit.
22397
22398@item
22399@strong{Specification_Exceptions}: list, indexed, case-insensitive index
22400
22401Index is a language name. Value is a list of specs for the language that do not
22402necessarily follow the naming scheme for the language and that may or may not
22403be found in the source directories of the project.
22404
22405@item
22406@strong{Implementation_Exceptions}: list, indexed, case-insensitive index
22407
22408Index is a language name. Value is a list of bodies for the language that do not
22409necessarily follow the naming scheme for the language and that may or may not
22410be found in the source directories of the project.
22411@end itemize
22412
22413
22414@node Package Remote Attributes,Package Stack Attributes,Package Naming Attributes,Attributes
22415@anchor{gnat_ugn/gnat_project_manager package-remote-attributes}@anchor{1bf}@anchor{gnat_ugn/gnat_project_manager id63}@anchor{1c0}
22416@subsubsection Package Remote Attributes
22417
22418
22419
22420@itemize *
22421
22422@item
22423@strong{Included_Patterns}: list
22424
22425If this attribute is defined it sets the patterns to
22426synchronized from the master to the slaves. It is exclusive
22427with Excluded_Patterns, that is it is an error to define
22428both.
22429
22430@item
22431@strong{Included_Artifact_Patterns}: list
22432
22433If this attribute is defined it sets the patterns of compilation
22434artifacts to synchronized from the slaves to the build master.
22435This attribute replace the default hard-coded patterns.
22436
22437@item
22438@strong{Excluded_Patterns}: list
22439
22440Set of patterns to ignore when synchronizing sources from the build
22441master to the slaves. A set of predefined patterns are supported
22442(e.g. *.o, *.ali, *.exe, etc.), this attributes make it possible to
22443add some more patterns.
22444
22445@item
22446@strong{Root_Dir}: single
22447
22448Value is the root directory used by the slave machines.
22449@end itemize
22450
22451@node Package Stack Attributes,Package Synchronize Attributes,Package Remote Attributes,Attributes
22452@anchor{gnat_ugn/gnat_project_manager id64}@anchor{1c1}@anchor{gnat_ugn/gnat_project_manager package-stack-attributes}@anchor{1c2}
22453@subsubsection Package Stack Attributes
22454
22455
22456
22457@itemize *
22458
22459@item
22460@strong{Switches}: list
22461
22462Value is the list of switches to be used when invoking @cite{gnatstack}.
22463@end itemize
22464
22465@node Package Synchronize Attributes,,Package Stack Attributes,Attributes
22466@anchor{gnat_ugn/gnat_project_manager package-synchronize-attributes}@anchor{1c3}
22467@subsubsection Package Synchronize Attributes
22468
22469
22470
22471@itemize *
22472
22473@item
22474@strong{Default_Switches}: list, indexed, case-insensitive index
22475
22476Index is a language name. Value is a list of switches to be used when invoking
22477@cite{gnatsync} for a source of the language, if there is no applicable
22478attribute Switches.
22479
22480@item
22481@strong{Switches}: list, optional index, indexed, case-insensitive index,
22482others allowed
22483
22484Index is a source file name. Value is the list of switches to be used when
22485invoking @cite{gnatsync} for the source.
22486@end itemize
22487
22488@node Tools Supporting Project Files,GNAT Utility Programs,GNAT Project Manager,Top
22489@anchor{gnat_ugn/tools_supporting_project_files doc}@anchor{1c4}@anchor{gnat_ugn/tools_supporting_project_files tools-supporting-project-files}@anchor{c}@anchor{gnat_ugn/tools_supporting_project_files id1}@anchor{1c5}
22490@chapter Tools Supporting Project Files
22491
22492
22493This section describes how project files can be used in conjunction with a number of
22494GNAT tools.
22495
22496@menu
22497* gnatmake and Project Files::
22498* The GNAT Driver and Project Files::
22499
22500@end menu
22501
22502@node gnatmake and Project Files,The GNAT Driver and Project Files,,Tools Supporting Project Files
22503@anchor{gnat_ugn/tools_supporting_project_files id2}@anchor{1c6}@anchor{gnat_ugn/tools_supporting_project_files gnatmake-and-project-files}@anchor{e4}
22504@section gnatmake and Project Files
22505
22506
22507This section covers several topics related to @emph{gnatmake} and
22508project files: defining switches for @emph{gnatmake}
22509and for the tools that it invokes; specifying configuration pragmas;
22510the use of the @cite{Main} attribute; building and rebuilding library project
22511files.
22512
22513@menu
22514* Switches Related to Project Files::
22515* Switches and Project Files::
22516* Specifying Configuration Pragmas::
22517* Project Files and Main Subprograms::
22518* Library Project Files::
22519
22520@end menu
22521
22522@node Switches Related to Project Files,Switches and Project Files,,gnatmake and Project Files
22523@anchor{gnat_ugn/tools_supporting_project_files switches-related-to-project-files}@anchor{e6}@anchor{gnat_ugn/tools_supporting_project_files id3}@anchor{1c7}
22524@subsection Switches Related to Project Files
22525
22526
22527The following switches are used by GNAT tools that support project files:
22528
22529@quotation
22530
22531@geindex -P (any project-aware tool)
22532@end quotation
22533
22534
22535@table @asis
22536
22537@item @code{-P@emph{project}}
22538
22539Indicates the name of a project file. This project file will be parsed with
22540the verbosity indicated by @emph{-vP*x*},
22541if any, and using the external references indicated
22542by @emph{-X} switches, if any.
22543There may zero, one or more spaces between @emph{-P} and @cite{project}.
22544
22545There must be only one @emph{-P} switch on the command line.
22546
22547Since the Project Manager parses the project file only after all the switches
22548on the command line are checked, the order of the switches
22549@emph{-P},
22550@emph{-vP*x*}
22551or @emph{-X} is not significant.
22552
22553@geindex -X (any project-aware tool)
22554
22555@item @code{-X@emph{name}=@emph{value}}
22556
22557Indicates that external variable @cite{name} has the value @cite{value}.
22558The Project Manager will use this value for occurrences of
22559@cite{external(name)} when parsing the project file.
22560
22561If @cite{name} or @cite{value} includes a space, then @cite{name=value} should be
22562put between quotes.
22563
22564@example
22565-XOS=NT
22566-X"user=John Doe"
22567@end example
22568
22569Several @emph{-X} switches can be used simultaneously.
22570If several @emph{-X} switches specify the same
22571@cite{name}, only the last one is used.
22572
22573An external variable specified with a @emph{-X} switch
22574takes precedence over the value of the same name in the environment.
22575
22576@geindex -vP (any project-aware tool)
22577
22578@item @code{-vP@emph{x}}
22579
22580Indicates the verbosity of the parsing of GNAT project files.
22581
22582@emph{-vP0} means Default;
22583@emph{-vP1} means Medium;
22584@emph{-vP2} means High.
22585
22586The default is Default: no output for syntactically correct
22587project files.
22588If several @emph{-vP*x*} switches are present,
22589only the last one is used.
22590
22591@geindex -aP (any project-aware tool)
22592
22593@item @code{-aP@emph{dir}}
22594
22595Add directory @cite{dir} at the beginning of the project search path, in order,
22596after the current working directory.
22597
22598@geindex -eL (any project-aware tool)
22599
22600@item @code{-eL}
22601
22602Follow all symbolic links when processing project files.
22603
22604@geindex --subdirs= (gnatmake and gnatclean)
22605
22606@item @code{--subdirs=@emph{subdir}}
22607
22608This switch is recognized by @emph{gnatmake} and @emph{gnatclean}. It
22609indicate that the real directories (except the source directories) are the
22610subdirectories @cite{subdir} of the directories specified in the project files.
22611This applies in particular to object directories, library directories and
22612exec directories. If the subdirectories do not exist, they are created
22613automatically.
22614@end table
22615
22616@node Switches and Project Files,Specifying Configuration Pragmas,Switches Related to Project Files,gnatmake and Project Files
22617@anchor{gnat_ugn/tools_supporting_project_files id4}@anchor{1c8}@anchor{gnat_ugn/tools_supporting_project_files switches-and-project-files}@anchor{1c9}
22618@subsection Switches and Project Files
22619
22620
22621For each of the packages @cite{Builder}, @cite{Compiler}, @cite{Binder}, and
22622@cite{Linker}, you can specify a @cite{Default_Switches}
22623attribute, a @cite{Switches} attribute, or both;
22624as their names imply, these switch-related
22625attributes affect the switches that are used for each of these GNAT
22626components when
22627@emph{gnatmake} is invoked.  As will be explained below, these
22628component-specific switches precede
22629the switches provided on the @emph{gnatmake} command line.
22630
22631The @cite{Default_Switches} attribute is an attribute
22632indexed by language name (case insensitive) whose value is a string list.
22633For example:
22634
22635@quotation
22636
22637@example
22638package Compiler is
22639  for Default_Switches ("Ada")
22640      use ("-gnaty",
22641           "-v");
22642end Compiler;
22643@end example
22644@end quotation
22645
22646The @cite{Switches} attribute is indexed on a file name (which may or may
22647not be case sensitive, depending
22648on the operating system) whose value is a string list.  For example:
22649
22650@quotation
22651
22652@example
22653package Builder is
22654   for Switches ("main1.adb")
22655       use ("-O2");
22656   for Switches ("main2.adb")
22657       use ("-g");
22658end Builder;
22659@end example
22660@end quotation
22661
22662For the @cite{Builder} package, the file names must designate source files
22663for main subprograms.  For the @cite{Binder} and @cite{Linker} packages, the
22664file names must designate @code{ALI} or source files for main subprograms.
22665In each case just the file name without an explicit extension is acceptable.
22666
22667For each tool used in a program build (@emph{gnatmake}, the compiler, the
22668binder, and the linker), the corresponding package @@dfn@{contributes@} a set of
22669switches for each file on which the tool is invoked, based on the
22670switch-related attributes defined in the package.
22671In particular, the switches
22672that each of these packages contributes for a given file @cite{f} comprise:
22673
22674
22675@itemize *
22676
22677@item
22678the value of attribute @cite{Switches (`f})`,
22679if it is specified in the package for the given file,
22680
22681@item
22682otherwise, the value of @cite{Default_Switches ("Ada")},
22683if it is specified in the package.
22684@end itemize
22685
22686If neither of these attributes is defined in the package, then the package does
22687not contribute any switches for the given file.
22688
22689When @emph{gnatmake} is invoked on a file, the switches comprise
22690two sets, in the following order: those contributed for the file
22691by the @cite{Builder} package;
22692and the switches passed on the command line.
22693
22694When @emph{gnatmake} invokes a tool (compiler, binder, linker) on a file,
22695the switches passed to the tool comprise three sets,
22696in the following order:
22697
22698
22699@itemize *
22700
22701@item
22702the applicable switches contributed for the file
22703by the @cite{Builder} package in the project file supplied on the command line;
22704
22705@item
22706those contributed for the file by the package (in the relevant project file --
22707see below) corresponding to the tool; and
22708
22709@item
22710the applicable switches passed on the command line.
22711@end itemize
22712
22713The term @emph{applicable switches} reflects the fact that
22714@emph{gnatmake} switches may or may not be passed to individual
22715tools, depending on the individual switch.
22716
22717@emph{gnatmake} may invoke the compiler on source files from different
22718projects. The Project Manager will use the appropriate project file to
22719determine the @cite{Compiler} package for each source file being compiled.
22720Likewise for the @cite{Binder} and @cite{Linker} packages.
22721
22722As an example, consider the following package in a project file:
22723
22724@quotation
22725
22726@example
22727project Proj1 is
22728   package Compiler is
22729      for Default_Switches ("Ada")
22730          use ("-g");
22731      for Switches ("a.adb")
22732          use ("-O1");
22733      for Switches ("b.adb")
22734          use ("-O2",
22735               "-gnaty");
22736   end Compiler;
22737end Proj1;
22738@end example
22739@end quotation
22740
22741If @emph{gnatmake} is invoked with this project file, and it needs to
22742compile, say, the files @code{a.adb}, @code{b.adb}, and @code{c.adb}, then
22743@code{a.adb} will be compiled with the switch @emph{-O1},
22744@code{b.adb} with switches @emph{-O2} and @emph{-gnaty},
22745and @code{c.adb} with @emph{-g}.
22746
22747The following example illustrates the ordering of the switches
22748contributed by different packages:
22749
22750@quotation
22751
22752@example
22753project Proj2 is
22754   package Builder is
22755      for Switches ("main.adb")
22756          use ("-g",
22757               "-O1",
22758               "-f");
22759   end Builder;
22760
22761   package Compiler is
22762      for Switches ("main.adb")
22763          use ("-O2");
22764   end Compiler;
22765end Proj2;
22766@end example
22767@end quotation
22768
22769If you issue the command:
22770
22771@quotation
22772
22773@example
22774$ gnatmake -Pproj2 -O0 main
22775@end example
22776@end quotation
22777
22778then the compiler will be invoked on @code{main.adb} with the following
22779sequence of switches
22780
22781@quotation
22782
22783@example
22784-g -O1 -O2 -O0
22785@end example
22786@end quotation
22787
22788with the last @emph{-O}
22789switch having precedence over the earlier ones;
22790several other switches
22791(such as @emph{-c}) are added implicitly.
22792
22793The switches @emph{-g}
22794and @emph{-O1} are contributed by package
22795@cite{Builder},  @emph{-O2} is contributed
22796by the package @cite{Compiler}
22797and @emph{-O0} comes from the command line.
22798
22799The @emph{-g} switch will also be passed in the invocation of
22800@emph{Gnatlink.}
22801
22802A final example illustrates switch contributions from packages in different
22803project files:
22804
22805@quotation
22806
22807@example
22808project Proj3 is
22809   for Source_Files use ("pack.ads", "pack.adb");
22810   package Compiler is
22811      for Default_Switches ("Ada")
22812          use ("-gnata");
22813   end Compiler;
22814end Proj3;
22815
22816with "Proj3";
22817project Proj4 is
22818   for Source_Files use ("foo_main.adb", "bar_main.adb");
22819   package Builder is
22820      for Switches ("foo_main.adb")
22821          use ("-s",
22822               "-g");
22823   end Builder;
22824end Proj4;
22825@end example
22826
22827@example
22828-- Ada source file:
22829with Pack;
22830procedure Foo_Main is
22831   ...
22832end Foo_Main;
22833@end example
22834@end quotation
22835
22836If the command is
22837
22838@quotation
22839
22840@example
22841$ gnatmake -PProj4 foo_main.adb -cargs -gnato
22842@end example
22843@end quotation
22844
22845then the switches passed to the compiler for @code{foo_main.adb} are
22846@emph{-g} (contributed by the package @cite{Proj4.Builder}) and
22847@emph{-gnato} (passed on the command line).
22848When the imported package @cite{Pack} is compiled, the switches used
22849are @emph{-g} from @cite{Proj4.Builder},
22850@emph{-gnata} (contributed from package @cite{Proj3.Compiler},
22851and @emph{-gnato} from the command line.
22852
22853When using @emph{gnatmake} with project files, some switches or
22854arguments may be expressed as relative paths. As the working directory where
22855compilation occurs may change, these relative paths are converted to absolute
22856paths. For the switches found in a project file, the relative paths
22857are relative to the project file directory, for the switches on the command
22858line, they are relative to the directory where @emph{gnatmake} is invoked.
22859The switches for which this occurs are:
22860-I,
22861-A,
22862-L,
22863-aO,
22864-aL,
22865-aI, as well as all arguments that are not switches (arguments to
22866switch
22867-o, object files specified in package @cite{Linker} or after
22868-largs on the command line). The exception to this rule is the switch
22869--RTS= for which a relative path argument is never converted.
22870
22871@node Specifying Configuration Pragmas,Project Files and Main Subprograms,Switches and Project Files,gnatmake and Project Files
22872@anchor{gnat_ugn/tools_supporting_project_files id5}@anchor{1ca}@anchor{gnat_ugn/tools_supporting_project_files specifying-configuration-pragmas}@anchor{7d}
22873@subsection Specifying Configuration Pragmas
22874
22875
22876When using @emph{gnatmake} with project files, if there exists a file
22877@code{gnat.adc} that contains configuration pragmas, this file will be
22878ignored.
22879
22880Configuration pragmas can be defined by means of the following attributes in
22881project files: @cite{Global_Configuration_Pragmas} in package @cite{Builder}
22882and @cite{Local_Configuration_Pragmas} in package @cite{Compiler}.
22883
22884Both these attributes are single string attributes. Their values is the path
22885name of a file containing configuration pragmas. If a path name is relative,
22886then it is relative to the project directory of the project file where the
22887attribute is defined.
22888
22889When compiling a source, the configuration pragmas used are, in order,
22890those listed in the file designated by attribute
22891@cite{Global_Configuration_Pragmas} in package @cite{Builder} of the main
22892project file, if it is specified, and those listed in the file designated by
22893attribute @cite{Local_Configuration_Pragmas} in package @cite{Compiler} of
22894the project file of the source, if it exists.
22895
22896@node Project Files and Main Subprograms,Library Project Files,Specifying Configuration Pragmas,gnatmake and Project Files
22897@anchor{gnat_ugn/tools_supporting_project_files id6}@anchor{1cb}@anchor{gnat_ugn/tools_supporting_project_files project-files-and-main-subprograms}@anchor{e5}
22898@subsection Project Files and Main Subprograms
22899
22900
22901When using a project file, you can invoke @emph{gnatmake}
22902with one or several main subprograms, by specifying their source files on the
22903command line.
22904
22905@quotation
22906
22907@example
22908$ gnatmake -Pprj main1.adb main2.adb main3.adb
22909@end example
22910@end quotation
22911
22912Each of these needs to be a source file of the same project, except
22913when the switch @cite{-u} is used.
22914
22915When @cite{-u} is not used, all the mains need to be sources of the
22916same project, one of the project in the tree rooted at the project specified
22917on the command line. The package @cite{Builder} of this common project, the
22918"main project" is the one that is considered by @emph{gnatmake}.
22919
22920When @cite{-u} is used, the specified source files may be in projects
22921imported directly or indirectly by the project specified on the command line.
22922Note that if such a source file is not part of the project specified on the
22923command line, the switches found in package @cite{Builder} of the
22924project specified on the command line, if any, that are transmitted
22925to the compiler will still be used, not those found in the project file of
22926the source file.
22927
22928When using a project file, you can also invoke @emph{gnatmake} without
22929explicitly specifying any main, and the effect depends on whether you have
22930defined the @cite{Main} attribute.  This attribute has a string list value,
22931where each element in the list is the name of a source file (the file
22932extension is optional) that contains a unit that can be a main subprogram.
22933
22934If the @cite{Main} attribute is defined in a project file as a non-empty
22935string list and the switch @emph{-u} is not used on the command
22936line, then invoking @emph{gnatmake} with this project file but without any
22937main on the command line is equivalent to invoking @emph{gnatmake} with all
22938the file names in the @cite{Main} attribute on the command line.
22939
22940Example:
22941
22942@quotation
22943
22944@example
22945project Prj is
22946   for Main use ("main1.adb", "main2.adb", "main3.adb");
22947end Prj;
22948@end example
22949@end quotation
22950
22951With this project file, @cite{"gnatmake -Pprj"}
22952is equivalent to
22953@cite{"gnatmake -Pprj main1.adb main2.adb main3.adb"}.
22954
22955When the project attribute @cite{Main} is not specified, or is specified
22956as an empty string list, or when the switch @emph{-u} is used on the command
22957line, then invoking @emph{gnatmake} with no main on the command line will
22958result in all immediate sources of the project file being checked, and
22959potentially recompiled. Depending on the presence of the switch @emph{-u},
22960sources from other project files on which the immediate sources of the main
22961project file depend are also checked and potentially recompiled. In other
22962words, the @emph{-u} switch is applied to all of the immediate sources of the
22963main project file.
22964
22965When no main is specified on the command line and attribute @cite{Main} exists
22966and includes several mains, or when several mains are specified on the
22967command line, the default switches in package @cite{Builder} will
22968be used for all mains, even if there are specific switches
22969specified for one or several mains.
22970
22971But the switches from package @cite{Binder} or @cite{Linker} will be
22972the specific switches for each main, if they are specified.
22973
22974@node Library Project Files,,Project Files and Main Subprograms,gnatmake and Project Files
22975@anchor{gnat_ugn/tools_supporting_project_files id7}@anchor{1cc}@anchor{gnat_ugn/tools_supporting_project_files library-project-files}@anchor{1cd}
22976@subsection Library Project Files
22977
22978
22979When @emph{gnatmake} is invoked with a main project file that is a library
22980project file, it is not allowed to specify one or more mains on the command
22981line.
22982
22983When a library project file is specified, switches @cite{-b} and
22984@cite{-l} have special meanings.
22985
22986
22987@itemize *
22988
22989@item
22990@cite{-b} is only allowed for stand-alone libraries. It indicates
22991to @emph{gnatmake} that @emph{gnatbind} should be invoked for the
22992library.
22993
22994@item
22995@cite{-l} may be used for all library projects. It indicates
22996to @emph{gnatmake} that the binder generated file should be compiled
22997(in the case of a stand-alone library) and that the library should be built.
22998@end itemize
22999
23000@node The GNAT Driver and Project Files,,gnatmake and Project Files,Tools Supporting Project Files
23001@anchor{gnat_ugn/tools_supporting_project_files id8}@anchor{1ce}@anchor{gnat_ugn/tools_supporting_project_files the-gnat-driver-and-project-files}@anchor{122}
23002@section The GNAT Driver and Project Files
23003
23004
23005A number of GNAT tools beyond @emph{gnatmake}
23006can benefit from project files:
23007
23008
23009
23010@itemize *
23011
23012@item
23013@emph{gnatbind}
23014
23015@item
23016@emph{gnatclean}
23017
23018@item
23019@emph{gnatfind}
23020
23021@item
23022@emph{gnatlink}
23023
23024@item
23025@emph{gnatls}
23026
23027@item
23028@emph{gnatxref}
23029@end itemize
23030
23031However, none of these tools can be invoked
23032directly with a project file switch (@emph{-P}).
23033They must be invoked through the @emph{gnat} driver.
23034
23035The @emph{gnat} driver is a wrapper that accepts a number of commands and
23036calls the corresponding tool. It was designed initially for VMS platforms (to
23037convert VMS qualifiers to Unix-style switches), but it is now available on all
23038GNAT platforms.
23039
23040On non-VMS platforms, the @emph{gnat} driver accepts the following commands
23041(case insensitive):
23042
23043
23044
23045@itemize *
23046
23047@item
23048BIND to invoke @emph{gnatbind}
23049
23050@item
23051CHOP to invoke @emph{gnatchop}
23052
23053@item
23054CLEAN to invoke @emph{gnatclean}
23055
23056@item
23057COMP or COMPILE to invoke the compiler
23058
23059@item
23060FIND to invoke @emph{gnatfind}
23061
23062@item
23063KR or KRUNCH to invoke @emph{gnatkr}
23064
23065@item
23066LINK to invoke @emph{gnatlink}
23067
23068@item
23069LS or LIST to invoke @emph{gnatls}
23070
23071@item
23072MAKE to invoke @emph{gnatmake}
23073
23074@item
23075NAME to invoke @emph{gnatname}
23076
23077@item
23078PREP or PREPROCESS to invoke @emph{gnatprep}
23079
23080@item
23081XREF to invoke @emph{gnatxref}
23082@end itemize
23083
23084Note that the command
23085@emph{gnatmake -c -f -u} is used to invoke the compiler.
23086
23087On non-VMS platforms, between @emph{gnat} and the command, two
23088special switches may be used:
23089
23090
23091@itemize *
23092
23093@item
23094@emph{-v} to display the invocation of the tool.
23095
23096@item
23097@emph{-dn} to prevent the @emph{gnat} driver from removing
23098the temporary files it has created. These temporary files are
23099configuration files and temporary file list files.
23100@end itemize
23101
23102The command may be followed by switches and arguments for the invoked
23103tool.
23104
23105@quotation
23106
23107@example
23108$ gnat bind -C main.ali
23109$ gnat ls -a main
23110$ gnat chop foo.txt
23111@end example
23112@end quotation
23113
23114Switches may also be put in text files, one switch per line, and the text
23115files may be specified with their path name preceded by '@@'.
23116
23117@quotation
23118
23119@example
23120$ gnat bind @@args.txt main.ali
23121@end example
23122@end quotation
23123
23124In addition, for the following commands the project file related switches
23125(@emph{-P}, @emph{-X} and @emph{-vPx}) may be used in addition to
23126the switches of the invoking tool:
23127
23128
23129
23130@itemize *
23131
23132@item
23133BIND
23134
23135@item
23136COMP or COMPILE
23137
23138@item
23139FIND
23140
23141@item
23142LS or LIST
23143
23144@item
23145LINK
23146
23147@item
23148XREF
23149@end itemize
23150
23151
23152For each of the following commands, there is optionally a corresponding
23153package in the main project.
23154
23155
23156
23157@itemize *
23158
23159@item
23160package @cite{Binder} for command BIND (invoking @cite{gnatbind})
23161
23162@item
23163package @cite{Compiler} for command COMP or COMPILE (invoking the compiler)
23164
23165@item
23166package @cite{Cross_Reference} for command XREF (invoking @cite{gnatxref})
23167
23168@item
23169package @cite{Finder} for command FIND (invoking @cite{gnatfind})
23170
23171@item
23172package @cite{Gnatls} for command LS or LIST (invoking @cite{gnatls})
23173
23174@item
23175package @cite{Linker} for command LINK (invoking @cite{gnatlink})
23176@end itemize
23177
23178Package @cite{Gnatls} has a unique attribute @cite{Switches},
23179a simple variable with a string list value. It contains switches
23180for the invocation of @cite{gnatls}.
23181
23182@quotation
23183
23184@example
23185project Proj1 is
23186   package gnatls is
23187      for Switches
23188          use ("-a",
23189               "-v");
23190   end gnatls;
23191end Proj1;
23192@end example
23193@end quotation
23194
23195All other packages have two attribute @cite{Switches} and
23196@cite{Default_Switches}.
23197
23198@cite{Switches} is an indexed attribute, indexed by the
23199source file name, that has a string list value: the switches to be
23200used when the tool corresponding to the package is invoked for the specific
23201source file.
23202
23203@cite{Default_Switches} is an attribute,
23204indexed by  the programming language that has a string list value.
23205@cite{Default_Switches ("Ada")} contains the
23206switches for the invocation of the tool corresponding
23207to the package, except if a specific @cite{Switches} attribute
23208is specified for the source file.
23209
23210@quotation
23211
23212@example
23213project Proj is
23214
23215   for Source_Dirs use ("");
23216
23217   package gnatls is
23218      for Switches use
23219          ("-a",
23220           "-v");
23221   end gnatls;
23222
23223   package Compiler is
23224      for Default_Switches ("Ada")
23225          use ("-gnatv",
23226               "-gnatwa");
23227   end Binder;
23228
23229   package Binder is
23230      for Default_Switches ("Ada")
23231          use ("-C",
23232               "-e");
23233   end Binder;
23234
23235   package Linker is
23236      for Default_Switches ("Ada")
23237          use ("-C");
23238      for Switches ("main.adb")
23239          use ("-C",
23240               "-v",
23241               "-v");
23242   end Linker;
23243
23244   package Finder is
23245      for Default_Switches ("Ada")
23246           use ("-a",
23247                "-f");
23248   end Finder;
23249
23250   package Cross_Reference is
23251      for Default_Switches ("Ada")
23252          use ("-a",
23253               "-f",
23254               "-d",
23255               "-u");
23256   end Cross_Reference;
23257end Proj;
23258@end example
23259@end quotation
23260
23261With the above project file, commands such as
23262
23263@quotation
23264
23265@example
23266$ gnat comp -Pproj main
23267$ gnat ls -Pproj main
23268$ gnat xref -Pproj main
23269$ gnat bind -Pproj main.ali
23270$ gnat link -Pproj main.ali
23271@end example
23272@end quotation
23273
23274will set up the environment properly and invoke the tool with the switches
23275found in the package corresponding to the tool:
23276@cite{Default_Switches ("Ada")} for all tools,
23277except @cite{Switches ("main.adb")}
23278for @cite{gnatlink}.
23279
23280
23281@node GNAT Utility Programs,GNAT and Program Execution,Tools Supporting Project Files,Top
23282@anchor{gnat_ugn/gnat_utility_programs doc}@anchor{1cf}@anchor{gnat_ugn/gnat_utility_programs gnat-utility-programs}@anchor{d}@anchor{gnat_ugn/gnat_utility_programs id1}@anchor{1d0}
23283@chapter GNAT Utility Programs
23284
23285
23286This chapter describes a number of utility programs:
23287
23288
23289
23290@itemize *
23291
23292@item
23293@ref{22,,The File Cleanup Utility gnatclean}
23294
23295@item
23296@ref{23,,The GNAT Library Browser gnatls}
23297
23298@item
23299@ref{24,,The Cross-Referencing Tools gnatxref and gnatfind}
23300
23301@item
23302@ref{25,,The Ada to HTML Converter gnathtml}
23303@end itemize
23304
23305Other GNAT utilities are described elsewhere in this manual:
23306
23307
23308@itemize *
23309
23310@item
23311@ref{5b,,Handling Arbitrary File Naming Conventions with gnatname}
23312
23313@item
23314@ref{65,,File Name Krunching with gnatkr}
23315
23316@item
23317@ref{38,,Renaming Files with gnatchop}
23318
23319@item
23320@ref{19,,Preprocessing with gnatprep}
23321@end itemize
23322
23323@menu
23324* The File Cleanup Utility gnatclean::
23325* The GNAT Library Browser gnatls::
23326* The Cross-Referencing Tools gnatxref and gnatfind::
23327* The Ada to HTML Converter gnathtml::
23328
23329@end menu
23330
23331@node The File Cleanup Utility gnatclean,The GNAT Library Browser gnatls,,GNAT Utility Programs
23332@anchor{gnat_ugn/gnat_utility_programs id2}@anchor{1d1}@anchor{gnat_ugn/gnat_utility_programs the-file-cleanup-utility-gnatclean}@anchor{22}
23333@section The File Cleanup Utility @emph{gnatclean}
23334
23335
23336@geindex File cleanup tool
23337
23338@geindex gnatclean
23339
23340@cite{gnatclean} is a tool that allows the deletion of files produced by the
23341compiler, binder and linker, including ALI files, object files, tree files,
23342expanded source files, library files, interface copy source files, binder
23343generated files and executable files.
23344
23345@menu
23346* Running gnatclean::
23347* Switches for gnatclean::
23348
23349@end menu
23350
23351@node Running gnatclean,Switches for gnatclean,,The File Cleanup Utility gnatclean
23352@anchor{gnat_ugn/gnat_utility_programs running-gnatclean}@anchor{1d2}@anchor{gnat_ugn/gnat_utility_programs id3}@anchor{1d3}
23353@subsection Running @cite{gnatclean}
23354
23355
23356The @cite{gnatclean} command has the form:
23357
23358@quotation
23359
23360@example
23361$ gnatclean switches `names`
23362@end example
23363@end quotation
23364
23365where @cite{names} is a list of source file names. Suffixes @code{.ads} and
23366@code{adb} may be omitted. If a project file is specified using switch
23367@code{-P}, then @cite{names} may be completely omitted.
23368
23369In normal mode, @cite{gnatclean} delete the files produced by the compiler and,
23370if switch @cite{-c} is not specified, by the binder and
23371the linker. In informative-only mode, specified by switch
23372@cite{-n}, the list of files that would have been deleted in
23373normal mode is listed, but no file is actually deleted.
23374
23375@node Switches for gnatclean,,Running gnatclean,The File Cleanup Utility gnatclean
23376@anchor{gnat_ugn/gnat_utility_programs id4}@anchor{1d4}@anchor{gnat_ugn/gnat_utility_programs switches-for-gnatclean}@anchor{1d5}
23377@subsection Switches for @cite{gnatclean}
23378
23379
23380@cite{gnatclean} recognizes the following switches:
23381
23382@geindex --version (gnatclean)
23383
23384
23385@table @asis
23386
23387@item @code{--version}
23388
23389Display Copyright and version, then exit disregarding all other options.
23390@end table
23391
23392@geindex --help (gnatclean)
23393
23394
23395@table @asis
23396
23397@item @code{--help}
23398
23399If @emph{--version} was not used, display usage, then exit disregarding
23400all other options.
23401
23402@item @code{--subdirs=@emph{subdir}}
23403
23404Actual object directory of each project file is the subdirectory subdir of the
23405object directory specified or defaulted in the project file.
23406
23407@item @code{--unchecked-shared-lib-imports}
23408
23409By default, shared library projects are not allowed to import static library
23410projects. When this switch is used on the command line, this restriction is
23411relaxed.
23412@end table
23413
23414@geindex -c (gnatclean)
23415
23416
23417@table @asis
23418
23419@item @code{-c}
23420
23421Only attempt to delete the files produced by the compiler, not those produced
23422by the binder or the linker. The files that are not to be deleted are library
23423files, interface copy files, binder generated files and executable files.
23424@end table
23425
23426@geindex -D (gnatclean)
23427
23428
23429@table @asis
23430
23431@item @code{-D @emph{dir}}
23432
23433Indicate that ALI and object files should normally be found in directory @cite{dir}.
23434@end table
23435
23436@geindex -F (gnatclean)
23437
23438
23439@table @asis
23440
23441@item @code{-F}
23442
23443When using project files, if some errors or warnings are detected during
23444parsing and verbose mode is not in effect (no use of switch
23445-v), then error lines start with the full path name of the project
23446file, rather than its simple file name.
23447@end table
23448
23449@geindex -h (gnatclean)
23450
23451
23452@table @asis
23453
23454@item @code{-h}
23455
23456Output a message explaining the usage of @cite{gnatclean}.
23457@end table
23458
23459@geindex -n (gnatclean)
23460
23461
23462@table @asis
23463
23464@item @code{-n}
23465
23466Informative-only mode. Do not delete any files. Output the list of the files
23467that would have been deleted if this switch was not specified.
23468@end table
23469
23470@geindex -P (gnatclean)
23471
23472
23473@table @asis
23474
23475@item @code{-P@emph{project}}
23476
23477Use project file @cite{project}. Only one such switch can be used.
23478When cleaning a project file, the files produced by the compilation of the
23479immediate sources or inherited sources of the project files are to be
23480deleted. This is not depending on the presence or not of executable names
23481on the command line.
23482@end table
23483
23484@geindex -q (gnatclean)
23485
23486
23487@table @asis
23488
23489@item @code{-q}
23490
23491Quiet output. If there are no errors, do not output anything, except in
23492verbose mode (switch -v) or in informative-only mode
23493(switch -n).
23494@end table
23495
23496@geindex -r (gnatclean)
23497
23498
23499@table @asis
23500
23501@item @code{-r}
23502
23503When a project file is specified (using switch -P),
23504clean all imported and extended project files, recursively. If this switch
23505is not specified, only the files related to the main project file are to be
23506deleted. This switch has no effect if no project file is specified.
23507@end table
23508
23509@geindex -v (gnatclean)
23510
23511
23512@table @asis
23513
23514@item @code{-v}
23515
23516Verbose mode.
23517@end table
23518
23519@geindex -vP (gnatclean)
23520
23521
23522@table @asis
23523
23524@item @code{-vP@emph{x}}
23525
23526Indicates the verbosity of the parsing of GNAT project files.
23527@ref{e6,,Switches Related to Project Files}.
23528@end table
23529
23530@geindex -X (gnatclean)
23531
23532
23533@table @asis
23534
23535@item @code{-X@emph{name}=@emph{value}}
23536
23537Indicates that external variable @cite{name} has the value @cite{value}.
23538The Project Manager will use this value for occurrences of
23539@cite{external(name)} when parsing the project file.
23540@ref{e6,,Switches Related to Project Files}.
23541@end table
23542
23543@geindex -aO (gnatclean)
23544
23545
23546@table @asis
23547
23548@item @code{-aO@emph{dir}}
23549
23550When searching for ALI and object files, look in directory @cite{dir}.
23551@end table
23552
23553@geindex -I (gnatclean)
23554
23555
23556@table @asis
23557
23558@item @code{-I@emph{dir}}
23559
23560Equivalent to @code{-aO@emph{dir}}.
23561@end table
23562
23563@geindex -I- (gnatclean)
23564
23565@geindex Source files
23566@geindex suppressing search
23567
23568
23569@table @asis
23570
23571@item @code{-I-}
23572
23573Do not look for ALI or object files in the directory
23574where @cite{gnatclean} was invoked.
23575@end table
23576
23577@node The GNAT Library Browser gnatls,The Cross-Referencing Tools gnatxref and gnatfind,The File Cleanup Utility gnatclean,GNAT Utility Programs
23578@anchor{gnat_ugn/gnat_utility_programs the-gnat-library-browser-gnatls}@anchor{23}@anchor{gnat_ugn/gnat_utility_programs id5}@anchor{1d6}
23579@section The GNAT Library Browser @cite{gnatls}
23580
23581
23582@geindex Library browser
23583
23584@geindex gnatls
23585
23586@cite{gnatls} is a tool that outputs information about compiled
23587units. It gives the relationship between objects, unit names and source
23588files. It can also be used to check the source dependencies of a unit
23589as well as various characteristics.
23590
23591Note: to invoke @cite{gnatls} with a project file, use the @cite{gnat}
23592driver (see @ref{122,,The GNAT Driver and Project Files}).
23593
23594@menu
23595* Running gnatls::
23596* Switches for gnatls::
23597* Example of gnatls Usage::
23598
23599@end menu
23600
23601@node Running gnatls,Switches for gnatls,,The GNAT Library Browser gnatls
23602@anchor{gnat_ugn/gnat_utility_programs id6}@anchor{1d7}@anchor{gnat_ugn/gnat_utility_programs running-gnatls}@anchor{1d8}
23603@subsection Running @cite{gnatls}
23604
23605
23606The @cite{gnatls} command has the form
23607
23608@quotation
23609
23610@example
23611$ gnatls switches `object_or_ali_file`
23612@end example
23613@end quotation
23614
23615The main argument is the list of object or @code{ali} files
23616(see @ref{44,,The Ada Library Information Files})
23617for which information is requested.
23618
23619In normal mode, without additional option, @cite{gnatls} produces a
23620four-column listing. Each line represents information for a specific
23621object. The first column gives the full path of the object, the second
23622column gives the name of the principal unit in this object, the third
23623column gives the status of the source and the fourth column gives the
23624full path of the source representing this unit.
23625Here is a simple example of use:
23626
23627@quotation
23628
23629@example
23630$ gnatls *.o
23631./demo1.o            demo1            DIF demo1.adb
23632./demo2.o            demo2             OK demo2.adb
23633./hello.o            h1                OK hello.adb
23634./instr-child.o      instr.child      MOK instr-child.adb
23635./instr.o            instr             OK instr.adb
23636./tef.o              tef              DIF tef.adb
23637./text_io_example.o  text_io_example   OK text_io_example.adb
23638./tgef.o             tgef             DIF tgef.adb
23639@end example
23640@end quotation
23641
23642The first line can be interpreted as follows: the main unit which is
23643contained in
23644object file @code{demo1.o} is demo1, whose main source is in
23645@code{demo1.adb}. Furthermore, the version of the source used for the
23646compilation of demo1 has been modified (DIF). Each source file has a status
23647qualifier which can be:
23648
23649
23650@table @asis
23651
23652@item @emph{OK (unchanged)}
23653
23654The version of the source file used for the compilation of the
23655specified unit corresponds exactly to the actual source file.
23656
23657@item @emph{MOK (slightly modified)}
23658
23659The version of the source file used for the compilation of the
23660specified unit differs from the actual source file but not enough to
23661require recompilation. If you use gnatmake with the qualifier
23662@emph{-m (minimal recompilation)}, a file marked
23663MOK will not be recompiled.
23664
23665@item @emph{DIF (modified)}
23666
23667No version of the source found on the path corresponds to the source
23668used to build this object.
23669
23670@item @emph{??? (file not found)}
23671
23672No source file was found for this unit.
23673
23674@item @emph{HID (hidden,  unchanged version not first on PATH)}
23675
23676The version of the source that corresponds exactly to the source used
23677for compilation has been found on the path but it is hidden by another
23678version of the same source that has been modified.
23679@end table
23680
23681@node Switches for gnatls,Example of gnatls Usage,Running gnatls,The GNAT Library Browser gnatls
23682@anchor{gnat_ugn/gnat_utility_programs id7}@anchor{1d9}@anchor{gnat_ugn/gnat_utility_programs switches-for-gnatls}@anchor{1da}
23683@subsection Switches for @cite{gnatls}
23684
23685
23686@cite{gnatls} recognizes the following switches:
23687
23688@geindex --version (gnatls)
23689
23690
23691@table @asis
23692
23693@item @code{--version}
23694
23695Display Copyright and version, then exit disregarding all other options.
23696@end table
23697
23698@geindex --help (gnatls)
23699
23700
23701@table @asis
23702
23703@item @code{*--help}
23704
23705If @emph{--version} was not used, display usage, then exit disregarding
23706all other options.
23707@end table
23708
23709@geindex -a (gnatls)
23710
23711
23712@table @asis
23713
23714@item @code{-a}
23715
23716Consider all units, including those of the predefined Ada library.
23717Especially useful with @emph{-d}.
23718@end table
23719
23720@geindex -d (gnatls)
23721
23722
23723@table @asis
23724
23725@item @code{-d}
23726
23727List sources from which specified units depend on.
23728@end table
23729
23730@geindex -h (gnatls)
23731
23732
23733@table @asis
23734
23735@item @code{-h}
23736
23737Output the list of options.
23738@end table
23739
23740@geindex -o (gnatls)
23741
23742
23743@table @asis
23744
23745@item @code{-o}
23746
23747Only output information about object files.
23748@end table
23749
23750@geindex -s (gnatls)
23751
23752
23753@table @asis
23754
23755@item @code{-s}
23756
23757Only output information about source files.
23758@end table
23759
23760@geindex -u (gnatls)
23761
23762
23763@table @asis
23764
23765@item @code{-u}
23766
23767Only output information about compilation units.
23768@end table
23769
23770@geindex -files (gnatls)
23771
23772
23773@table @asis
23774
23775@item @code{-files=@emph{file}}
23776
23777Take as arguments the files listed in text file @cite{file}.
23778Text file @cite{file} may contain empty lines that are ignored.
23779Each nonempty line should contain the name of an existing file.
23780Several such switches may be specified simultaneously.
23781@end table
23782
23783@geindex -aO (gnatls)
23784
23785@geindex -aI (gnatls)
23786
23787@geindex -I (gnatls)
23788
23789@geindex -I- (gnatls)
23790
23791
23792@table @asis
23793
23794@item @code{-aO@emph{dir}}, @code{-aI@emph{dir}}, @code{-I@emph{dir}}, @code{-I-}, @code{-nostdinc}
23795
23796Source path manipulation. Same meaning as the equivalent @emph{gnatmake}
23797flags (@ref{e2,,Switches for gnatmake}).
23798@end table
23799
23800@geindex -aP (gnatls)
23801
23802
23803@table @asis
23804
23805@item @code{-aP@emph{dir}}
23806
23807Add @cite{dir} at the beginning of the project search dir.
23808@end table
23809
23810@geindex --RTS (gnatls)
23811
23812
23813@table @asis
23814
23815@item @code{--RTS=@emph{rts-path}`}
23816
23817Specifies the default location of the runtime library. Same meaning as the
23818equivalent @emph{gnatmake} flag (@ref{e2,,Switches for gnatmake}).
23819@end table
23820
23821@geindex -v (gnatls)
23822
23823
23824@table @asis
23825
23826@item @code{-v}
23827
23828Verbose mode. Output the complete source, object and project paths. Do not use
23829the default column layout but instead use long format giving as much as
23830information possible on each requested units, including special
23831characteristics such as:
23832
23833
23834@itemize *
23835
23836@item
23837@emph{Preelaborable}: The unit is preelaborable in the Ada sense.
23838
23839@item
23840@emph{No_Elab_Code}:  No elaboration code has been produced by the compiler for this unit.
23841
23842@item
23843@emph{Pure}: The unit is pure in the Ada sense.
23844
23845@item
23846@emph{Elaborate_Body}: The unit contains a pragma Elaborate_Body.
23847
23848@item
23849@emph{Remote_Types}: The unit contains a pragma Remote_Types.
23850
23851@item
23852@emph{Shared_Passive}: The unit contains a pragma Shared_Passive.
23853
23854@item
23855@emph{Predefined}: This unit is part of the predefined environment and cannot be modified
23856by the user.
23857
23858@item
23859@emph{Remote_Call_Interface}: The unit contains a pragma Remote_Call_Interface.
23860@end itemize
23861@end table
23862
23863@node Example of gnatls Usage,,Switches for gnatls,The GNAT Library Browser gnatls
23864@anchor{gnat_ugn/gnat_utility_programs id8}@anchor{1db}@anchor{gnat_ugn/gnat_utility_programs example-of-gnatls-usage}@anchor{1dc}
23865@subsection Example of @cite{gnatls} Usage
23866
23867
23868Example of using the verbose switch. Note how the source and
23869object paths are affected by the -I switch.
23870
23871@quotation
23872
23873@example
23874$ gnatls -v -I.. demo1.o
23875
23876GNATLS 5.03w (20041123-34)
23877Copyright 1997-2004 Free Software Foundation, Inc.
23878
23879Source Search Path:
23880   <Current_Directory>
23881   ../
23882   /home/comar/local/adainclude/
23883
23884Object Search Path:
23885   <Current_Directory>
23886   ../
23887   /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
23888
23889Project Search Path:
23890   <Current_Directory>
23891   /home/comar/local/lib/gnat/
23892
23893./demo1.o
23894   Unit =>
23895     Name   => demo1
23896     Kind   => subprogram body
23897     Flags  => No_Elab_Code
23898     Source => demo1.adb    modified
23899@end example
23900@end quotation
23901
23902The following is an example of use of the dependency list.
23903Note the use of the -s switch
23904which gives a straight list of source files. This can be useful for
23905building specialized scripts.
23906
23907@quotation
23908
23909@example
23910$ gnatls -d demo2.o
23911./demo2.o   demo2        OK demo2.adb
23912                         OK gen_list.ads
23913                         OK gen_list.adb
23914                         OK instr.ads
23915                         OK instr-child.ads
23916
23917$ gnatls -d -s -a demo1.o
23918demo1.adb
23919/home/comar/local/adainclude/ada.ads
23920/home/comar/local/adainclude/a-finali.ads
23921/home/comar/local/adainclude/a-filico.ads
23922/home/comar/local/adainclude/a-stream.ads
23923/home/comar/local/adainclude/a-tags.ads
23924gen_list.ads
23925gen_list.adb
23926/home/comar/local/adainclude/gnat.ads
23927/home/comar/local/adainclude/g-io.ads
23928instr.ads
23929/home/comar/local/adainclude/system.ads
23930/home/comar/local/adainclude/s-exctab.ads
23931/home/comar/local/adainclude/s-finimp.ads
23932/home/comar/local/adainclude/s-finroo.ads
23933/home/comar/local/adainclude/s-secsta.ads
23934/home/comar/local/adainclude/s-stalib.ads
23935/home/comar/local/adainclude/s-stoele.ads
23936/home/comar/local/adainclude/s-stratt.ads
23937/home/comar/local/adainclude/s-tasoli.ads
23938/home/comar/local/adainclude/s-unstyp.ads
23939/home/comar/local/adainclude/unchconv.ads
23940@end example
23941@end quotation
23942
23943@node The Cross-Referencing Tools gnatxref and gnatfind,The Ada to HTML Converter gnathtml,The GNAT Library Browser gnatls,GNAT Utility Programs
23944@anchor{gnat_ugn/gnat_utility_programs the-cross-referencing-tools-gnatxref-and-gnatfind}@anchor{24}@anchor{gnat_ugn/gnat_utility_programs id9}@anchor{1dd}
23945@section The Cross-Referencing Tools @cite{gnatxref} and @cite{gnatfind}
23946
23947
23948@geindex gnatxref
23949
23950@geindex gnatfind
23951
23952The compiler generates cross-referencing information (unless
23953you set the @code{-gnatx} switch), which are saved in the @code{.ali} files.
23954This information indicates where in the source each entity is declared and
23955referenced. Note that entities in package Standard are not included, but
23956entities in all other predefined units are included in the output.
23957
23958Before using any of these two tools, you need to compile successfully your
23959application, so that GNAT gets a chance to generate the cross-referencing
23960information.
23961
23962The two tools @cite{gnatxref} and @cite{gnatfind} take advantage of this
23963information to provide the user with the capability to easily locate the
23964declaration and references to an entity. These tools are quite similar,
23965the difference being that @cite{gnatfind} is intended for locating
23966definitions and/or references to a specified entity or entities, whereas
23967@cite{gnatxref} is oriented to generating a full report of all
23968cross-references.
23969
23970To use these tools, you must not compile your application using the
23971@emph{-gnatx} switch on the @emph{gnatmake} command line
23972(see @ref{1d,,Building with gnatmake}). Otherwise, cross-referencing
23973information will not be generated.
23974
23975Note: to invoke @cite{gnatxref} or @cite{gnatfind} with a project file,
23976use the @cite{gnat} driver (see @ref{122,,The GNAT Driver and Project Files}).
23977
23978@menu
23979* gnatxref Switches::
23980* gnatfind Switches::
23981* Project Files for gnatxref and gnatfind::
23982* Regular Expressions in gnatfind and gnatxref::
23983* Examples of gnatxref Usage::
23984* Examples of gnatfind Usage::
23985
23986@end menu
23987
23988@node gnatxref Switches,gnatfind Switches,,The Cross-Referencing Tools gnatxref and gnatfind
23989@anchor{gnat_ugn/gnat_utility_programs id10}@anchor{1de}@anchor{gnat_ugn/gnat_utility_programs gnatxref-switches}@anchor{1df}
23990@subsection @cite{gnatxref} Switches
23991
23992
23993The command invocation for @cite{gnatxref} is:
23994
23995@quotation
23996
23997@example
23998$ gnatxref [`switches`] `sourcefile1` [`sourcefile2` ...]
23999@end example
24000@end quotation
24001
24002where
24003
24004
24005@table @asis
24006
24007@item @emph{sourcefile1} [, @emph{sourcefile2} ...]
24008
24009identify the source files for which a report is to be generated. The
24010'with'ed units will be processed too. You must provide at least one file.
24011
24012These file names are considered to be regular expressions, so for instance
24013specifying @code{source*.adb} is the same as giving every file in the current
24014directory whose name starts with @code{source} and whose extension is
24015@code{adb}.
24016
24017You shouldn't specify any directory name, just base names. @emph{gnatxref}
24018and @emph{gnatfind} will be able to locate these files by themselves using
24019the source path. If you specify directories, no result is produced.
24020@end table
24021
24022The following switches are available for @emph{gnatxref}:
24023
24024@geindex --version (gnatxref)
24025
24026
24027@table @asis
24028
24029@item @code{-version}
24030
24031Display Copyright and version, then exit disregarding all other options.
24032@end table
24033
24034@geindex --help (gnatxref)
24035
24036
24037@table @asis
24038
24039@item @code{-help}
24040
24041If @emph{--version} was not used, display usage, then exit disregarding
24042all other options.
24043@end table
24044
24045@geindex -a (gnatxref)
24046
24047
24048@table @asis
24049
24050@item @code{a}
24051
24052If this switch is present, @cite{gnatfind} and @cite{gnatxref} will parse
24053the read-only files found in the library search path. Otherwise, these files
24054will be ignored. This option can be used to protect Gnat sources or your own
24055libraries from being parsed, thus making @cite{gnatfind} and @cite{gnatxref}
24056much faster, and their output much smaller. Read-only here refers to access
24057or permissions status in the file system for the current user.
24058@end table
24059
24060@geindex -aIDIR (gnatxref)
24061
24062
24063@table @asis
24064
24065@item @code{aI@emph{DIR}}
24066
24067When looking for source files also look in directory DIR. The order in which
24068source file search is undertaken is the same as for @emph{gnatmake}.
24069@end table
24070
24071@geindex -aODIR (gnatxref)
24072
24073
24074@table @asis
24075
24076@item @code{aO@emph{DIR}}
24077
24078When searching for library and object files, look in directory
24079DIR. The order in which library files are searched is the same as for
24080@emph{gnatmake}.
24081@end table
24082
24083@geindex -nostdinc (gnatxref)
24084
24085
24086@table @asis
24087
24088@item @code{nostdinc}
24089
24090Do not look for sources in the system default directory.
24091@end table
24092
24093@geindex -nostdlib (gnatxref)
24094
24095
24096@table @asis
24097
24098@item @code{nostdlib}
24099
24100Do not look for library files in the system default directory.
24101@end table
24102
24103@geindex --ext (gnatxref)
24104
24105
24106@table @asis
24107
24108@item @code{-ext=@emph{extension}}
24109
24110Specify an alternate ali file extension. The default is @cite{ali} and other
24111extensions (e.g. @cite{gli} for C/C++ sources when using @emph{-fdump-xref})
24112may be specified via this switch. Note that if this switch overrides the
24113default, which means that only the new extension will be considered.
24114@end table
24115
24116@geindex --RTS (gnatxref)
24117
24118
24119@table @asis
24120
24121@item @code{-RTS=@emph{rts-path}}
24122
24123Specifies the default location of the runtime library. Same meaning as the
24124equivalent @emph{gnatmake} flag (@ref{e2,,Switches for gnatmake}).
24125@end table
24126
24127@geindex -d (gnatxref)
24128
24129
24130@table @asis
24131
24132@item @code{d}
24133
24134If this switch is set @cite{gnatxref} will output the parent type
24135reference for each matching derived types.
24136@end table
24137
24138@geindex -f (gnatxref)
24139
24140
24141@table @asis
24142
24143@item @code{f}
24144
24145If this switch is set, the output file names will be preceded by their
24146directory (if the file was found in the search path). If this switch is
24147not set, the directory will not be printed.
24148@end table
24149
24150@geindex -g (gnatxref)
24151
24152
24153@table @asis
24154
24155@item @code{g}
24156
24157If this switch is set, information is output only for library-level
24158entities, ignoring local entities. The use of this switch may accelerate
24159@cite{gnatfind} and @cite{gnatxref}.
24160@end table
24161
24162@geindex -IDIR (gnatxref)
24163
24164
24165@table @asis
24166
24167@item @code{I@emph{DIR}}
24168
24169Equivalent to @code{-aODIR -aIDIR}.
24170@end table
24171
24172@geindex -pFILE (gnatxref)
24173
24174
24175@table @asis
24176
24177@item @code{p@emph{FILE}}
24178
24179Specify a project file to use @ref{b,,GNAT Project Manager}.
24180If you need to use the @code{.gpr}
24181project files, you should use gnatxref through the GNAT driver
24182(@emph{gnat xref -Pproject}).
24183
24184By default, @cite{gnatxref} and @cite{gnatfind} will try to locate a
24185project file in the current directory.
24186
24187If a project file is either specified or found by the tools, then the content
24188of the source directory and object directory lines are added as if they
24189had been specified respectively by @code{-aI}
24190and @code{-aO}.
24191
24192@item @code{u}
24193
24194Output only unused symbols. This may be really useful if you give your
24195main compilation unit on the command line, as @cite{gnatxref} will then
24196display every unused entity and 'with'ed package.
24197
24198@item @code{v}
24199
24200Instead of producing the default output, @cite{gnatxref} will generate a
24201@code{tags} file that can be used by vi. For examples how to use this
24202feature, see @ref{1e0,,Examples of gnatxref Usage}. The tags file is output
24203to the standard output, thus you will have to redirect it to a file.
24204@end table
24205
24206All these switches may be in any order on the command line, and may even
24207appear after the file names. They need not be separated by spaces, thus
24208you can say @code{gnatxref -ag} instead of @code{gnatxref -a -g}.
24209
24210@node gnatfind Switches,Project Files for gnatxref and gnatfind,gnatxref Switches,The Cross-Referencing Tools gnatxref and gnatfind
24211@anchor{gnat_ugn/gnat_utility_programs id11}@anchor{1e1}@anchor{gnat_ugn/gnat_utility_programs gnatfind-switches}@anchor{1e2}
24212@subsection @cite{gnatfind} Switches
24213
24214
24215The command invocation for @cite{gnatfind} is:
24216
24217@quotation
24218
24219@example
24220$ gnatfind [`switches`] `pattern`[:`sourcefile`[:`line`[:`column`]]]
24221      [`file1` `file2` ...]
24222@end example
24223@end quotation
24224
24225with the following iterpretation of the command arguments:
24226
24227
24228@table @asis
24229
24230@item @emph{pattern}
24231
24232An entity will be output only if it matches the regular expression found
24233in @cite{pattern}, see @ref{1e3,,Regular Expressions in gnatfind and gnatxref}.
24234
24235Omitting the pattern is equivalent to specifying @code{*}, which
24236will match any entity. Note that if you do not provide a pattern, you
24237have to provide both a sourcefile and a line.
24238
24239Entity names are given in Latin-1, with uppercase/lowercase equivalence
24240for matching purposes. At the current time there is no support for
242418-bit codes other than Latin-1, or for wide characters in identifiers.
24242
24243@item @emph{sourcefile}
24244
24245@cite{gnatfind} will look for references, bodies or declarations
24246of symbols referenced in @code{sourcefile}, at line @cite{line}
24247and column @cite{column}. See @ref{1e4,,Examples of gnatfind Usage}
24248for syntax examples.
24249
24250@item @emph{line}
24251
24252A decimal integer identifying the line number containing
24253the reference to the entity (or entities) to be located.
24254
24255@item @emph{column}
24256
24257A decimal integer identifying the exact location on the
24258line of the first character of the identifier for the
24259entity reference. Columns are numbered from 1.
24260
24261@item @emph{file1 file2 ...}
24262
24263The search will be restricted to these source files. If none are given, then
24264the search will be conducted for every library file in the search path.
24265These files must appear only after the pattern or sourcefile.
24266
24267These file names are considered to be regular expressions, so for instance
24268specifying @code{source*.adb} is the same as giving every file in the current
24269directory whose name starts with @code{source} and whose extension is
24270@code{adb}.
24271
24272The location of the spec of the entity will always be displayed, even if it
24273isn't in one of @code{file1}, @code{file2}, ... The
24274occurrences of the entity in the separate units of the ones given on the
24275command line will also be displayed.
24276
24277Note that if you specify at least one file in this part, @cite{gnatfind} may
24278sometimes not be able to find the body of the subprograms.
24279@end table
24280
24281At least one of 'sourcefile' or 'pattern' has to be present on
24282the command line.
24283
24284The following switches are available:
24285
24286@geindex --version (gnatfind)
24287
24288
24289@table @asis
24290
24291@item @code{--version}
24292
24293Display Copyright and version, then exit disregarding all other options.
24294@end table
24295
24296@geindex --help (gnatfind)
24297
24298
24299@table @asis
24300
24301@item @code{-help}
24302
24303If @emph{--version} was not used, display usage, then exit disregarding
24304all other options.
24305@end table
24306
24307@geindex -a (gnatfind)
24308
24309
24310@table @asis
24311
24312@item @code{a}
24313
24314If this switch is present, @cite{gnatfind} and @cite{gnatxref} will parse
24315the read-only files found in the library search path. Otherwise, these files
24316will be ignored. This option can be used to protect Gnat sources or your own
24317libraries from being parsed, thus making @cite{gnatfind} and @cite{gnatxref}
24318much faster, and their output much smaller. Read-only here refers to access
24319or permission status in the file system for the current user.
24320@end table
24321
24322@geindex -aIDIR (gnatfind)
24323
24324
24325@table @asis
24326
24327@item @code{aI@emph{DIR}}
24328
24329When looking for source files also look in directory DIR. The order in which
24330source file search is undertaken is the same as for @emph{gnatmake}.
24331@end table
24332
24333@geindex -aODIR (gnatfind)
24334
24335
24336@table @asis
24337
24338@item @code{aO@emph{DIR}}
24339
24340When searching for library and object files, look in directory
24341DIR. The order in which library files are searched is the same as for
24342@emph{gnatmake}.
24343@end table
24344
24345@geindex -nostdinc (gnatfind)
24346
24347
24348@table @asis
24349
24350@item @code{nostdinc}
24351
24352Do not look for sources in the system default directory.
24353@end table
24354
24355@geindex -nostdlib (gnatfind)
24356
24357
24358@table @asis
24359
24360@item @code{nostdlib}
24361
24362Do not look for library files in the system default directory.
24363@end table
24364
24365@geindex --ext (gnatfind)
24366
24367
24368@table @asis
24369
24370@item @code{-ext=@emph{extension}}
24371
24372Specify an alternate ali file extension. The default is @cite{ali} and other
24373extensions (e.g. @cite{gli} for C/C++ sources when using @emph{-fdump-xref})
24374may be specified via this switch. Note that if this switch overrides the
24375default, which means that only the new extension will be considered.
24376@end table
24377
24378@geindex --RTS (gnatfind)
24379
24380
24381@table @asis
24382
24383@item @code{-RTS=@emph{rts-path}}
24384
24385Specifies the default location of the runtime library. Same meaning as the
24386equivalent @emph{gnatmake} flag (@ref{e2,,Switches for gnatmake}).
24387@end table
24388
24389@geindex -d (gnatfind)
24390
24391
24392@table @asis
24393
24394@item @code{d}
24395
24396If this switch is set, then @cite{gnatfind} will output the parent type
24397reference for each matching derived types.
24398@end table
24399
24400@geindex -e (gnatfind)
24401
24402
24403@table @asis
24404
24405@item @code{e}
24406
24407By default, @cite{gnatfind} accept the simple regular expression set for
24408@cite{pattern}. If this switch is set, then the pattern will be
24409considered as full Unix-style regular expression.
24410@end table
24411
24412@geindex -f (gnatfind)
24413
24414
24415@table @asis
24416
24417@item @code{f}
24418
24419If this switch is set, the output file names will be preceded by their
24420directory (if the file was found in the search path). If this switch is
24421not set, the directory will not be printed.
24422@end table
24423
24424@geindex -g (gnatfind)
24425
24426
24427@table @asis
24428
24429@item @code{g}
24430
24431If this switch is set, information is output only for library-level
24432entities, ignoring local entities. The use of this switch may accelerate
24433@cite{gnatfind} and @cite{gnatxref}.
24434@end table
24435
24436@geindex -IDIR (gnatfind)
24437
24438
24439@table @asis
24440
24441@item @code{I@emph{DIR}}
24442
24443Equivalent to @code{-aODIR -aIDIR}.
24444@end table
24445
24446@geindex -pFILE (gnatfind)
24447
24448
24449@table @asis
24450
24451@item @code{p@emph{FILE}}
24452
24453Specify a project file (@ref{b,,GNAT Project Manager}) to use.
24454By default, @cite{gnatxref} and @cite{gnatfind} will try to locate a
24455project file in the current directory.
24456
24457If a project file is either specified or found by the tools, then the content
24458of the source directory and object directory lines are added as if they
24459had been specified respectively by @code{-aI} and
24460@code{-aO}.
24461@end table
24462
24463@geindex -r (gnatfind)
24464
24465
24466@table @asis
24467
24468@item @code{r}
24469
24470By default, @cite{gnatfind} will output only the information about the
24471declaration, body or type completion of the entities. If this switch is
24472set, the @cite{gnatfind} will locate every reference to the entities in
24473the files specified on the command line (or in every file in the search
24474path if no file is given on the command line).
24475@end table
24476
24477@geindex -s (gnatfind)
24478
24479
24480@table @asis
24481
24482@item @code{s}
24483
24484If this switch is set, then @cite{gnatfind} will output the content
24485of the Ada source file lines were the entity was found.
24486@end table
24487
24488@geindex -t (gnatfind)
24489
24490
24491@table @asis
24492
24493@item @code{t}
24494
24495If this switch is set, then @cite{gnatfind} will output the type hierarchy for
24496the specified type. It act like -d option but recursively from parent
24497type to parent type. When this switch is set it is not possible to
24498specify more than one file.
24499@end table
24500
24501All these switches may be in any order on the command line, and may even
24502appear after the file names. They need not be separated by spaces, thus
24503you can say @code{gnatxref -ag} instead of
24504@code{gnatxref -a -g}.
24505
24506As stated previously, gnatfind will search in every directory in the
24507search path. You can force it to look only in the current directory if
24508you specify @cite{*} at the end of the command line.
24509
24510@node Project Files for gnatxref and gnatfind,Regular Expressions in gnatfind and gnatxref,gnatfind Switches,The Cross-Referencing Tools gnatxref and gnatfind
24511@anchor{gnat_ugn/gnat_utility_programs project-files-for-gnatxref-and-gnatfind}@anchor{1e5}@anchor{gnat_ugn/gnat_utility_programs id12}@anchor{1e6}
24512@subsection Project Files for @emph{gnatxref} and @emph{gnatfind}
24513
24514
24515Project files allow a programmer to specify how to compile its
24516application, where to find sources, etc.  These files are used
24517primarily by GPS, but they can also be used
24518by the two tools @cite{gnatxref} and @cite{gnatfind}.
24519
24520A project file name must end with @code{.gpr}. If a single one is
24521present in the current directory, then @cite{gnatxref} and @cite{gnatfind} will
24522extract the information from it. If multiple project files are found, none of
24523them is read, and you have to use the @code{-p} switch to specify the one
24524you want to use.
24525
24526The following lines can be included, even though most of them have default
24527values which can be used in most cases.
24528The lines can be entered in any order in the file.
24529Except for @code{src_dir} and @code{obj_dir}, you can only have one instance of
24530each line. If you have multiple instances, only the last one is taken into
24531account.
24532
24533
24534@itemize *
24535
24536@item
24537
24538@table @asis
24539
24540@item @emph{src_dir=DIR}
24541
24542[default: @cite{"./"}].
24543Specifies a directory where to look for source files. Multiple @cite{src_dir}
24544lines can be specified and they will be searched in the order they
24545are specified.
24546@end table
24547
24548@item
24549
24550@table @asis
24551
24552@item @emph{obj_dir=DIR}
24553
24554[default: @cite{"./"}].
24555Specifies a directory where to look for object and library files. Multiple
24556@cite{obj_dir} lines can be specified, and they will be searched in the order
24557they are specified
24558@end table
24559
24560@item
24561
24562@table @asis
24563
24564@item @emph{comp_opt=SWITCHES}
24565
24566[default: @cite{""}].
24567Creates a variable which can be referred to subsequently by using
24568the @cite{$@{comp_opt@}} notation. This is intended to store the default
24569switches given to @emph{gnatmake} and @emph{gcc}.
24570@end table
24571
24572@item
24573
24574@table @asis
24575
24576@item @emph{bind_opt=SWITCHES}
24577
24578[default: @cite{""}].
24579Creates a variable which can be referred to subsequently by using
24580the @code{$@emph{bind_opt}} notation. This is intended to store the default
24581switches given to @emph{gnatbind}.
24582@end table
24583
24584@item
24585
24586@table @asis
24587
24588@item @emph{link_opt=SWITCHES}
24589
24590[default: @cite{""}].
24591Creates a variable which can be referred to subsequently by using
24592the @code{$@emph{link_opt}} notation. This is intended to store the default
24593switches given to @emph{gnatlink}.
24594@end table
24595
24596@item
24597
24598@table @asis
24599
24600@item @emph{main=EXECUTABLE}
24601
24602[default: @cite{""}].
24603Specifies the name of the executable for the application. This variable can
24604be referred to in the following lines by using the @code{@emph{$@{main}} notation.
24605@end table
24606
24607@item
24608
24609@table @asis
24610
24611@item @emph{comp_cmd=COMMAND}
24612
24613[default: @cite{"gcc -c -I$@{src_dir@} -g -gnatq"}].
24614Specifies the command used to compile a single file in the application.
24615@end table
24616
24617@item
24618
24619@table @asis
24620
24621@item @emph{make_cmd=COMMAND}
24622
24623[default: @cite{"gnatmake $@{main@} -aI$@{src_dir@} -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@} -bargs $@{bind_opt@} -largs $@{link_opt@}"}].
24624Specifies the command used to recompile the whole application.
24625@end table
24626
24627@item
24628
24629@table @asis
24630
24631@item @emph{run_cmd=COMMAND}
24632
24633[default: @cite{"$@{main@}"}].
24634Specifies the command used to run the application.
24635@end table
24636
24637@item
24638
24639@table @asis
24640
24641@item @emph{debug_cmd=COMMAND}
24642
24643[default: @cite{"gdb $@{main@}"}].
24644Specifies the command used to debug the application
24645@end table
24646@end itemize
24647
24648@emph{gnatxref} and @emph{gnatfind} only take into account the
24649@cite{src_dir} and @cite{obj_dir} lines, and ignore the others.
24650
24651@node Regular Expressions in gnatfind and gnatxref,Examples of gnatxref Usage,Project Files for gnatxref and gnatfind,The Cross-Referencing Tools gnatxref and gnatfind
24652@anchor{gnat_ugn/gnat_utility_programs id13}@anchor{1e7}@anchor{gnat_ugn/gnat_utility_programs regular-expressions-in-gnatfind-and-gnatxref}@anchor{1e3}
24653@subsection Regular Expressions in @cite{gnatfind} and @cite{gnatxref}
24654
24655
24656As specified in the section about @emph{gnatfind}, the pattern can be a
24657regular expression. Two kinds of regular expressions
24658are recognized:
24659
24660
24661@itemize *
24662
24663@item
24664
24665@table @asis
24666
24667@item @emph{Globbing pattern}
24668
24669These are the most common regular expression. They are the same as are
24670generally used in a Unix shell command line, or in a DOS session.
24671
24672Here is a more formal grammar:
24673
24674@example
24675regexp ::= term
24676term   ::= elmt            -- matches elmt
24677term   ::= elmt elmt       -- concatenation (elmt then elmt)
24678term   ::= *               -- any string of 0 or more characters
24679term   ::= ?               -- matches any character
24680term   ::= [char @{char@}]   -- matches any character listed
24681term   ::= [char - char]   -- matches any character in range
24682@end example
24683@end table
24684
24685@item
24686
24687@table @asis
24688
24689@item @emph{Full regular expression}
24690
24691The second set of regular expressions is much more powerful. This is the
24692type of regular expressions recognized by utilities such as @code{grep}.
24693
24694The following is the form of a regular expression, expressed in same BNF
24695style as is found in the Ada Reference Manual:
24696
24697@example
24698regexp ::= term @{| term@}   -- alternation (term or term ...)
24699
24700term ::= item @{item@}       -- concatenation (item then item)
24701
24702item ::= elmt              -- match elmt
24703item ::= elmt *            -- zero or more elmt's
24704item ::= elmt +            -- one or more elmt's
24705item ::= elmt ?            -- matches elmt or nothing
24706
24707elmt ::= nschar            -- matches given character
24708elmt ::= [nschar @{nschar@}]   -- matches any character listed
24709elmt ::= [^ nschar @{nschar@}] -- matches any character not listed
24710elmt ::= [char - char]     -- matches chars in given range
24711elmt ::= \\ char            -- matches given character
24712elmt ::= .                 -- matches any single character
24713elmt ::= ( regexp )        -- parens used for grouping
24714
24715char ::= any character, including special characters
24716nschar ::= any character except ()[].*+?^
24717@end example
24718
24719Here are a few examples:
24720
24721@quotation
24722
24723
24724@table @asis
24725
24726@item @code{abcde|fghi}
24727
24728will match any of the two strings @code{abcde} and @code{fghi},
24729
24730@item @code{abc*d}
24731
24732will match any string like @code{abd}, @code{abcd}, @code{abccd},
24733@code{abcccd}, and so on,
24734
24735@item @code{[a-z]+}
24736
24737will match any string which has only lowercase characters in it (and at
24738least one character.
24739@end table
24740@end quotation
24741@end table
24742@end itemize
24743
24744@node Examples of gnatxref Usage,Examples of gnatfind Usage,Regular Expressions in gnatfind and gnatxref,The Cross-Referencing Tools gnatxref and gnatfind
24745@anchor{gnat_ugn/gnat_utility_programs examples-of-gnatxref-usage}@anchor{1e0}@anchor{gnat_ugn/gnat_utility_programs id14}@anchor{1e8}
24746@subsection Examples of @cite{gnatxref} Usage
24747
24748
24749@menu
24750* General Usage::
24751* Using gnatxref with vi::
24752
24753@end menu
24754
24755@node General Usage,Using gnatxref with vi,,Examples of gnatxref Usage
24756@anchor{gnat_ugn/gnat_utility_programs general-usage}@anchor{1e9}
24757@subsubsection General Usage
24758
24759
24760For the following examples, we will consider the following units:
24761
24762@quotation
24763
24764@example
24765main.ads:
247661: with Bar;
247672: package Main is
247683:     procedure Foo (B : in Integer);
247694:     C : Integer;
247705: private
247716:     D : Integer;
247727: end Main;
24773
24774main.adb:
247751: package body Main is
247762:     procedure Foo (B : in Integer) is
247773:     begin
247784:        C := B;
247795:        D := B;
247806:        Bar.Print (B);
247817:        Bar.Print (C);
247828:     end Foo;
247839: end Main;
24784
24785bar.ads:
247861: package Bar is
247872:     procedure Print (B : Integer);
247883: end bar;
24789@end example
24790@end quotation
24791
24792The first thing to do is to recompile your application (for instance, in
24793that case just by doing a @code{gnatmake main}, so that GNAT generates
24794the cross-referencing information.
24795You can then issue any of the following commands:
24796
24797@quotation
24798
24799
24800@itemize *
24801
24802@item
24803@code{gnatxref main.adb}
24804@cite{gnatxref} generates cross-reference information for main.adb
24805and every unit 'with'ed by main.adb.
24806
24807The output would be:
24808
24809@quotation
24810
24811@example
24812B                                                      Type: Integer
24813  Decl: bar.ads           2:22
24814B                                                      Type: Integer
24815  Decl: main.ads          3:20
24816  Body: main.adb          2:20
24817  Ref:  main.adb          4:13     5:13     6:19
24818Bar                                                    Type: Unit
24819  Decl: bar.ads           1:9
24820  Ref:  main.adb          6:8      7:8
24821       main.ads           1:6
24822C                                                      Type: Integer
24823  Decl: main.ads          4:5
24824  Modi: main.adb          4:8
24825  Ref:  main.adb          7:19
24826D                                                      Type: Integer
24827  Decl: main.ads          6:5
24828  Modi: main.adb          5:8
24829Foo                                                    Type: Unit
24830  Decl: main.ads          3:15
24831  Body: main.adb          2:15
24832Main                                                    Type: Unit
24833  Decl: main.ads          2:9
24834  Body: main.adb          1:14
24835Print                                                   Type: Unit
24836  Decl: bar.ads           2:15
24837  Ref:  main.adb          6:12     7:12
24838@end example
24839@end quotation
24840
24841This shows that the entity @cite{Main} is declared in main.ads, line 2, column 9,
24842its body is in main.adb, line 1, column 14 and is not referenced any where.
24843
24844The entity @cite{Print} is declared in bar.ads, line 2, column 15 and it
24845is referenced in main.adb, line 6 column 12 and line 7 column 12.
24846
24847@item
24848@code{gnatxref package1.adb package2.ads}
24849@cite{gnatxref} will generates cross-reference information for
24850package1.adb, package2.ads and any other package 'with'ed by any
24851of these.
24852@end itemize
24853@end quotation
24854
24855@node Using gnatxref with vi,,General Usage,Examples of gnatxref Usage
24856@anchor{gnat_ugn/gnat_utility_programs using-gnatxref-with-vi}@anchor{1ea}
24857@subsubsection Using gnatxref with vi
24858
24859
24860@cite{gnatxref} can generate a tags file output, which can be used
24861directly from @emph{vi}. Note that the standard version of @emph{vi}
24862will not work properly with overloaded symbols. Consider using another
24863free implementation of @emph{vi}, such as @emph{vim}.
24864
24865@quotation
24866
24867@example
24868$ gnatxref -v gnatfind.adb > tags
24869@end example
24870@end quotation
24871
24872The following command will generate the tags file for @cite{gnatfind} itself
24873(if the sources are in the search path!):
24874
24875@quotation
24876
24877@example
24878$ gnatxref -v gnatfind.adb > tags
24879@end example
24880@end quotation
24881
24882From @emph{vi}, you can then use the command @code{:tag @emph{entity}}
24883(replacing @cite{entity} by whatever you are looking for), and vi will
24884display a new file with the corresponding declaration of entity.
24885
24886@node Examples of gnatfind Usage,,Examples of gnatxref Usage,The Cross-Referencing Tools gnatxref and gnatfind
24887@anchor{gnat_ugn/gnat_utility_programs id15}@anchor{1eb}@anchor{gnat_ugn/gnat_utility_programs examples-of-gnatfind-usage}@anchor{1e4}
24888@subsection Examples of @cite{gnatfind} Usage
24889
24890
24891
24892@itemize *
24893
24894@item
24895@code{gnatfind -f xyz:main.adb}
24896Find declarations for all entities xyz referenced at least once in
24897main.adb. The references are search in every library file in the search
24898path.
24899
24900The directories will be printed as well (as the @code{-f}
24901switch is set)
24902
24903The output will look like:
24904
24905@quotation
24906
24907@example
24908directory/main.ads:106:14: xyz <= declaration
24909directory/main.adb:24:10: xyz <= body
24910directory/foo.ads:45:23: xyz <= declaration
24911@end example
24912@end quotation
24913
24914I.e., one of the entities xyz found in main.adb is declared at
24915line 12 of main.ads (and its body is in main.adb), and another one is
24916declared at line 45 of foo.ads
24917
24918@item
24919@code{gnatfind -fs xyz:main.adb}
24920This is the same command as the previous one, but @cite{gnatfind} will
24921display the content of the Ada source file lines.
24922
24923The output will look like:
24924
24925@example
24926directory/main.ads:106:14: xyz <= declaration
24927   procedure xyz;
24928directory/main.adb:24:10: xyz <= body
24929   procedure xyz is
24930directory/foo.ads:45:23: xyz <= declaration
24931   xyz : Integer;
24932@end example
24933
24934This can make it easier to find exactly the location your are looking
24935for.
24936
24937@item
24938@code{gnatfind -r "*x*":main.ads:123 foo.adb}
24939Find references to all entities containing an x that are
24940referenced on line 123 of main.ads.
24941The references will be searched only in main.ads and foo.adb.
24942
24943@item
24944@code{gnatfind main.ads:123}
24945Find declarations and bodies for all entities that are referenced on
24946line 123 of main.ads.
24947
24948This is the same as @code{gnatfind "*":main.adb:123`}
24949
24950@item
24951@code{gnatfind mydir/main.adb:123:45}
24952Find the declaration for the entity referenced at column 45 in
24953line 123 of file main.adb in directory mydir. Note that it
24954is usual to omit the identifier name when the column is given,
24955since the column position identifies a unique reference.
24956
24957The column has to be the beginning of the identifier, and should not
24958point to any character in the middle of the identifier.
24959@end itemize
24960
24961@node The Ada to HTML Converter gnathtml,,The Cross-Referencing Tools gnatxref and gnatfind,GNAT Utility Programs
24962@anchor{gnat_ugn/gnat_utility_programs the-ada-to-html-converter-gnathtml}@anchor{25}@anchor{gnat_ugn/gnat_utility_programs id16}@anchor{1ec}
24963@section The Ada to HTML Converter @cite{gnathtml}
24964
24965
24966@geindex gnathtml
24967
24968@emph{gnathtml} is a Perl script that allows Ada source files to be browsed using
24969standard Web browsers. For installation information, see @ref{1ed,,Installing gnathtml}.
24970
24971Ada reserved keywords are highlighted in a bold font and Ada comments in
24972a blue font. Unless your program was compiled with the gcc @emph{-gnatx}
24973switch to suppress the generation of cross-referencing information, user
24974defined variables and types will appear in a different color; you will
24975be able to click on any identifier and go to its declaration.
24976
24977@menu
24978* Invoking gnathtml::
24979* Installing gnathtml::
24980
24981@end menu
24982
24983@node Invoking gnathtml,Installing gnathtml,,The Ada to HTML Converter gnathtml
24984@anchor{gnat_ugn/gnat_utility_programs invoking-gnathtml}@anchor{1ee}@anchor{gnat_ugn/gnat_utility_programs id17}@anchor{1ef}
24985@subsection Invoking @emph{gnathtml}
24986
24987
24988The command line is as follows:
24989
24990@quotation
24991
24992@example
24993$ perl gnathtml.pl [`switches`] `ada-files`
24994@end example
24995@end quotation
24996
24997You can specify as many Ada files as you want. @cite{gnathtml} will generate
24998an html file for every ada file, and a global file called @code{index.htm}.
24999This file is an index of every identifier defined in the files.
25000
25001The following switches are available:
25002
25003@geindex -83 (gnathtml)
25004
25005
25006@table @asis
25007
25008@item @code{83}
25009
25010Only the Ada 83 subset of keywords will be highlighted.
25011@end table
25012
25013@geindex -cc (gnathtml)
25014
25015
25016@table @asis
25017
25018@item @code{cc @emph{color}}
25019
25020This option allows you to change the color used for comments. The default
25021value is green. The color argument can be any name accepted by html.
25022@end table
25023
25024@geindex -d (gnathtml)
25025
25026
25027@table @asis
25028
25029@item @code{d}
25030
25031If the Ada files depend on some other files (for instance through
25032@cite{with} clauses, the latter files will also be converted to html.
25033Only the files in the user project will be converted to html, not the files
25034in the run-time library itself.
25035@end table
25036
25037@geindex -D (gnathtml)
25038
25039
25040@table @asis
25041
25042@item @code{D}
25043
25044This command is the same as @emph{-d} above, but @emph{gnathtml} will
25045also look for files in the run-time library, and generate html files for them.
25046@end table
25047
25048@geindex -ext (gnathtml)
25049
25050
25051@table @asis
25052
25053@item @code{ext @emph{extension}}
25054
25055This option allows you to change the extension of the generated HTML files.
25056If you do not specify an extension, it will default to @code{htm}.
25057@end table
25058
25059@geindex -f (gnathtml)
25060
25061
25062@table @asis
25063
25064@item @code{f}
25065
25066By default, gnathtml will generate html links only for global entities
25067('with'ed units, global variables and types,...).  If you specify
25068@emph{-f} on the command line, then links will be generated for local
25069entities too.
25070@end table
25071
25072@geindex -l (gnathtml)
25073
25074
25075@table @asis
25076
25077@item @code{l @emph{number}}
25078
25079If this switch is provided and @cite{number} is not 0, then
25080@cite{gnathtml} will number the html files every @cite{number} line.
25081@end table
25082
25083@geindex -I (gnathtml)
25084
25085
25086@table @asis
25087
25088@item @code{I @emph{dir}}
25089
25090Specify a directory to search for library files (@code{.ALI} files) and
25091source files. You can provide several -I switches on the command line,
25092and the directories will be parsed in the order of the command line.
25093@end table
25094
25095@geindex -o (gnathtml)
25096
25097
25098@table @asis
25099
25100@item @code{o @emph{dir}}
25101
25102Specify the output directory for html files. By default, gnathtml will
25103saved the generated html files in a subdirectory named @code{html/}.
25104@end table
25105
25106@geindex -p (gnathtml)
25107
25108
25109@table @asis
25110
25111@item @code{p @emph{file}}
25112
25113If you are using Emacs and the most recent Emacs Ada mode, which provides
25114a full Integrated Development Environment for compiling, checking,
25115running and debugging applications, you may use @code{.gpr} files
25116to give the directories where Emacs can find sources and object files.
25117
25118Using this switch, you can tell gnathtml to use these files.
25119This allows you to get an html version of your application, even if it
25120is spread over multiple directories.
25121@end table
25122
25123@geindex -sc (gnathtml)
25124
25125
25126@table @asis
25127
25128@item @code{sc @emph{color}}
25129
25130This switch allows you to change the color used for symbol
25131definitions.
25132The default value is red. The color argument can be any name accepted by html.
25133@end table
25134
25135@geindex -t (gnathtml)
25136
25137
25138@table @asis
25139
25140@item @code{t @emph{file}}
25141
25142This switch provides the name of a file. This file contains a list of
25143file names to be converted, and the effect is exactly as though they had
25144appeared explicitly on the command line. This
25145is the recommended way to work around the command line length limit on some
25146systems.
25147@end table
25148
25149@node Installing gnathtml,,Invoking gnathtml,The Ada to HTML Converter gnathtml
25150@anchor{gnat_ugn/gnat_utility_programs installing-gnathtml}@anchor{1ed}@anchor{gnat_ugn/gnat_utility_programs id18}@anchor{1f0}
25151@subsection Installing @cite{gnathtml}
25152
25153
25154@cite{Perl} needs to be installed on your machine to run this script.
25155@cite{Perl} is freely available for almost every architecture and
25156operating system via the Internet.
25157
25158On Unix systems, you  may want to modify  the  first line of  the script
25159@cite{gnathtml},  to explicitly  specify  where Perl
25160is located. The syntax of this line is:
25161
25162@quotation
25163
25164@example
25165#!full_path_name_to_perl
25166@end example
25167@end quotation
25168
25169Alternatively, you may run the script using the following command line:
25170
25171@quotation
25172
25173@example
25174$ perl gnathtml.pl [`switches`] `files`
25175@end example
25176@end quotation
25177
25178@c -- +---------------------------------------------------------------------+
25179
25180@c -- | The following sections are present only in the PRO and GPL editions |
25181
25182@c -- +---------------------------------------------------------------------+
25183
25184
25185
25186
25187
25188
25189
25190@c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
25191
25192@node GNAT and Program Execution,Platform-Specific Information,GNAT Utility Programs,Top
25193@anchor{gnat_ugn/gnat_and_program_execution gnat-and-program-execution}@anchor{e}@anchor{gnat_ugn/gnat_and_program_execution doc}@anchor{1f1}@anchor{gnat_ugn/gnat_and_program_execution id1}@anchor{1f2}
25194@chapter GNAT and Program Execution
25195
25196
25197This chapter covers several topics:
25198
25199
25200@itemize *
25201
25202@item
25203@ref{1f3,,Running and Debugging Ada Programs}
25204
25205@item
25206@ref{1f4,,Code Coverage and Profiling}
25207
25208@item
25209@ref{1f5,,Improving Performance}
25210
25211@item
25212@ref{1f6,,Overflow Check Handling in GNAT}
25213
25214@item
25215@ref{1f7,,Performing Dimensionality Analysis in GNAT}
25216
25217@item
25218@ref{1f8,,Stack Related Facilities}
25219
25220@item
25221@ref{1f9,,Memory Management Issues}
25222@end itemize
25223
25224@menu
25225* Running and Debugging Ada Programs::
25226* Code Coverage and Profiling::
25227* Improving Performance::
25228* Overflow Check Handling in GNAT::
25229* Performing Dimensionality Analysis in GNAT::
25230* Stack Related Facilities::
25231* Memory Management Issues::
25232
25233@end menu
25234
25235@node Running and Debugging Ada Programs,Code Coverage and Profiling,,GNAT and Program Execution
25236@anchor{gnat_ugn/gnat_and_program_execution id2}@anchor{1f3}@anchor{gnat_ugn/gnat_and_program_execution running-and-debugging-ada-programs}@anchor{26}
25237@section Running and Debugging Ada Programs
25238
25239
25240@geindex Debugging
25241
25242This section discusses how to debug Ada programs.
25243
25244An incorrect Ada program may be handled in three ways by the GNAT compiler:
25245
25246
25247@itemize *
25248
25249@item
25250The illegality may be a violation of the static semantics of Ada. In
25251that case GNAT diagnoses the constructs in the program that are illegal.
25252It is then a straightforward matter for the user to modify those parts of
25253the program.
25254
25255@item
25256The illegality may be a violation of the dynamic semantics of Ada. In
25257that case the program compiles and executes, but may generate incorrect
25258results, or may terminate abnormally with some exception.
25259
25260@item
25261When presented with a program that contains convoluted errors, GNAT
25262itself may terminate abnormally without providing full diagnostics on
25263the incorrect user program.
25264@end itemize
25265
25266@geindex Debugger
25267
25268@geindex gdb
25269
25270@menu
25271* The GNAT Debugger GDB::
25272* Running GDB::
25273* Introduction to GDB Commands::
25274* Using Ada Expressions::
25275* Calling User-Defined Subprograms::
25276* Using the next Command in a Function::
25277* Stopping When Ada Exceptions Are Raised::
25278* Ada Tasks::
25279* Debugging Generic Units::
25280* Remote Debugging with gdbserver::
25281* GNAT Abnormal Termination or Failure to Terminate::
25282* Naming Conventions for GNAT Source Files::
25283* Getting Internal Debugging Information::
25284* Stack Traceback::
25285
25286@end menu
25287
25288@node The GNAT Debugger GDB,Running GDB,,Running and Debugging Ada Programs
25289@anchor{gnat_ugn/gnat_and_program_execution the-gnat-debugger-gdb}@anchor{1fa}@anchor{gnat_ugn/gnat_and_program_execution id3}@anchor{1fb}
25290@subsection The GNAT Debugger GDB
25291
25292
25293@cite{GDB} is a general purpose, platform-independent debugger that
25294can be used to debug mixed-language programs compiled with @emph{gcc},
25295and in particular is capable of debugging Ada programs compiled with
25296GNAT. The latest versions of @cite{GDB} are Ada-aware and can handle
25297complex Ada data structures.
25298
25299See @cite{Debugging with GDB},
25300for full details on the usage of @cite{GDB}, including a section on
25301its usage on programs. This manual should be consulted for full
25302details. The section that follows is a brief introduction to the
25303philosophy and use of @cite{GDB}.
25304
25305When GNAT programs are compiled, the compiler optionally writes debugging
25306information into the generated object file, including information on
25307line numbers, and on declared types and variables. This information is
25308separate from the generated code. It makes the object files considerably
25309larger, but it does not add to the size of the actual executable that
25310will be loaded into memory, and has no impact on run-time performance. The
25311generation of debug information is triggered by the use of the
25312-g switch in the @emph{gcc} or @emph{gnatmake} command
25313used to carry out the compilations. It is important to emphasize that
25314the use of these options does not change the generated code.
25315
25316The debugging information is written in standard system formats that
25317are used by many tools, including debuggers and profilers. The format
25318of the information is typically designed to describe C types and
25319semantics, but GNAT implements a translation scheme which allows full
25320details about Ada types and variables to be encoded into these
25321standard C formats. Details of this encoding scheme may be found in
25322the file exp_dbug.ads in the GNAT source distribution. However, the
25323details of this encoding are, in general, of no interest to a user,
25324since @cite{GDB} automatically performs the necessary decoding.
25325
25326When a program is bound and linked, the debugging information is
25327collected from the object files, and stored in the executable image of
25328the program. Again, this process significantly increases the size of
25329the generated executable file, but it does not increase the size of
25330the executable program itself. Furthermore, if this program is run in
25331the normal manner, it runs exactly as if the debug information were
25332not present, and takes no more actual memory.
25333
25334However, if the program is run under control of @cite{GDB}, the
25335debugger is activated.  The image of the program is loaded, at which
25336point it is ready to run.  If a run command is given, then the program
25337will run exactly as it would have if @cite{GDB} were not present. This
25338is a crucial part of the @cite{GDB} design philosophy.  @cite{GDB} is
25339entirely non-intrusive until a breakpoint is encountered.  If no
25340breakpoint is ever hit, the program will run exactly as it would if no
25341debugger were present. When a breakpoint is hit, @cite{GDB} accesses
25342the debugging information and can respond to user commands to inspect
25343variables, and more generally to report on the state of execution.
25344
25345@node Running GDB,Introduction to GDB Commands,The GNAT Debugger GDB,Running and Debugging Ada Programs
25346@anchor{gnat_ugn/gnat_and_program_execution id4}@anchor{1fc}@anchor{gnat_ugn/gnat_and_program_execution running-gdb}@anchor{1fd}
25347@subsection Running GDB
25348
25349
25350This section describes how to initiate the debugger.
25351
25352The debugger can be launched from a @cite{GPS} menu or
25353directly from the command line. The description below covers the latter use.
25354All the commands shown can be used in the @cite{GPS} debug console window,
25355but there are usually more GUI-based ways to achieve the same effect.
25356
25357The command to run @cite{GDB} is
25358
25359@quotation
25360
25361@example
25362$ gdb program
25363@end example
25364@end quotation
25365
25366where @cite{program} is the name of the executable file. This
25367activates the debugger and results in a prompt for debugger commands.
25368The simplest command is simply @cite{run}, which causes the program to run
25369exactly as if the debugger were not present. The following section
25370describes some of the additional commands that can be given to @cite{GDB}.
25371
25372@node Introduction to GDB Commands,Using Ada Expressions,Running GDB,Running and Debugging Ada Programs
25373@anchor{gnat_ugn/gnat_and_program_execution introduction-to-gdb-commands}@anchor{1fe}@anchor{gnat_ugn/gnat_and_program_execution id5}@anchor{1ff}
25374@subsection Introduction to GDB Commands
25375
25376
25377@cite{GDB} contains a large repertoire of commands.
25378See @cite{Debugging with GDB} for extensive documentation on the use
25379of these commands, together with examples of their use. Furthermore,
25380the command @emph{help} invoked from within GDB activates a simple help
25381facility which summarizes the available commands and their options.
25382In this section we summarize a few of the most commonly
25383used commands to give an idea of what @cite{GDB} is about. You should create
25384a simple program with debugging information and experiment with the use of
25385these @cite{GDB} commands on the program as you read through the
25386following section.
25387
25388
25389@itemize *
25390
25391@item
25392
25393@table @asis
25394
25395@item @emph{set args `arguments`}
25396
25397The @cite{arguments} list above is a list of arguments to be passed to
25398the program on a subsequent run command, just as though the arguments
25399had been entered on a normal invocation of the program. The @cite{set args}
25400command is not needed if the program does not require arguments.
25401@end table
25402
25403@item
25404
25405@table @asis
25406
25407@item @emph{run}
25408
25409The @cite{run} command causes execution of the program to start from
25410the beginning. If the program is already running, that is to say if
25411you are currently positioned at a breakpoint, then a prompt will ask
25412for confirmation that you want to abandon the current execution and
25413restart.
25414@end table
25415
25416@item
25417
25418@table @asis
25419
25420@item @emph{breakpoint `location`}
25421
25422The breakpoint command sets a breakpoint, that is to say a point at which
25423execution will halt and @cite{GDB} will await further
25424commands. @cite{location} is
25425either a line number within a file, given in the format @cite{file:linenumber},
25426or it is the name of a subprogram. If you request that a breakpoint be set on
25427a subprogram that is overloaded, a prompt will ask you to specify on which of
25428those subprograms you want to breakpoint. You can also
25429specify that all of them should be breakpointed. If the program is run
25430and execution encounters the breakpoint, then the program
25431stops and @cite{GDB} signals that the breakpoint was encountered by
25432printing the line of code before which the program is halted.
25433@end table
25434
25435@item
25436
25437@table @asis
25438
25439@item @emph{catch exception `name`}
25440
25441This command causes the program execution to stop whenever exception
25442@cite{name} is raised.  If @cite{name} is omitted, then the execution is
25443suspended when any exception is raised.
25444@end table
25445
25446@item
25447
25448@table @asis
25449
25450@item @emph{print `expression`}
25451
25452This will print the value of the given expression. Most simple
25453Ada expression formats are properly handled by @cite{GDB}, so the expression
25454can contain function calls, variables, operators, and attribute references.
25455@end table
25456
25457@item
25458
25459@table @asis
25460
25461@item @emph{continue}
25462
25463Continues execution following a breakpoint, until the next breakpoint or the
25464termination of the program.
25465@end table
25466
25467@item
25468
25469@table @asis
25470
25471@item @emph{step}
25472
25473Executes a single line after a breakpoint. If the next statement
25474is a subprogram call, execution continues into (the first statement of)
25475the called subprogram.
25476@end table
25477
25478@item
25479
25480@table @asis
25481
25482@item @emph{next}
25483
25484Executes a single line. If this line is a subprogram call, executes and
25485returns from the call.
25486@end table
25487
25488@item
25489
25490@table @asis
25491
25492@item @emph{list}
25493
25494Lists a few lines around the current source location. In practice, it
25495is usually more convenient to have a separate edit window open with the
25496relevant source file displayed. Successive applications of this command
25497print subsequent lines. The command can be given an argument which is a
25498line number, in which case it displays a few lines around the specified one.
25499@end table
25500
25501@item
25502
25503@table @asis
25504
25505@item @emph{backtrace}
25506
25507Displays a backtrace of the call chain. This command is typically
25508used after a breakpoint has occurred, to examine the sequence of calls that
25509leads to the current breakpoint. The display includes one line for each
25510activation record (frame) corresponding to an active subprogram.
25511@end table
25512
25513@item
25514
25515@table @asis
25516
25517@item @emph{up}
25518
25519At a breakpoint, @cite{GDB} can display the values of variables local
25520to the current frame. The command @cite{up} can be used to
25521examine the contents of other active frames, by moving the focus up
25522the stack, that is to say from callee to caller, one frame at a time.
25523@end table
25524
25525@item
25526
25527@table @asis
25528
25529@item @emph{down}
25530
25531Moves the focus of @cite{GDB} down from the frame currently being
25532examined to the frame of its callee (the reverse of the previous command),
25533@end table
25534
25535@item
25536
25537@table @asis
25538
25539@item @emph{frame `n`}
25540
25541Inspect the frame with the given number. The value 0 denotes the frame
25542of the current breakpoint, that is to say the top of the call stack.
25543@end table
25544
25545@item
25546
25547@table @asis
25548
25549@item @emph{kill}
25550
25551Kills the child process in which the program is running under GDB.
25552This may be useful for several purposes:
25553
25554
25555@itemize *
25556
25557@item
25558It allows you to recompile and relink your program, since on many systems
25559you cannot regenerate an executable file while it is running in a process.
25560
25561@item
25562You can run your program outside the debugger, on systems that do not
25563permit executing a program outside GDB while breakpoints are set
25564within GDB.
25565
25566@item
25567It allows you to debug a core dump rather than a running process.
25568@end itemize
25569@end table
25570@end itemize
25571
25572The above list is a very short introduction to the commands that
25573@cite{GDB} provides. Important additional capabilities, including conditional
25574breakpoints, the ability to execute command sequences on a breakpoint,
25575the ability to debug at the machine instruction level and many other
25576features are described in detail in @cite{Debugging with GDB}.
25577Note that most commands can be abbreviated
25578(for example, c for continue, bt for backtrace).
25579
25580@node Using Ada Expressions,Calling User-Defined Subprograms,Introduction to GDB Commands,Running and Debugging Ada Programs
25581@anchor{gnat_ugn/gnat_and_program_execution id6}@anchor{200}@anchor{gnat_ugn/gnat_and_program_execution using-ada-expressions}@anchor{201}
25582@subsection Using Ada Expressions
25583
25584
25585@geindex Ada expressions (in gdb)
25586
25587@cite{GDB} supports a fairly large subset of Ada expression syntax, with some
25588extensions. The philosophy behind the design of this subset is
25589
25590@quotation
25591
25592
25593@itemize *
25594
25595@item
25596That @cite{GDB} should provide basic literals and access to operations for
25597arithmetic, dereferencing, field selection, indexing, and subprogram calls,
25598leaving more sophisticated computations to subprograms written into the
25599program (which therefore may be called from @cite{GDB}).
25600
25601@item
25602That type safety and strict adherence to Ada language restrictions
25603are not particularly relevant in a debugging context.
25604
25605@item
25606That brevity is important to the @cite{GDB} user.
25607@end itemize
25608@end quotation
25609
25610Thus, for brevity, the debugger acts as if there were
25611implicit @cite{with} and @cite{use} clauses in effect for all user-written
25612packages, thus making it unnecessary to fully qualify most names with
25613their packages, regardless of context. Where this causes ambiguity,
25614@cite{GDB} asks the user's intent.
25615
25616For details on the supported Ada syntax, see @cite{Debugging with GDB}.
25617
25618@node Calling User-Defined Subprograms,Using the next Command in a Function,Using Ada Expressions,Running and Debugging Ada Programs
25619@anchor{gnat_ugn/gnat_and_program_execution id7}@anchor{202}@anchor{gnat_ugn/gnat_and_program_execution calling-user-defined-subprograms}@anchor{203}
25620@subsection Calling User-Defined Subprograms
25621
25622
25623An important capability of @cite{GDB} is the ability to call user-defined
25624subprograms while debugging. This is achieved simply by entering
25625a subprogram call statement in the form:
25626
25627@quotation
25628
25629@example
25630call subprogram-name (parameters)
25631@end example
25632@end quotation
25633
25634The keyword @cite{call} can be omitted in the normal case where the
25635@cite{subprogram-name} does not coincide with any of the predefined
25636@cite{GDB} commands.
25637
25638The effect is to invoke the given subprogram, passing it the
25639list of parameters that is supplied. The parameters can be expressions and
25640can include variables from the program being debugged. The
25641subprogram must be defined
25642at the library level within your program, and @cite{GDB} will call the
25643subprogram within the environment of your program execution (which
25644means that the subprogram is free to access or even modify variables
25645within your program).
25646
25647The most important use of this facility is in allowing the inclusion of
25648debugging routines that are tailored to particular data structures
25649in your program. Such debugging routines can be written to provide a suitably
25650high-level description of an abstract type, rather than a low-level dump
25651of its physical layout. After all, the standard
25652@cite{GDB print} command only knows the physical layout of your
25653types, not their abstract meaning. Debugging routines can provide information
25654at the desired semantic level and are thus enormously useful.
25655
25656For example, when debugging GNAT itself, it is crucial to have access to
25657the contents of the tree nodes used to represent the program internally.
25658But tree nodes are represented simply by an integer value (which in turn
25659is an index into a table of nodes).
25660Using the @cite{print} command on a tree node would simply print this integer
25661value, which is not very useful. But the PN routine (defined in file
25662treepr.adb in the GNAT sources) takes a tree node as input, and displays
25663a useful high level representation of the tree node, which includes the
25664syntactic category of the node, its position in the source, the integers
25665that denote descendant nodes and parent node, as well as varied
25666semantic information. To study this example in more detail, you might want to
25667look at the body of the PN procedure in the stated file.
25668
25669Another useful application of this capability is to deal with situations of
25670complex data which are not handled suitably by GDB. For example, if you specify
25671Convention Fortran for a multi-dimensional array, GDB does not know that
25672the ordering of array elements has been switched and will not properly
25673address the array elements. In such a case, instead of trying to print the
25674elements directly from GDB, you can write a callable procedure that prints
25675the elements in the desired format.
25676
25677@node Using the next Command in a Function,Stopping When Ada Exceptions Are Raised,Calling User-Defined Subprograms,Running and Debugging Ada Programs
25678@anchor{gnat_ugn/gnat_and_program_execution using-the-next-command-in-a-function}@anchor{204}@anchor{gnat_ugn/gnat_and_program_execution id8}@anchor{205}
25679@subsection Using the @emph{next} Command in a Function
25680
25681
25682When you use the @cite{next} command in a function, the current source
25683location will advance to the next statement as usual. A special case
25684arises in the case of a @cite{return} statement.
25685
25686Part of the code for a return statement is the 'epilogue' of the function.
25687This is the code that returns to the caller. There is only one copy of
25688this epilogue code, and it is typically associated with the last return
25689statement in the function if there is more than one return. In some
25690implementations, this epilogue is associated with the first statement
25691of the function.
25692
25693The result is that if you use the @cite{next} command from a return
25694statement that is not the last return statement of the function you
25695may see a strange apparent jump to the last return statement or to
25696the start of the function. You should simply ignore this odd jump.
25697The value returned is always that from the first return statement
25698that was stepped through.
25699
25700@node Stopping When Ada Exceptions Are Raised,Ada Tasks,Using the next Command in a Function,Running and Debugging Ada Programs
25701@anchor{gnat_ugn/gnat_and_program_execution stopping-when-ada-exceptions-are-raised}@anchor{206}@anchor{gnat_ugn/gnat_and_program_execution id9}@anchor{207}
25702@subsection Stopping When Ada Exceptions Are Raised
25703
25704
25705@geindex Exceptions (in gdb)
25706
25707You can set catchpoints that stop the program execution when your program
25708raises selected exceptions.
25709
25710
25711@itemize *
25712
25713@item
25714
25715@table @asis
25716
25717@item @emph{catch exception}
25718
25719Set a catchpoint that stops execution whenever (any task in the) program
25720raises any exception.
25721@end table
25722
25723@item
25724
25725@table @asis
25726
25727@item @emph{catch exception `name`}
25728
25729Set a catchpoint that stops execution whenever (any task in the) program
25730raises the exception @cite{name}.
25731@end table
25732
25733@item
25734
25735@table @asis
25736
25737@item @emph{catch exception unhandled}
25738
25739Set a catchpoint that stops executing whenever (any task in the) program
25740raises an exception for which there is no handler.
25741@end table
25742
25743@item
25744
25745@table @asis
25746
25747@item @emph{info exceptions}, @emph{info exceptions `regexp`}
25748
25749The @cite{info exceptions} command permits the user to examine all defined
25750exceptions within Ada programs. With a regular expression, @cite{regexp}, as
25751argument, prints out only those exceptions whose name matches @cite{regexp}.
25752@end table
25753@end itemize
25754
25755@geindex Tasks (in gdb)
25756
25757@node Ada Tasks,Debugging Generic Units,Stopping When Ada Exceptions Are Raised,Running and Debugging Ada Programs
25758@anchor{gnat_ugn/gnat_and_program_execution ada-tasks}@anchor{208}@anchor{gnat_ugn/gnat_and_program_execution id10}@anchor{209}
25759@subsection Ada Tasks
25760
25761
25762@cite{GDB} allows the following task-related commands:
25763
25764
25765@itemize *
25766
25767@item
25768
25769@table @asis
25770
25771@item @emph{info tasks}
25772
25773This command shows a list of current Ada tasks, as in the following example:
25774
25775@example
25776(gdb) info tasks
25777  ID       TID P-ID   Thread Pri State                 Name
25778   1   8088000   0   807e000  15 Child Activation Wait main_task
25779   2   80a4000   1   80ae000  15 Accept/Select Wait    b
25780   3   809a800   1   80a4800  15 Child Activation Wait a
25781*  4   80ae800   3   80b8000  15 Running               c
25782@end example
25783
25784In this listing, the asterisk before the first task indicates it to be the
25785currently running task. The first column lists the task ID that is used
25786to refer to tasks in the following commands.
25787@end table
25788@end itemize
25789
25790@geindex Breakpoints and tasks
25791
25792
25793@itemize *
25794
25795@item
25796@emph{break `linespec` task `taskid`}, @emph{break `linespec` task `taskid` if ...}
25797
25798@quotation
25799
25800These commands are like the @cite{break ... thread ...}.
25801@cite{linespec} specifies source lines.
25802
25803Use the qualifier @code{task @emph{taskid}} with a breakpoint command
25804to specify that you only want @cite{GDB} to stop the program when a
25805particular Ada task reaches this breakpoint. @cite{taskid} is one of the
25806numeric task identifiers assigned by @cite{GDB}, shown in the first
25807column of the @code{info tasks} display.
25808
25809If you do not specify @code{task @emph{taskid}} when you set a
25810breakpoint, the breakpoint applies to @emph{all} tasks of your
25811program.
25812
25813You can use the @cite{task} qualifier on conditional breakpoints as
25814well; in this case, place @code{task @emph{taskid}} before the
25815breakpoint condition (before the @cite{if}).
25816@end quotation
25817@end itemize
25818
25819@geindex Task switching (in gdb)
25820
25821
25822@itemize *
25823
25824@item
25825@emph{task `taskno`}
25826
25827@quotation
25828
25829This command allows switching to the task referred by @cite{taskno}. In
25830particular, this allows browsing of the backtrace of the specified
25831task. It is advisable to switch back to the original task before
25832continuing execution otherwise the scheduling of the program may be
25833perturbed.
25834@end quotation
25835@end itemize
25836
25837For more detailed information on the tasking support,
25838see @cite{Debugging with GDB}.
25839
25840@geindex Debugging Generic Units
25841
25842@geindex Generics
25843
25844@node Debugging Generic Units,Remote Debugging with gdbserver,Ada Tasks,Running and Debugging Ada Programs
25845@anchor{gnat_ugn/gnat_and_program_execution debugging-generic-units}@anchor{20a}@anchor{gnat_ugn/gnat_and_program_execution id11}@anchor{20b}
25846@subsection Debugging Generic Units
25847
25848
25849GNAT always uses code expansion for generic instantiation. This means that
25850each time an instantiation occurs, a complete copy of the original code is
25851made, with appropriate substitutions of formals by actuals.
25852
25853It is not possible to refer to the original generic entities in
25854@cite{GDB}, but it is always possible to debug a particular instance of
25855a generic, by using the appropriate expanded names. For example, if we have
25856
25857@quotation
25858
25859@example
25860procedure g is
25861
25862   generic package k is
25863      procedure kp (v1 : in out integer);
25864   end k;
25865
25866   package body k is
25867      procedure kp (v1 : in out integer) is
25868      begin
25869         v1 := v1 + 1;
25870      end kp;
25871   end k;
25872
25873   package k1 is new k;
25874   package k2 is new k;
25875
25876   var : integer := 1;
25877
25878begin
25879   k1.kp (var);
25880   k2.kp (var);
25881   k1.kp (var);
25882   k2.kp (var);
25883end;
25884@end example
25885@end quotation
25886
25887Then to break on a call to procedure kp in the k2 instance, simply
25888use the command:
25889
25890@quotation
25891
25892@example
25893(gdb) break g.k2.kp
25894@end example
25895@end quotation
25896
25897When the breakpoint occurs, you can step through the code of the
25898instance in the normal manner and examine the values of local variables, as for
25899other units.
25900
25901@geindex Remote Debugging with gdbserver
25902
25903@node Remote Debugging with gdbserver,GNAT Abnormal Termination or Failure to Terminate,Debugging Generic Units,Running and Debugging Ada Programs
25904@anchor{gnat_ugn/gnat_and_program_execution remote-debugging-with-gdbserver}@anchor{20c}@anchor{gnat_ugn/gnat_and_program_execution id12}@anchor{20d}
25905@subsection Remote Debugging with gdbserver
25906
25907
25908On platforms where gdbserver is supported, it is possible to use this tool
25909to debug your application remotely.  This can be useful in situations
25910where the program needs to be run on a target host that is different
25911from the host used for development, particularly when the target has
25912a limited amount of resources (either CPU and/or memory).
25913
25914To do so, start your program using gdbserver on the target machine.
25915gdbserver then automatically suspends the execution of your program
25916at its entry point, waiting for a debugger to connect to it.  The
25917following commands starts an application and tells gdbserver to
25918wait for a connection with the debugger on localhost port 4444.
25919
25920@quotation
25921
25922@example
25923$ gdbserver localhost:4444 program
25924Process program created; pid = 5685
25925Listening on port 4444
25926@end example
25927@end quotation
25928
25929Once gdbserver has started listening, we can tell the debugger to establish
25930a connection with this gdbserver, and then start the same debugging session
25931as if the program was being debugged on the same host, directly under
25932the control of GDB.
25933
25934@quotation
25935
25936@example
25937$ gdb program
25938(gdb) target remote targethost:4444
25939Remote debugging using targethost:4444
259400x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
25941(gdb) b foo.adb:3
25942Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
25943(gdb) continue
25944Continuing.
25945
25946Breakpoint 1, foo () at foo.adb:4
259474       end foo;
25948@end example
25949@end quotation
25950
25951It is also possible to use gdbserver to attach to an already running
25952program, in which case the execution of that program is simply suspended
25953until the connection between the debugger and gdbserver is established.
25954
25955For more information on how to use gdbserver, see the @emph{Using the gdbserver Program}
25956section in @cite{Debugging with GDB}.
25957GNAT provides support for gdbserver on x86-linux, x86-windows and x86_64-linux.
25958
25959@geindex Abnormal Termination or Failure to Terminate
25960
25961@node GNAT Abnormal Termination or Failure to Terminate,Naming Conventions for GNAT Source Files,Remote Debugging with gdbserver,Running and Debugging Ada Programs
25962@anchor{gnat_ugn/gnat_and_program_execution gnat-abnormal-termination-or-failure-to-terminate}@anchor{20e}@anchor{gnat_ugn/gnat_and_program_execution id13}@anchor{20f}
25963@subsection GNAT Abnormal Termination or Failure to Terminate
25964
25965
25966When presented with programs that contain serious errors in syntax
25967or semantics,
25968GNAT may on rare occasions  experience problems in operation, such
25969as aborting with a
25970segmentation fault or illegal memory access, raising an internal
25971exception, terminating abnormally, or failing to terminate at all.
25972In such cases, you can activate
25973various features of GNAT that can help you pinpoint the construct in your
25974program that is the likely source of the problem.
25975
25976The following strategies are presented in increasing order of
25977difficulty, corresponding to your experience in using GNAT and your
25978familiarity with compiler internals.
25979
25980
25981@itemize *
25982
25983@item
25984Run @emph{gcc} with the @emph{-gnatf}. This first
25985switch causes all errors on a given line to be reported. In its absence,
25986only the first error on a line is displayed.
25987
25988The @emph{-gnatdO} switch causes errors to be displayed as soon as they
25989are encountered, rather than after compilation is terminated. If GNAT
25990terminates prematurely or goes into an infinite loop, the last error
25991message displayed may help to pinpoint the culprit.
25992
25993@item
25994Run @emph{gcc} with the @emph{-v (verbose)} switch. In this
25995mode, @emph{gcc} produces ongoing information about the progress of the
25996compilation and provides the name of each procedure as code is
25997generated. This switch allows you to find which Ada procedure was being
25998compiled when it encountered a code generation problem.
25999@end itemize
26000
26001@geindex -gnatdc switch
26002
26003
26004@itemize *
26005
26006@item
26007Run @emph{gcc} with the @emph{-gnatdc} switch. This is a GNAT specific
26008switch that does for the front-end what @emph{-v} does
26009for the back end. The system prints the name of each unit,
26010either a compilation unit or nested unit, as it is being analyzed.
26011
26012@item
26013Finally, you can start
26014@cite{gdb} directly on the @cite{gnat1} executable. @cite{gnat1} is the
26015front-end of GNAT, and can be run independently (normally it is just
26016called from @emph{gcc}). You can use @cite{gdb} on @cite{gnat1} as you
26017would on a C program (but @ref{1fa,,The GNAT Debugger GDB} for caveats). The
26018@cite{where} command is the first line of attack; the variable
26019@cite{lineno} (seen by @cite{print lineno}), used by the second phase of
26020@cite{gnat1} and by the @emph{gcc} backend, indicates the source line at
26021which the execution stopped, and @cite{input_file name} indicates the name of
26022the source file.
26023@end itemize
26024
26025@node Naming Conventions for GNAT Source Files,Getting Internal Debugging Information,GNAT Abnormal Termination or Failure to Terminate,Running and Debugging Ada Programs
26026@anchor{gnat_ugn/gnat_and_program_execution naming-conventions-for-gnat-source-files}@anchor{210}@anchor{gnat_ugn/gnat_and_program_execution id14}@anchor{211}
26027@subsection Naming Conventions for GNAT Source Files
26028
26029
26030In order to examine the workings of the GNAT system, the following
26031brief description of its organization may be helpful:
26032
26033
26034@itemize *
26035
26036@item
26037Files with prefix @code{sc} contain the lexical scanner.
26038
26039@item
26040All files prefixed with @code{par} are components of the parser. The
26041numbers correspond to chapters of the Ada Reference Manual. For example,
26042parsing of select statements can be found in @code{par-ch9.adb}.
26043
26044@item
26045All files prefixed with @code{sem} perform semantic analysis. The
26046numbers correspond to chapters of the Ada standard. For example, all
26047issues involving context clauses can be found in @code{sem_ch10.adb}. In
26048addition, some features of the language require sufficient special processing
26049to justify their own semantic files: sem_aggr for aggregates, sem_disp for
26050dynamic dispatching, etc.
26051
26052@item
26053All files prefixed with @code{exp} perform normalization and
26054expansion of the intermediate representation (abstract syntax tree, or AST).
26055these files use the same numbering scheme as the parser and semantics files.
26056For example, the construction of record initialization procedures is done in
26057@code{exp_ch3.adb}.
26058
26059@item
26060The files prefixed with @code{bind} implement the binder, which
26061verifies the consistency of the compilation, determines an order of
26062elaboration, and generates the bind file.
26063
26064@item
26065The files @code{atree.ads} and @code{atree.adb} detail the low-level
26066data structures used by the front-end.
26067
26068@item
26069The files @code{sinfo.ads} and @code{sinfo.adb} detail the structure of
26070the abstract syntax tree as produced by the parser.
26071
26072@item
26073The files @code{einfo.ads} and @code{einfo.adb} detail the attributes of
26074all entities, computed during semantic analysis.
26075
26076@item
26077Library management issues are dealt with in files with prefix
26078@code{lib}.
26079
26080@geindex Annex A (in Ada Reference Manual)
26081
26082@item
26083Ada files with the prefix @code{a-} are children of @cite{Ada}, as
26084defined in Annex A.
26085
26086@geindex Annex B (in Ada reference Manual)
26087
26088@item
26089Files with prefix @code{i-} are children of @cite{Interfaces}, as
26090defined in Annex B.
26091
26092@geindex System (package in Ada Reference Manual)
26093
26094@item
26095Files with prefix @code{s-} are children of @cite{System}. This includes
26096both language-defined children and GNAT run-time routines.
26097
26098@geindex GNAT (package)
26099
26100@item
26101Files with prefix @code{g-} are children of @cite{GNAT}. These are useful
26102general-purpose packages, fully documented in their specs. All
26103the other @code{.c} files are modifications of common @emph{gcc} files.
26104@end itemize
26105
26106@node Getting Internal Debugging Information,Stack Traceback,Naming Conventions for GNAT Source Files,Running and Debugging Ada Programs
26107@anchor{gnat_ugn/gnat_and_program_execution id15}@anchor{212}@anchor{gnat_ugn/gnat_and_program_execution getting-internal-debugging-information}@anchor{213}
26108@subsection Getting Internal Debugging Information
26109
26110
26111Most compilers have internal debugging switches and modes. GNAT
26112does also, except GNAT internal debugging switches and modes are not
26113secret. A summary and full description of all the compiler and binder
26114debug flags are in the file @code{debug.adb}. You must obtain the
26115sources of the compiler to see the full detailed effects of these flags.
26116
26117The switches that print the source of the program (reconstructed from
26118the internal tree) are of general interest for user programs, as are the
26119options to print
26120the full internal tree, and the entity table (the symbol table
26121information). The reconstructed source provides a readable version of the
26122program after the front-end has completed analysis and  expansion,
26123and is useful when studying the performance of specific constructs.
26124For example, constraint checks are indicated, complex aggregates
26125are replaced with loops and assignments, and tasking primitives
26126are replaced with run-time calls.
26127
26128@geindex traceback
26129
26130@geindex stack traceback
26131
26132@geindex stack unwinding
26133
26134@node Stack Traceback,,Getting Internal Debugging Information,Running and Debugging Ada Programs
26135@anchor{gnat_ugn/gnat_and_program_execution stack-traceback}@anchor{214}@anchor{gnat_ugn/gnat_and_program_execution id16}@anchor{215}
26136@subsection Stack Traceback
26137
26138
26139Traceback is a mechanism to display the sequence of subprogram calls that
26140leads to a specified execution point in a program. Often (but not always)
26141the execution point is an instruction at which an exception has been raised.
26142This mechanism is also known as @emph{stack unwinding} because it obtains
26143its information by scanning the run-time stack and recovering the activation
26144records of all active subprograms. Stack unwinding is one of the most
26145important tools for program debugging.
26146
26147The first entry stored in traceback corresponds to the deepest calling level,
26148that is to say the subprogram currently executing the instruction
26149from which we want to obtain the traceback.
26150
26151Note that there is no runtime performance penalty when stack traceback
26152is enabled, and no exception is raised during program execution.
26153
26154@geindex traceback
26155@geindex non-symbolic
26156
26157@menu
26158* Non-Symbolic Traceback::
26159* Symbolic Traceback::
26160
26161@end menu
26162
26163@node Non-Symbolic Traceback,Symbolic Traceback,,Stack Traceback
26164@anchor{gnat_ugn/gnat_and_program_execution non-symbolic-traceback}@anchor{216}@anchor{gnat_ugn/gnat_and_program_execution id17}@anchor{217}
26165@subsubsection Non-Symbolic Traceback
26166
26167
26168Note: this feature is not supported on all platforms. See
26169@code{GNAT.Traceback} spec in @code{g-traceb.ads}
26170for a complete list of supported platforms.
26171
26172@subsubheading Tracebacks From an Unhandled Exception
26173
26174
26175A runtime non-symbolic traceback is a list of addresses of call instructions.
26176To enable this feature you must use the @emph{-E}
26177@cite{gnatbind}'s option. With this option a stack traceback is stored as part
26178of exception information. You can retrieve this information using the
26179@cite{addr2line} tool.
26180
26181Here is a simple example:
26182
26183@quotation
26184
26185@example
26186procedure STB is
26187
26188   procedure P1 is
26189   begin
26190      raise Constraint_Error;
26191   end P1;
26192
26193   procedure P2 is
26194   begin
26195      P1;
26196   end P2;
26197
26198begin
26199   P2;
26200end STB;
26201@end example
26202
26203@example
26204$ gnatmake stb -bargs -E
26205$ stb
26206
26207Execution terminated by unhandled exception
26208Exception name: CONSTRAINT_ERROR
26209Message: stb.adb:5
26210Call stack traceback locations:
262110x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
26212@end example
26213@end quotation
26214
26215As we see the traceback lists a sequence of addresses for the unhandled
26216exception @cite{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
26217guess that this exception come from procedure P1. To translate these
26218addresses into the source lines where the calls appear, the
26219@cite{addr2line} tool, described below, is invaluable. The use of this tool
26220requires the program to be compiled with debug information.
26221
26222@quotation
26223
26224@example
26225$ gnatmake -g stb -bargs -E
26226$ stb
26227
26228Execution terminated by unhandled exception
26229Exception name: CONSTRAINT_ERROR
26230Message: stb.adb:5
26231Call stack traceback locations:
262320x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
26233
26234$ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
26235   0x4011f1 0x77e892a4
26236
2623700401373 at d:/stb/stb.adb:5
262380040138B at d:/stb/stb.adb:10
262390040139C at d:/stb/stb.adb:14
2624000401335 at d:/stb/b~stb.adb:104
26241004011C4 at /build/.../crt1.c:200
26242004011F1 at /build/.../crt1.c:222
2624377E892A4 in ?? at ??:0
26244@end example
26245@end quotation
26246
26247The @cite{addr2line} tool has several other useful options:
26248
26249@quotation
26250
26251
26252@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
26253@item
26254
26255@code{--functions}
26256
26257@tab
26258
26259to get the function name corresponding to any location
26260
26261@item
26262
26263@code{--demangle=gnat}
26264
26265@tab
26266
26267to use the gnat decoding mode for the function names.
26268Note that for binutils version 2.9.x the option is
26269simply @code{--demangle}.
26270
26271@end multitable
26272
26273
26274@example
26275$ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
26276   0x40139c 0x401335 0x4011c4 0x4011f1
26277
2627800401373 in stb.p1 at d:/stb/stb.adb:5
262790040138B in stb.p2 at d:/stb/stb.adb:10
262800040139C in stb at d:/stb/stb.adb:14
2628100401335 in main at d:/stb/b~stb.adb:104
26282004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
26283004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
26284@end example
26285@end quotation
26286
26287From this traceback we can see that the exception was raised in
26288@code{stb.adb} at line 5, which was reached from a procedure call in
26289@code{stb.adb} at line 10, and so on. The @code{b~std.adb} is the binder file,
26290which contains the call to the main program.
26291@ref{123,,Running gnatbind}. The remaining entries are assorted runtime routines,
26292and the output will vary from platform to platform.
26293
26294It is also possible to use @cite{GDB} with these traceback addresses to debug
26295the program. For example, we can break at a given code location, as reported
26296in the stack traceback:
26297
26298@quotation
26299
26300@example
26301$ gdb -nw stb
26302@end example
26303@end quotation
26304
26305Furthermore, this feature is not implemented inside Windows DLL. Only
26306the non-symbolic traceback is reported in this case.
26307
26308@quotation
26309
26310@example
26311(gdb) break *0x401373
26312Breakpoint 1 at 0x401373: file stb.adb, line 5.
26313@end example
26314@end quotation
26315
26316It is important to note that the stack traceback addresses
26317do not change when debug information is included. This is particularly useful
26318because it makes it possible to release software without debug information (to
26319minimize object size), get a field report that includes a stack traceback
26320whenever an internal bug occurs, and then be able to retrieve the sequence
26321of calls with the same program compiled with debug information.
26322
26323@subsubheading Tracebacks From Exception Occurrences
26324
26325
26326Non-symbolic tracebacks are obtained by using the @emph{-E} binder argument.
26327The stack traceback is attached to the exception information string, and can
26328be retrieved in an exception handler within the Ada program, by means of the
26329Ada facilities defined in @cite{Ada.Exceptions}. Here is a simple example:
26330
26331@quotation
26332
26333@example
26334with Ada.Text_IO;
26335with Ada.Exceptions;
26336
26337procedure STB is
26338
26339   use Ada;
26340   use Ada.Exceptions;
26341
26342   procedure P1 is
26343      K : Positive := 1;
26344   begin
26345      K := K - 1;
26346   exception
26347      when E : others =>
26348         Text_IO.Put_Line (Exception_Information (E));
26349   end P1;
26350
26351   procedure P2 is
26352   begin
26353      P1;
26354   end P2;
26355
26356begin
26357   P2;
26358end STB;
26359@end example
26360@end quotation
26361
26362This program will output:
26363
26364@quotation
26365
26366@example
26367$ stb
26368
26369Exception name: CONSTRAINT_ERROR
26370Message: stb.adb:12
26371Call stack traceback locations:
263720x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
26373@end example
26374@end quotation
26375
26376@subsubheading Tracebacks From Anywhere in a Program
26377
26378
26379It is also possible to retrieve a stack traceback from anywhere in a
26380program. For this you need to
26381use the @cite{GNAT.Traceback} API. This package includes a procedure called
26382@cite{Call_Chain} that computes a complete stack traceback, as well as useful
26383display procedures described below. It is not necessary to use the
26384@emph{-E gnatbind} option in this case, because the stack traceback mechanism
26385is invoked explicitly.
26386
26387In the following example we compute a traceback at a specific location in
26388the program, and we display it using @cite{GNAT.Debug_Utilities.Image} to
26389convert addresses to strings:
26390
26391@quotation
26392
26393@example
26394with Ada.Text_IO;
26395with GNAT.Traceback;
26396with GNAT.Debug_Utilities;
26397
26398procedure STB is
26399
26400   use Ada;
26401   use GNAT;
26402   use GNAT.Traceback;
26403
26404   procedure P1 is
26405      TB  : Tracebacks_Array (1 .. 10);
26406      --  We are asking for a maximum of 10 stack frames.
26407      Len : Natural;
26408      --  Len will receive the actual number of stack frames returned.
26409   begin
26410      Call_Chain (TB, Len);
26411
26412      Text_IO.Put ("In STB.P1 : ");
26413
26414      for K in 1 .. Len loop
26415         Text_IO.Put (Debug_Utilities.Image (TB (K)));
26416         Text_IO.Put (' ');
26417      end loop;
26418
26419      Text_IO.New_Line;
26420   end P1;
26421
26422   procedure P2 is
26423   begin
26424      P1;
26425   end P2;
26426
26427begin
26428   P2;
26429end STB;
26430@end example
26431
26432@example
26433$ gnatmake -g stb
26434$ stb
26435
26436In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
2643716#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
26438@end example
26439@end quotation
26440
26441You can then get further information by invoking the @cite{addr2line}
26442tool as described earlier (note that the hexadecimal addresses
26443need to be specified in C format, with a leading '0x').
26444
26445@geindex traceback
26446@geindex symbolic
26447
26448@node Symbolic Traceback,,Non-Symbolic Traceback,Stack Traceback
26449@anchor{gnat_ugn/gnat_and_program_execution id18}@anchor{218}@anchor{gnat_ugn/gnat_and_program_execution symbolic-traceback}@anchor{219}
26450@subsubsection Symbolic Traceback
26451
26452
26453A symbolic traceback is a stack traceback in which procedure names are
26454associated with each code location.
26455
26456Note that this feature is not supported on all platforms. See
26457@code{GNAT.Traceback.Symbolic} spec in @code{g-trasym.ads} for a complete
26458list of currently supported platforms.
26459
26460Note that the symbolic traceback requires that the program be compiled
26461with debug information. If it is not compiled with debug information
26462only the non-symbolic information will be valid.
26463
26464@subsubheading Tracebacks From Exception Occurrences
26465
26466
26467Here is an example:
26468
26469@quotation
26470
26471@example
26472with Ada.Text_IO;
26473with GNAT.Traceback.Symbolic;
26474
26475procedure STB is
26476
26477   procedure P1 is
26478   begin
26479      raise Constraint_Error;
26480   end P1;
26481
26482   procedure P2 is
26483   begin
26484      P1;
26485   end P2;
26486
26487   procedure P3 is
26488   begin
26489      P2;
26490   end P3;
26491
26492begin
26493   P3;
26494exception
26495   when E : others =>
26496      Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
26497end STB;
26498@end example
26499
26500@example
26501$ gnatmake -g .\stb -bargs -E
26502$ stb
26503
265040040149F in stb.p1 at stb.adb:8
26505004014B7 in stb.p2 at stb.adb:13
26506004014CF in stb.p3 at stb.adb:18
26507004015DD in ada.stb at stb.adb:22
2650800401461 in main at b~stb.adb:168
26509004011C4 in __mingw_CRTStartup at crt1.c:200
26510004011F1 in mainCRTStartup at crt1.c:222
2651177E892A4 in ?? at ??:0
26512@end example
26513@end quotation
26514
26515In the above example the @code{.\} syntax in the @emph{gnatmake} command
26516is currently required by @emph{addr2line} for files that are in
26517the current working directory.
26518Moreover, the exact sequence of linker options may vary from platform
26519to platform.
26520The above @emph{-largs} section is for Windows platforms. By contrast,
26521under Unix there is no need for the @emph{-largs} section.
26522Differences across platforms are due to details of linker implementation.
26523
26524@subsubheading Tracebacks From Anywhere in a Program
26525
26526
26527It is possible to get a symbolic stack traceback
26528from anywhere in a program, just as for non-symbolic tracebacks.
26529The first step is to obtain a non-symbolic
26530traceback, and then call @cite{Symbolic_Traceback} to compute the symbolic
26531information. Here is an example:
26532
26533@quotation
26534
26535@example
26536with Ada.Text_IO;
26537with GNAT.Traceback;
26538with GNAT.Traceback.Symbolic;
26539
26540procedure STB is
26541
26542   use Ada;
26543   use GNAT.Traceback;
26544   use GNAT.Traceback.Symbolic;
26545
26546   procedure P1 is
26547      TB  : Tracebacks_Array (1 .. 10);
26548      --  We are asking for a maximum of 10 stack frames.
26549      Len : Natural;
26550      --  Len will receive the actual number of stack frames returned.
26551   begin
26552      Call_Chain (TB, Len);
26553      Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
26554   end P1;
26555
26556   procedure P2 is
26557   begin
26558      P1;
26559   end P2;
26560
26561begin
26562   P2;
26563end STB;
26564@end example
26565@end quotation
26566
26567@subsubheading Automatic Symbolic Tracebacks
26568
26569
26570Symbolic tracebacks may also be enabled by using the -Es switch to gnatbind (as
26571in @cite{gprbuild -g ... -bargs -Es}).
26572This will cause the Exception_Information to contain a symbolic traceback,
26573which will also be printed if an unhandled exception terminates the
26574program.
26575
26576@geindex Code Coverage
26577
26578@geindex Profiling
26579
26580@node Code Coverage and Profiling,Improving Performance,Running and Debugging Ada Programs,GNAT and Program Execution
26581@anchor{gnat_ugn/gnat_and_program_execution id19}@anchor{1f4}@anchor{gnat_ugn/gnat_and_program_execution code-coverage-and-profiling}@anchor{27}
26582@section Code Coverage and Profiling
26583
26584
26585This section describes how to use the @cite{gcov} coverage testing tool and
26586the @cite{gprof} profiler tool on Ada programs.
26587
26588@geindex gcov
26589
26590@menu
26591* Code Coverage of Ada Programs with gcov::
26592* Profiling an Ada Program with gprof::
26593
26594@end menu
26595
26596@node Code Coverage of Ada Programs with gcov,Profiling an Ada Program with gprof,,Code Coverage and Profiling
26597@anchor{gnat_ugn/gnat_and_program_execution id20}@anchor{21a}@anchor{gnat_ugn/gnat_and_program_execution code-coverage-of-ada-programs-with-gcov}@anchor{21b}
26598@subsection Code Coverage of Ada Programs with gcov
26599
26600
26601@cite{gcov} is a test coverage program: it analyzes the execution of a given
26602program on selected tests, to help you determine the portions of the program
26603that are still untested.
26604
26605@cite{gcov} is part of the GCC suite, and is described in detail in the GCC
26606User's Guide. You can refer to this documentation for a more complete
26607description.
26608
26609This chapter provides a quick startup guide, and
26610details some GNAT-specific features.
26611
26612@menu
26613* Quick startup guide::
26614* GNAT specifics::
26615
26616@end menu
26617
26618@node Quick startup guide,GNAT specifics,,Code Coverage of Ada Programs with gcov
26619@anchor{gnat_ugn/gnat_and_program_execution id21}@anchor{21c}@anchor{gnat_ugn/gnat_and_program_execution quick-startup-guide}@anchor{21d}
26620@subsubsection Quick startup guide
26621
26622
26623In order to perform coverage analysis of a program using @cite{gcov}, several
26624steps are needed:
26625
26626
26627@enumerate
26628
26629@item
26630Instrument the code during the compilation process,
26631
26632@item
26633Execute the instrumented program, and
26634
26635@item
26636Invoke the @cite{gcov} tool to generate the coverage results.
26637@end enumerate
26638
26639@geindex -fprofile-arcs (gcc)
26640
26641@geindex -ftest-coverage (gcc
26642
26643@geindex -fprofile-arcs (gnatbind)
26644
26645The code instrumentation needed by gcov is created at the object level.
26646The source code is not modified in any way, because the instrumentation code is
26647inserted by gcc during the compilation process. To compile your code with code
26648coverage activated, you need to recompile your whole project using the
26649switches
26650@cite{-fprofile-arcs} and @cite{-ftest-coverage}, and link it using
26651@cite{-fprofile-arcs}.
26652
26653@quotation
26654
26655@example
26656$ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \\
26657   -largs -fprofile-arcs
26658@end example
26659@end quotation
26660
26661This compilation process will create @code{.gcno} files together with
26662the usual object files.
26663
26664Once the program is compiled with coverage instrumentation, you can
26665run it as many times as needed -- on portions of a test suite for
26666example. The first execution will produce @code{.gcda} files at the
26667same location as the @code{.gcno} files.  Subsequent executions
26668will update those files, so that a cumulative result of the covered
26669portions of the program is generated.
26670
26671Finally, you need to call the @cite{gcov} tool. The different options of
26672@cite{gcov} are described in the GCC User's Guide, section 'Invoking gcov'.
26673
26674This will create annotated source files with a @code{.gcov} extension:
26675@code{my_main.adb} file will be analyzed in @code{my_main.adb.gcov}.
26676
26677@node GNAT specifics,,Quick startup guide,Code Coverage of Ada Programs with gcov
26678@anchor{gnat_ugn/gnat_and_program_execution gnat-specifics}@anchor{21e}@anchor{gnat_ugn/gnat_and_program_execution id22}@anchor{21f}
26679@subsubsection GNAT specifics
26680
26681
26682Because of Ada semantics, portions of the source code may be shared among
26683several object files. This is the case for example when generics are
26684involved, when inlining is active  or when declarations generate  initialisation
26685calls. In order to take
26686into account this shared code, you need to call @cite{gcov} on all
26687source files of the tested program at once.
26688
26689The list of source files might exceed the system's maximum command line
26690length. In order to bypass this limitation, a new mechanism has been
26691implemented in @cite{gcov}: you can now list all your project's files into a
26692text file, and provide this file to gcov as a parameter,  preceded by a @code{@@}
26693(e.g. @code{gcov @@mysrclist.txt}).
26694
26695Note that on AIX compiling a static library with @cite{-fprofile-arcs} is
26696not supported as there can be unresolved symbols during the final link.
26697
26698@geindex gprof
26699
26700@geindex Profiling
26701
26702@node Profiling an Ada Program with gprof,,Code Coverage of Ada Programs with gcov,Code Coverage and Profiling
26703@anchor{gnat_ugn/gnat_and_program_execution profiling-an-ada-program-with-gprof}@anchor{220}@anchor{gnat_ugn/gnat_and_program_execution id23}@anchor{221}
26704@subsection Profiling an Ada Program with gprof
26705
26706
26707This section is not meant to be an exhaustive documentation of @cite{gprof}.
26708Full documentation for it can be found in the @cite{GNU Profiler User's Guide}
26709documentation that is part of this GNAT distribution.
26710
26711Profiling a program helps determine the parts of a program that are executed
26712most often, and are therefore the most time-consuming.
26713
26714@cite{gprof} is the standard GNU profiling tool; it has been enhanced to
26715better handle Ada programs and multitasking.
26716It is currently supported on the following platforms
26717
26718
26719@itemize *
26720
26721@item
26722linux x86/x86_64
26723
26724@item
26725solaris sparc/sparc64/x86
26726
26727@item
26728windows x86
26729@end itemize
26730
26731In order to profile a program using @cite{gprof}, several steps are needed:
26732
26733
26734@enumerate
26735
26736@item
26737Instrument the code, which requires a full recompilation of the project with the
26738proper switches.
26739
26740@item
26741Execute the program under the analysis conditions, i.e. with the desired
26742input.
26743
26744@item
26745Analyze the results using the @cite{gprof} tool.
26746@end enumerate
26747
26748The following sections detail the different steps, and indicate how
26749to interpret the results.
26750
26751@menu
26752* Compilation for profiling::
26753* Program execution::
26754* Running gprof::
26755* Interpretation of profiling results::
26756
26757@end menu
26758
26759@node Compilation for profiling,Program execution,,Profiling an Ada Program with gprof
26760@anchor{gnat_ugn/gnat_and_program_execution id24}@anchor{222}@anchor{gnat_ugn/gnat_and_program_execution compilation-for-profiling}@anchor{223}
26761@subsubsection Compilation for profiling
26762
26763
26764@geindex -pg (gcc)
26765@geindex for profiling
26766
26767@geindex -pg (gnatlink)
26768@geindex for profiling
26769
26770In order to profile a program the first step is to tell the compiler
26771to generate the necessary profiling information. The compiler switch to be used
26772is @code{-pg}, which must be added to other compilation switches. This
26773switch needs to be specified both during compilation and link stages, and can
26774be specified once when using gnatmake:
26775
26776@quotation
26777
26778@example
26779$ gnatmake -f -pg -P my_project
26780@end example
26781@end quotation
26782
26783Note that only the objects that were compiled with the @code{-pg} switch will
26784be profiled; if you need to profile your whole project, use the @code{-f}
26785gnatmake switch to force full recompilation.
26786
26787@node Program execution,Running gprof,Compilation for profiling,Profiling an Ada Program with gprof
26788@anchor{gnat_ugn/gnat_and_program_execution program-execution}@anchor{224}@anchor{gnat_ugn/gnat_and_program_execution id25}@anchor{225}
26789@subsubsection Program execution
26790
26791
26792Once the program has been compiled for profiling, you can run it as usual.
26793
26794The only constraint imposed by profiling is that the program must terminate
26795normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
26796properly analyzed.
26797
26798Once the program completes execution, a data file called @code{gmon.out} is
26799generated in the directory where the program was launched from. If this file
26800already exists, it will be overwritten.
26801
26802@node Running gprof,Interpretation of profiling results,Program execution,Profiling an Ada Program with gprof
26803@anchor{gnat_ugn/gnat_and_program_execution running-gprof}@anchor{226}@anchor{gnat_ugn/gnat_and_program_execution id26}@anchor{227}
26804@subsubsection Running gprof
26805
26806
26807The @cite{gprof} tool is called as follow:
26808
26809@quotation
26810
26811@example
26812$ gprof my_prog gmon.out
26813@end example
26814@end quotation
26815
26816or simply:
26817
26818@quotation
26819
26820@example
26821$  gprof my_prog
26822@end example
26823@end quotation
26824
26825The complete form of the gprof command line is the following:
26826
26827@quotation
26828
26829@example
26830$ gprof [switches] [executable [data-file]]
26831@end example
26832@end quotation
26833
26834@cite{gprof} supports numerous switches. The order of these
26835switch does not matter. The full list of options can be found in
26836the GNU Profiler User's Guide documentation that comes with this documentation.
26837
26838The following is the subset of those switches that is most relevant:
26839
26840@geindex --demangle (gprof)
26841
26842
26843@table @asis
26844
26845@item @code{--demangle[=@emph{style}]}, @code{--no-demangle}
26846
26847These options control whether symbol names should be demangled when
26848printing output.  The default is to demangle C++ symbols.  The
26849@code{--no-demangle} option may be used to turn off demangling. Different
26850compilers have different mangling styles.  The optional demangling style
26851argument can be used to choose an appropriate demangling style for your
26852compiler, in particular Ada symbols generated by GNAT can be demangled using
26853@code{--demangle=gnat}.
26854@end table
26855
26856@geindex -e (gprof)
26857
26858
26859@table @asis
26860
26861@item @code{-e @emph{function_name}}
26862
26863The @code{-e @emph{function}} option tells @cite{gprof} not to print
26864information about the function @cite{function_name} (and its
26865children...) in the call graph.  The function will still be listed
26866as a child of any functions that call it, but its index number will be
26867shown as @code{[not printed]}.  More than one @code{-e} option may be
26868given; only one @cite{function_name} may be indicated with each @code{-e}
26869option.
26870@end table
26871
26872@geindex -E (gprof)
26873
26874
26875@table @asis
26876
26877@item @code{-E @emph{function_name}}
26878
26879The @code{-E @emph{function}} option works like the @code{-e} option, but
26880execution time spent in the function (and children who were not called from
26881anywhere else), will not be used to compute the percentages-of-time for
26882the call graph.  More than one @code{-E} option may be given; only one
26883@cite{function_name} may be indicated with each @code{-E} option.
26884@end table
26885
26886@geindex -f (gprof)
26887
26888
26889@table @asis
26890
26891@item @code{-f @emph{function_name}}
26892
26893The @code{-f @emph{function}} option causes @cite{gprof} to limit the
26894call graph to the function @cite{function_name} and its children (and
26895their children...).  More than one @code{-f} option may be given;
26896only one @cite{function_name} may be indicated with each @code{-f}
26897option.
26898@end table
26899
26900@geindex -F (gprof)
26901
26902
26903@table @asis
26904
26905@item @code{-F @emph{function_name}}
26906
26907The @code{-F @emph{function}} option works like the @code{-f} option, but
26908only time spent in the function and its children (and their
26909children...) will be used to determine total-time and
26910percentages-of-time for the call graph.  More than one @code{-F} option
26911may be given; only one @cite{function_name} may be indicated with each
26912@code{-F} option.  The @code{-F} option overrides the @code{-E} option.
26913@end table
26914
26915@node Interpretation of profiling results,,Running gprof,Profiling an Ada Program with gprof
26916@anchor{gnat_ugn/gnat_and_program_execution id27}@anchor{228}@anchor{gnat_ugn/gnat_and_program_execution interpretation-of-profiling-results}@anchor{229}
26917@subsubsection Interpretation of profiling results
26918
26919
26920The results of the profiling analysis are represented by two arrays: the
26921'flat profile' and the 'call graph'. Full documentation of those outputs
26922can be found in the GNU Profiler User's Guide.
26923
26924The flat profile shows the time spent in each function of the program, and how
26925many time it has been called. This allows you to locate easily the most
26926time-consuming functions.
26927
26928The call graph shows, for each subprogram, the subprograms that call it,
26929and the subprograms that it calls. It also provides an estimate of the time
26930spent in each of those callers/called subprograms.
26931
26932@node Improving Performance,Overflow Check Handling in GNAT,Code Coverage and Profiling,GNAT and Program Execution
26933@anchor{gnat_ugn/gnat_and_program_execution improving-performance}@anchor{28}@anchor{gnat_ugn/gnat_and_program_execution id28}@anchor{1f5}
26934@section Improving Performance
26935
26936
26937@geindex Improving performance
26938
26939This section presents several topics related to program performance.
26940It first describes some of the tradeoffs that need to be considered
26941and some of the techniques for making your program run faster.
26942
26943
26944It then documents the unused subprogram/data elimination feature,
26945which can reduce the size of program executables.
26946
26947@menu
26948* Performance Considerations::
26949* Text_IO Suggestions::
26950* Reducing Size of Executables with Unused Subprogram/Data Elimination::
26951
26952@end menu
26953
26954@node Performance Considerations,Text_IO Suggestions,,Improving Performance
26955@anchor{gnat_ugn/gnat_and_program_execution id29}@anchor{22a}@anchor{gnat_ugn/gnat_and_program_execution performance-considerations}@anchor{22b}
26956@subsection Performance Considerations
26957
26958
26959The GNAT system provides a number of options that allow a trade-off
26960between
26961
26962
26963@itemize *
26964
26965@item
26966performance of the generated code
26967
26968@item
26969speed of compilation
26970
26971@item
26972minimization of dependences and recompilation
26973
26974@item
26975the degree of run-time checking.
26976@end itemize
26977
26978The defaults (if no options are selected) aim at improving the speed
26979of compilation and minimizing dependences, at the expense of performance
26980of the generated code:
26981
26982
26983@itemize *
26984
26985@item
26986no optimization
26987
26988@item
26989no inlining of subprogram calls
26990
26991@item
26992all run-time checks enabled except overflow and elaboration checks
26993@end itemize
26994
26995These options are suitable for most program development purposes. This
26996section describes how you can modify these choices, and also provides
26997some guidelines on debugging optimized code.
26998
26999@menu
27000* Controlling Run-Time Checks::
27001* Use of Restrictions::
27002* Optimization Levels::
27003* Debugging Optimized Code::
27004* Inlining of Subprograms::
27005* Floating_Point_Operations::
27006* Vectorization of loops::
27007* Other Optimization Switches::
27008* Optimization and Strict Aliasing::
27009* Aliased Variables and Optimization::
27010* Atomic Variables and Optimization::
27011* Passive Task Optimization::
27012
27013@end menu
27014
27015@node Controlling Run-Time Checks,Use of Restrictions,,Performance Considerations
27016@anchor{gnat_ugn/gnat_and_program_execution controlling-run-time-checks}@anchor{22c}@anchor{gnat_ugn/gnat_and_program_execution id30}@anchor{22d}
27017@subsubsection Controlling Run-Time Checks
27018
27019
27020By default, GNAT generates all run-time checks, except stack overflow
27021checks, and checks for access before elaboration on subprogram
27022calls. The latter are not required in default mode, because all
27023necessary checking is done at compile time.
27024
27025@geindex -gnatp (gcc)
27026
27027@geindex -gnato (gcc)
27028
27029The gnat switch, @emph{-gnatp} allows this default to be modified. See
27030@ref{101,,Run-Time Checks}.
27031
27032Our experience is that the default is suitable for most development
27033purposes.
27034
27035Elaboration checks are off by default, and also not needed by default, since
27036GNAT uses a static elaboration analysis approach that avoids the need for
27037run-time checking. This manual contains a full chapter discussing the issue
27038of elaboration checks, and if the default is not satisfactory for your use,
27039you should read this chapter.
27040
27041For validity checks, the minimal checks required by the Ada Reference
27042Manual (for case statements and assignments to array elements) are on
27043by default. These can be suppressed by use of the @emph{-gnatVn} switch.
27044Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
27045is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
27046it may be reasonable to routinely use @emph{-gnatVn}. Validity checks
27047are also suppressed entirely if @emph{-gnatp} is used.
27048
27049@geindex Overflow checks
27050
27051@geindex Checks
27052@geindex overflow
27053
27054@geindex Suppress
27055
27056@geindex Unsuppress
27057
27058@geindex pragma Suppress
27059
27060@geindex pragma Unsuppress
27061
27062Note that the setting of the switches controls the default setting of
27063the checks. They may be modified using either @cite{pragma Suppress} (to
27064remove checks) or @cite{pragma Unsuppress} (to add back suppressed
27065checks) in the program source.
27066
27067@node Use of Restrictions,Optimization Levels,Controlling Run-Time Checks,Performance Considerations
27068@anchor{gnat_ugn/gnat_and_program_execution use-of-restrictions}@anchor{22e}@anchor{gnat_ugn/gnat_and_program_execution id31}@anchor{22f}
27069@subsubsection Use of Restrictions
27070
27071
27072The use of pragma Restrictions allows you to control which features are
27073permitted in your program. Apart from the obvious point that if you avoid
27074relatively expensive features like finalization (enforceable by the use
27075of pragma Restrictions (No_Finalization), the use of this pragma does not
27076affect the generated code in most cases.
27077
27078One notable exception to this rule is that the possibility of task abort
27079results in some distributed overhead, particularly if finalization or
27080exception handlers are used. The reason is that certain sections of code
27081have to be marked as non-abortable.
27082
27083If you use neither the @cite{abort} statement, nor asynchronous transfer
27084of control (@cite{select ... then abort}), then this distributed overhead
27085is removed, which may have a general positive effect in improving
27086overall performance.  Especially code involving frequent use of tasking
27087constructs and controlled types will show much improved performance.
27088The relevant restrictions pragmas are
27089
27090@quotation
27091
27092@example
27093pragma Restrictions (No_Abort_Statements);
27094pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
27095@end example
27096@end quotation
27097
27098It is recommended that these restriction pragmas be used if possible. Note
27099that this also means that you can write code without worrying about the
27100possibility of an immediate abort at any point.
27101
27102@node Optimization Levels,Debugging Optimized Code,Use of Restrictions,Performance Considerations
27103@anchor{gnat_ugn/gnat_and_program_execution id32}@anchor{230}@anchor{gnat_ugn/gnat_and_program_execution optimization-levels}@anchor{104}
27104@subsubsection Optimization Levels
27105
27106
27107@geindex -O (gcc)
27108
27109Without any optimization option,
27110the compiler's goal is to reduce the cost of
27111compilation and to make debugging produce the expected results.
27112Statements are independent: if you stop the program with a breakpoint between
27113statements, you can then assign a new value to any variable or change
27114the program counter to any other statement in the subprogram and get exactly
27115the results you would expect from the source code.
27116
27117Turning on optimization makes the compiler attempt to improve the
27118performance and/or code size at the expense of compilation time and
27119possibly the ability to debug the program.
27120
27121If you use multiple
27122-O options, with or without level numbers,
27123the last such option is the one that is effective.
27124
27125The default is optimization off. This results in the fastest compile
27126times, but GNAT makes absolutely no attempt to optimize, and the
27127generated programs are considerably larger and slower than when
27128optimization is enabled. You can use the
27129@emph{-O} switch (the permitted forms are @emph{-O0}, @emph{-O1}
27130@emph{-O2}, @emph{-O3}, and @emph{-Os})
27131to @emph{gcc} to control the optimization level:
27132
27133
27134@itemize *
27135
27136@item
27137
27138@table @asis
27139
27140@item @emph{-O0}
27141
27142No optimization (the default);
27143generates unoptimized code but has
27144the fastest compilation time.
27145
27146Note that many other compilers do fairly extensive optimization
27147even if 'no optimization' is specified. With gcc, it is
27148very unusual to use -O0 for production if
27149execution time is of any concern, since -O0
27150really does mean no optimization at all. This difference between
27151gcc and other compilers should be kept in mind when doing
27152performance comparisons.
27153@end table
27154
27155@item
27156
27157@table @asis
27158
27159@item @emph{-O1}
27160
27161Moderate optimization;
27162optimizes reasonably well but does not
27163degrade compilation time significantly.
27164@end table
27165
27166@item
27167
27168@table @asis
27169
27170@item @emph{-O2}
27171
27172Full optimization;
27173generates highly optimized code and has
27174the slowest compilation time.
27175@end table
27176
27177@item
27178
27179@table @asis
27180
27181@item @emph{-O3}
27182
27183Full optimization as in @emph{-O2};
27184also uses more aggressive automatic inlining of subprograms within a unit
27185(@ref{117,,Inlining of Subprograms}) and attempts to vectorize loops.
27186@end table
27187
27188@item
27189
27190@table @asis
27191
27192@item @emph{-Os}
27193
27194Optimize space usage (code and data) of resulting program.
27195@end table
27196@end itemize
27197
27198Higher optimization levels perform more global transformations on the
27199program and apply more expensive analysis algorithms in order to generate
27200faster and more compact code. The price in compilation time, and the
27201resulting improvement in execution time,
27202both depend on the particular application and the hardware environment.
27203You should experiment to find the best level for your application.
27204
27205Since the precise set of optimizations done at each level will vary from
27206release to release (and sometime from target to target), it is best to think
27207of the optimization settings in general terms.
27208See the @emph{Options That Control Optimization} section in
27209@cite{Using the GNU Compiler Collection (GCC)}
27210for details about
27211the @emph{-O} settings and a number of @emph{-f} options that
27212individually enable or disable specific optimizations.
27213
27214Unlike some other compilation systems, @emph{gcc} has
27215been tested extensively at all optimization levels. There are some bugs
27216which appear only with optimization turned on, but there have also been
27217bugs which show up only in @emph{unoptimized} code. Selecting a lower
27218level of optimization does not improve the reliability of the code
27219generator, which in practice is highly reliable at all optimization
27220levels.
27221
27222Note regarding the use of @emph{-O3}: The use of this optimization level
27223is generally discouraged with GNAT, since it often results in larger
27224executables which may run more slowly. See further discussion of this point
27225in @ref{117,,Inlining of Subprograms}.
27226
27227@node Debugging Optimized Code,Inlining of Subprograms,Optimization Levels,Performance Considerations
27228@anchor{gnat_ugn/gnat_and_program_execution id33}@anchor{231}@anchor{gnat_ugn/gnat_and_program_execution debugging-optimized-code}@anchor{232}
27229@subsubsection Debugging Optimized Code
27230
27231
27232@geindex Debugging optimized code
27233
27234@geindex Optimization and debugging
27235
27236Although it is possible to do a reasonable amount of debugging at
27237nonzero optimization levels,
27238the higher the level the more likely that
27239source-level constructs will have been eliminated by optimization.
27240For example, if a loop is strength-reduced, the loop
27241control variable may be completely eliminated and thus cannot be
27242displayed in the debugger.
27243This can only happen at @emph{-O2} or @emph{-O3}.
27244Explicit temporary variables that you code might be eliminated at
27245level @emph{-O1} or higher.
27246
27247@geindex -g (gcc)
27248
27249The use of the @emph{-g} switch,
27250which is needed for source-level debugging,
27251affects the size of the program executable on disk,
27252and indeed the debugging information can be quite large.
27253However, it has no effect on the generated code (and thus does not
27254degrade performance)
27255
27256Since the compiler generates debugging tables for a compilation unit before
27257it performs optimizations, the optimizing transformations may invalidate some
27258of the debugging data.  You therefore need to anticipate certain
27259anomalous situations that may arise while debugging optimized code.
27260These are the most common cases:
27261
27262
27263@itemize *
27264
27265@item
27266@emph{The 'hopping Program Counter':}  Repeated @cite{step} or @cite{next}
27267commands show
27268the PC bouncing back and forth in the code.  This may result from any of
27269the following optimizations:
27270
27271
27272@itemize -
27273
27274@item
27275@emph{Common subexpression elimination:} using a single instance of code for a
27276quantity that the source computes several times.  As a result you
27277may not be able to stop on what looks like a statement.
27278
27279@item
27280@emph{Invariant code motion:} moving an expression that does not change within a
27281loop, to the beginning of the loop.
27282
27283@item
27284@emph{Instruction scheduling:} moving instructions so as to
27285overlap loads and stores (typically) with other code, or in
27286general to move computations of values closer to their uses. Often
27287this causes you to pass an assignment statement without the assignment
27288happening and then later bounce back to the statement when the
27289value is actually needed.  Placing a breakpoint on a line of code
27290and then stepping over it may, therefore, not always cause all the
27291expected side-effects.
27292@end itemize
27293
27294@item
27295@emph{The 'big leap':} More commonly known as @emph{cross-jumping}, in which
27296two identical pieces of code are merged and the program counter suddenly
27297jumps to a statement that is not supposed to be executed, simply because
27298it (and the code following) translates to the same thing as the code
27299that @emph{was} supposed to be executed.  This effect is typically seen in
27300sequences that end in a jump, such as a @cite{goto}, a @cite{return}, or
27301a @cite{break} in a C @cite{switch} statement.
27302
27303@item
27304@emph{The 'roving variable':} The symptom is an unexpected value in a variable.
27305There are various reasons for this effect:
27306
27307
27308@itemize -
27309
27310@item
27311In a subprogram prologue, a parameter may not yet have been moved to its
27312'home'.
27313
27314@item
27315A variable may be dead, and its register re-used.  This is
27316probably the most common cause.
27317
27318@item
27319As mentioned above, the assignment of a value to a variable may
27320have been moved.
27321
27322@item
27323A variable may be eliminated entirely by value propagation or
27324other means.  In this case, GCC may incorrectly generate debugging
27325information for the variable
27326@end itemize
27327
27328In general, when an unexpected value appears for a local variable or parameter
27329you should first ascertain if that value was actually computed by
27330your program, as opposed to being incorrectly reported by the debugger.
27331Record fields or
27332array elements in an object designated by an access value
27333are generally less of a problem, once you have ascertained that the access
27334value is sensible.
27335Typically, this means checking variables in the preceding code and in the
27336calling subprogram to verify that the value observed is explainable from other
27337values (one must apply the procedure recursively to those
27338other values); or re-running the code and stopping a little earlier
27339(perhaps before the call) and stepping to better see how the variable obtained
27340the value in question; or continuing to step @emph{from} the point of the
27341strange value to see if code motion had simply moved the variable's
27342assignments later.
27343@end itemize
27344
27345In light of such anomalies, a recommended technique is to use @emph{-O0}
27346early in the software development cycle, when extensive debugging capabilities
27347are most needed, and then move to @emph{-O1} and later @emph{-O2} as
27348the debugger becomes less critical.
27349Whether to use the @emph{-g} switch in the release version is
27350a release management issue.
27351Note that if you use @emph{-g} you can then use the @emph{strip} program
27352on the resulting executable,
27353which removes both debugging information and global symbols.
27354
27355@node Inlining of Subprograms,Floating_Point_Operations,Debugging Optimized Code,Performance Considerations
27356@anchor{gnat_ugn/gnat_and_program_execution id34}@anchor{233}@anchor{gnat_ugn/gnat_and_program_execution inlining-of-subprograms}@anchor{117}
27357@subsubsection Inlining of Subprograms
27358
27359
27360A call to a subprogram in the current unit is inlined if all the
27361following conditions are met:
27362
27363
27364@itemize *
27365
27366@item
27367The optimization level is at least @emph{-O1}.
27368
27369@item
27370The called subprogram is suitable for inlining: It must be small enough
27371and not contain something that @emph{gcc} cannot support in inlined
27372subprograms.
27373
27374@geindex pragma Inline
27375
27376@geindex Inline
27377
27378@item
27379Any one of the following applies: @cite{pragma Inline} is applied to the
27380subprogram and the @emph{-gnatn} switch is specified; the
27381subprogram is local to the unit and called once from within it; the
27382subprogram is small and optimization level @emph{-O2} is specified;
27383optimization level @emph{-O3} is specified.
27384@end itemize
27385
27386Calls to subprograms in @emph{with}ed units are normally not inlined.
27387To achieve actual inlining (that is, replacement of the call by the code
27388in the body of the subprogram), the following conditions must all be true:
27389
27390
27391@itemize *
27392
27393@item
27394The optimization level is at least @emph{-O1}.
27395
27396@item
27397The called subprogram is suitable for inlining: It must be small enough
27398and not contain something that @emph{gcc} cannot support in inlined
27399subprograms.
27400
27401@item
27402The call appears in a body (not in a package spec).
27403
27404@item
27405There is a @cite{pragma Inline} for the subprogram.
27406
27407@item
27408The @emph{-gnatn} switch is used on the command line.
27409@end itemize
27410
27411Even if all these conditions are met, it may not be possible for
27412the compiler to inline the call, due to the length of the body,
27413or features in the body that make it impossible for the compiler
27414to do the inlining.
27415
27416Note that specifying the @emph{-gnatn} switch causes additional
27417compilation dependencies. Consider the following:
27418
27419@quotation
27420
27421@example
27422package R is
27423   procedure Q;
27424   pragma Inline (Q);
27425end R;
27426package body R is
27427   ...
27428end R;
27429
27430with R;
27431procedure Main is
27432begin
27433   ...
27434   R.Q;
27435end Main;
27436@end example
27437@end quotation
27438
27439With the default behavior (no @emph{-gnatn} switch specified), the
27440compilation of the @cite{Main} procedure depends only on its own source,
27441@code{main.adb}, and the spec of the package in file @code{r.ads}. This
27442means that editing the body of @cite{R} does not require recompiling
27443@cite{Main}.
27444
27445On the other hand, the call @cite{R.Q} is not inlined under these
27446circumstances. If the @emph{-gnatn} switch is present when @cite{Main}
27447is compiled, the call will be inlined if the body of @cite{Q} is small
27448enough, but now @cite{Main} depends on the body of @cite{R} in
27449@code{r.adb} as well as on the spec. This means that if this body is edited,
27450the main program must be recompiled. Note that this extra dependency
27451occurs whether or not the call is in fact inlined by @emph{gcc}.
27452
27453The use of front end inlining with @emph{-gnatN} generates similar
27454additional dependencies.
27455
27456@geindex -fno-inline (gcc)
27457
27458Note: The @emph{-fno-inline} switch overrides all other conditions and ensures that
27459no inlining occurs, unless requested with pragma Inline_Always for gcc
27460back-ends. The extra dependences resulting from @emph{-gnatn} will still be active,
27461even if this switch is used to suppress the resulting inlining actions.
27462
27463@geindex -fno-inline-functions (gcc)
27464
27465Note: The @emph{-fno-inline-functions} switch can be used to prevent
27466automatic inlining of subprograms if @emph{-O3} is used.
27467
27468@geindex -fno-inline-small-functions (gcc)
27469
27470Note: The @emph{-fno-inline-small-functions} switch can be used to prevent
27471automatic inlining of small subprograms if @emph{-O2} is used.
27472
27473@geindex -fno-inline-functions-called-once (gcc)
27474
27475Note: The @emph{-fno-inline-functions-called-once} switch
27476can be used to prevent inlining of subprograms local to the unit
27477and called once from within it if @emph{-O1} is used.
27478
27479Note regarding the use of @emph{-O3}: @emph{-gnatn} is made up of two
27480sub-switches @emph{-gnatn1} and @emph{-gnatn2} that can be directly
27481specified in lieu of it, @emph{-gnatn} being translated into one of them
27482based on the optimization level. With @emph{-O2} or below, @emph{-gnatn}
27483is equivalent to @emph{-gnatn1} which activates pragma @cite{Inline} with
27484moderate inlining across modules. With @emph{-O3}, @emph{-gnatn} is
27485equivalent to @emph{-gnatn2} which activates pragma @cite{Inline} with
27486full inlining across modules. If you have used pragma @cite{Inline} in
27487appropriate cases, then it is usually much better to use @emph{-O2}
27488and @emph{-gnatn} and avoid the use of @emph{-O3} which has the additional
27489effect of inlining subprograms you did not think should be inlined. We have
27490found that the use of @emph{-O3} may slow down the compilation and increase
27491the code size by performing excessive inlining, leading to increased
27492instruction cache pressure from the increased code size and thus minor
27493performance improvements. So the bottom line here is that you should not
27494automatically assume that @emph{-O3} is better than @emph{-O2}, and
27495indeed you should use @emph{-O3} only if tests show that it actually
27496improves performance for your program.
27497
27498@node Floating_Point_Operations,Vectorization of loops,Inlining of Subprograms,Performance Considerations
27499@anchor{gnat_ugn/gnat_and_program_execution floating-point-operations}@anchor{234}@anchor{gnat_ugn/gnat_and_program_execution id35}@anchor{235}
27500@subsubsection Floating_Point_Operations
27501
27502
27503@geindex Floating-Point Operations
27504
27505On almost all targets, GNAT maps Float and Long_Float to the 32-bit and
2750664-bit standard IEEE floating-point representations, and operations will
27507use standard IEEE arithmetic as provided by the processor. On most, but
27508not all, architectures, the attribute Machine_Overflows is False for these
27509types, meaning that the semantics of overflow is implementation-defined.
27510In the case of GNAT, these semantics correspond to the normal IEEE
27511treatment of infinities and NaN (not a number) values. For example,
275121.0 / 0.0 yields plus infinitiy and 0.0 / 0.0 yields a NaN. By
27513avoiding explicit overflow checks, the performance is greatly improved
27514on many targets. However, if required, floating-point overflow can be
27515enabled by the use of the pragma Check_Float_Overflow.
27516
27517Another consideration that applies specifically to x86 32-bit
27518architectures is which form of floating-point arithmetic is used.
27519By default the operations use the old style x86 floating-point,
27520which implements an 80-bit extended precision form (on these
27521architectures the type Long_Long_Float corresponds to that form).
27522In addition, generation of efficient code in this mode means that
27523the extended precision form will be used for intermediate results.
27524This may be helpful in improving the final precision of a complex
27525expression. However it means that the results obtained on the x86
27526will be different from those on other architectures, and for some
27527algorithms, the extra intermediate precision can be detrimental.
27528
27529In addition to this old-style floating-point, all modern x86 chips
27530implement an alternative floating-point operation model referred
27531to as SSE2. In this model there is no extended form, and furthermore
27532execution performance is significantly enhanced. To force GNAT to use
27533this more modern form, use both of the switches:
27534
27535@quotation
27536
27537-msse2 -mfpmath=sse
27538@end quotation
27539
27540A unit compiled with these switches will automatically use the more
27541efficient SSE2 instruction set for Float and Long_Float operations.
27542Note that the ABI has the same form for both floating-point models,
27543so it is permissible to mix units compiled with and without these
27544switches.
27545
27546@node Vectorization of loops,Other Optimization Switches,Floating_Point_Operations,Performance Considerations
27547@anchor{gnat_ugn/gnat_and_program_execution id36}@anchor{236}@anchor{gnat_ugn/gnat_and_program_execution vectorization-of-loops}@anchor{237}
27548@subsubsection Vectorization of loops
27549
27550
27551@geindex Optimization Switches
27552
27553You can take advantage of the auto-vectorizer present in the @emph{gcc}
27554back end to vectorize loops with GNAT.  The corresponding command line switch
27555is @emph{-ftree-vectorize} but, as it is enabled by default at @emph{-O3}
27556and other aggressive optimizations helpful for vectorization also are enabled
27557by default at this level, using @emph{-O3} directly is recommended.
27558
27559You also need to make sure that the target architecture features a supported
27560SIMD instruction set.  For example, for the x86 architecture, you should at
27561least specify @emph{-msse2} to get significant vectorization (but you don't
27562need to specify it for x86-64 as it is part of the base 64-bit architecture).
27563Similarly, for the PowerPC architecture, you should specify @emph{-maltivec}.
27564
27565The preferred loop form for vectorization is the @cite{for} iteration scheme.
27566Loops with a @cite{while} iteration scheme can also be vectorized if they are
27567very simple, but the vectorizer will quickly give up otherwise.  With either
27568iteration scheme, the flow of control must be straight, in particular no
27569@cite{exit} statement may appear in the loop body.  The loop may however
27570contain a single nested loop, if it can be vectorized when considered alone:
27571
27572@quotation
27573
27574@example
27575A : array (1..4, 1..4) of Long_Float;
27576S : array (1..4) of Long_Float;
27577
27578procedure Sum is
27579begin
27580   for I in A'Range(1) loop
27581      for J in A'Range(2) loop
27582         S (I) := S (I) + A (I, J);
27583      end loop;
27584   end loop;
27585end Sum;
27586@end example
27587@end quotation
27588
27589The vectorizable operations depend on the targeted SIMD instruction set, but
27590the adding and some of the multiplying operators are generally supported, as
27591well as the logical operators for modular types. Note that compiling
27592with @emph{-gnatp} might well reveal cases where some checks do thwart
27593vectorization.
27594
27595Type conversions may also prevent vectorization if they involve semantics that
27596are not directly supported by the code generator or the SIMD instruction set.
27597A typical example is direct conversion from floating-point to integer types.
27598The solution in this case is to use the following idiom:
27599
27600@quotation
27601
27602@example
27603Integer (S'Truncation (F))
27604@end example
27605@end quotation
27606
27607if @cite{S} is the subtype of floating-point object @cite{F}.
27608
27609In most cases, the vectorizable loops are loops that iterate over arrays.
27610All kinds of array types are supported, i.e. constrained array types with
27611static bounds:
27612
27613@quotation
27614
27615@example
27616type Array_Type is array (1 .. 4) of Long_Float;
27617@end example
27618@end quotation
27619
27620constrained array types with dynamic bounds:
27621
27622@quotation
27623
27624@example
27625type Array_Type is array (1 .. Q.N) of Long_Float;
27626
27627type Array_Type is array (Q.K .. 4) of Long_Float;
27628
27629type Array_Type is array (Q.K .. Q.N) of Long_Float;
27630@end example
27631@end quotation
27632
27633or unconstrained array types:
27634
27635@quotation
27636
27637@example
27638type Array_Type is array (Positive range <>) of Long_Float;
27639@end example
27640@end quotation
27641
27642The quality of the generated code decreases when the dynamic aspect of the
27643array type increases, the worst code being generated for unconstrained array
27644types.  This is so because, the less information the compiler has about the
27645bounds of the array, the more fallback code it needs to generate in order to
27646fix things up at run time.
27647
27648It is possible to specify that a given loop should be subject to vectorization
27649preferably to other optimizations by means of pragma @cite{Loop_Optimize}:
27650
27651@quotation
27652
27653@example
27654pragma Loop_Optimize (Vector);
27655@end example
27656@end quotation
27657
27658placed immediately within the loop will convey the appropriate hint to the
27659compiler for this loop.
27660
27661It is also possible to help the compiler generate better vectorized code
27662for a given loop by asserting that there are no loop-carried dependencies
27663in the loop.  Consider for example the procedure:
27664
27665@quotation
27666
27667@example
27668type Arr is array (1 .. 4) of Long_Float;
27669
27670procedure Add (X, Y : not null access Arr; R : not null access Arr) is
27671begin
27672  for I in Arr'Range loop
27673    R(I) := X(I) + Y(I);
27674  end loop;
27675end;
27676@end example
27677@end quotation
27678
27679By default, the compiler cannot unconditionally vectorize the loop because
27680assigning to a component of the array designated by R in one iteration could
27681change the value read from the components of the array designated by X or Y
27682in a later iteration.  As a result, the compiler will generate two versions
27683of the loop in the object code, one vectorized and the other not vectorized,
27684as well as a test to select the appropriate version at run time.  This can
27685be overcome by another hint:
27686
27687@quotation
27688
27689@example
27690pragma Loop_Optimize (Ivdep);
27691@end example
27692@end quotation
27693
27694placed immediately within the loop will tell the compiler that it can safely
27695omit the non-vectorized version of the loop as well as the run-time test.
27696
27697@node Other Optimization Switches,Optimization and Strict Aliasing,Vectorization of loops,Performance Considerations
27698@anchor{gnat_ugn/gnat_and_program_execution id37}@anchor{238}@anchor{gnat_ugn/gnat_and_program_execution other-optimization-switches}@anchor{239}
27699@subsubsection Other Optimization Switches
27700
27701
27702@geindex Optimization Switches
27703
27704Since @cite{GNAT} uses the @emph{gcc} back end, all the specialized
27705@emph{gcc} optimization switches are potentially usable. These switches
27706have not been extensively tested with GNAT but can generally be expected
27707to work. Examples of switches in this category are @emph{-funroll-loops}
27708and the various target-specific @emph{-m} options (in particular, it has
27709been observed that @emph{-march=xxx} can significantly improve performance
27710on appropriate machines). For full details of these switches, see
27711the @cite{Submodel Options} section in the @cite{Hardware Models and Configurations}
27712chapter of @cite{Using the GNU Compiler Collection (GCC)}.
27713
27714@node Optimization and Strict Aliasing,Aliased Variables and Optimization,Other Optimization Switches,Performance Considerations
27715@anchor{gnat_ugn/gnat_and_program_execution optimization-and-strict-aliasing}@anchor{fb}@anchor{gnat_ugn/gnat_and_program_execution id38}@anchor{23a}
27716@subsubsection Optimization and Strict Aliasing
27717
27718
27719@geindex Aliasing
27720
27721@geindex Strict Aliasing
27722
27723@geindex No_Strict_Aliasing
27724
27725The strong typing capabilities of Ada allow an optimizer to generate
27726efficient code in situations where other languages would be forced to
27727make worst case assumptions preventing such optimizations. Consider
27728the following example:
27729
27730@quotation
27731
27732@example
27733procedure R is
27734   type Int1 is new Integer;
27735   type Int2 is new Integer;
27736   type Int1A is access Int1;
27737   type Int2A is access Int2;
27738   Int1V : Int1A;
27739   Int2V : Int2A;
27740   ...
27741
27742begin
27743   ...
27744   for J in Data'Range loop
27745      if Data (J) = Int1V.all then
27746         Int2V.all := Int2V.all + 1;
27747      end if;
27748   end loop;
27749   ...
27750end R;
27751@end example
27752@end quotation
27753
27754In this example, since the variable @cite{Int1V} can only access objects
27755of type @cite{Int1}, and @cite{Int2V} can only access objects of type
27756@cite{Int2}, there is no possibility that the assignment to
27757@cite{Int2V.all} affects the value of @cite{Int1V.all}. This means that
27758the compiler optimizer can "know" that the value @cite{Int1V.all} is constant
27759for all iterations of the loop and avoid the extra memory reference
27760required to dereference it each time through the loop.
27761
27762This kind of optimization, called strict aliasing analysis, is
27763triggered by specifying an optimization level of @emph{-O2} or
27764higher or @emph{-Os} and allows @cite{GNAT} to generate more efficient code
27765when access values are involved.
27766
27767However, although this optimization is always correct in terms of
27768the formal semantics of the Ada Reference Manual, difficulties can
27769arise if features like @cite{Unchecked_Conversion} are used to break
27770the typing system. Consider the following complete program example:
27771
27772@quotation
27773
27774@example
27775package p1 is
27776   type int1 is new integer;
27777   type int2 is new integer;
27778   type a1 is access int1;
27779   type a2 is access int2;
27780end p1;
27781
27782with p1; use p1;
27783package p2 is
27784   function to_a2 (Input : a1) return a2;
27785end p2;
27786
27787with Unchecked_Conversion;
27788package body p2 is
27789   function to_a2 (Input : a1) return a2 is
27790      function to_a2u is
27791        new Unchecked_Conversion (a1, a2);
27792   begin
27793      return to_a2u (Input);
27794   end to_a2;
27795end p2;
27796
27797with p2; use p2;
27798with p1; use p1;
27799with Text_IO; use Text_IO;
27800procedure m is
27801   v1 : a1 := new int1;
27802   v2 : a2 := to_a2 (v1);
27803begin
27804   v1.all := 1;
27805   v2.all := 0;
27806   put_line (int1'image (v1.all));
27807end;
27808@end example
27809@end quotation
27810
27811This program prints out 0 in @emph{-O0} or @emph{-O1}
27812mode, but it prints out 1 in @emph{-O2} mode. That's
27813because in strict aliasing mode, the compiler can and
27814does assume that the assignment to @cite{v2.all} could not
27815affect the value of @cite{v1.all}, since different types
27816are involved.
27817
27818This behavior is not a case of non-conformance with the standard, since
27819the Ada RM specifies that an unchecked conversion where the resulting
27820bit pattern is not a correct value of the target type can result in an
27821abnormal value and attempting to reference an abnormal value makes the
27822execution of a program erroneous.  That's the case here since the result
27823does not point to an object of type @cite{int2}.  This means that the
27824effect is entirely unpredictable.
27825
27826However, although that explanation may satisfy a language
27827lawyer, in practice an applications programmer expects an
27828unchecked conversion involving pointers to create true
27829aliases and the behavior of printing 1 seems plain wrong.
27830In this case, the strict aliasing optimization is unwelcome.
27831
27832Indeed the compiler recognizes this possibility, and the
27833unchecked conversion generates a warning:
27834
27835@quotation
27836
27837@example
27838p2.adb:5:07: warning: possible aliasing problem with type "a2"
27839p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
27840p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
27841@end example
27842@end quotation
27843
27844Unfortunately the problem is recognized when compiling the body of
27845package @cite{p2}, but the actual "bad" code is generated while
27846compiling the body of @cite{m} and this latter compilation does not see
27847the suspicious @cite{Unchecked_Conversion}.
27848
27849As implied by the warning message, there are approaches you can use to
27850avoid the unwanted strict aliasing optimization in a case like this.
27851
27852One possibility is to simply avoid the use of @emph{-O2}, but
27853that is a bit drastic, since it throws away a number of useful
27854optimizations that do not involve strict aliasing assumptions.
27855
27856A less drastic approach is to compile the program using the
27857option @emph{-fno-strict-aliasing}. Actually it is only the
27858unit containing the dereferencing of the suspicious pointer
27859that needs to be compiled. So in this case, if we compile
27860unit @cite{m} with this switch, then we get the expected
27861value of zero printed. Analyzing which units might need
27862the switch can be painful, so a more reasonable approach
27863is to compile the entire program with options @emph{-O2}
27864and @emph{-fno-strict-aliasing}. If the performance is
27865satisfactory with this combination of options, then the
27866advantage is that the entire issue of possible "wrong"
27867optimization due to strict aliasing is avoided.
27868
27869To avoid the use of compiler switches, the configuration
27870pragma @cite{No_Strict_Aliasing} with no parameters may be
27871used to specify that for all access types, the strict
27872aliasing optimization should be suppressed.
27873
27874However, these approaches are still overkill, in that they causes
27875all manipulations of all access values to be deoptimized. A more
27876refined approach is to concentrate attention on the specific
27877access type identified as problematic.
27878
27879First, if a careful analysis of uses of the pointer shows
27880that there are no possible problematic references, then
27881the warning can be suppressed by bracketing the
27882instantiation of @cite{Unchecked_Conversion} to turn
27883the warning off:
27884
27885@quotation
27886
27887@example
27888pragma Warnings (Off);
27889function to_a2u is
27890  new Unchecked_Conversion (a1, a2);
27891pragma Warnings (On);
27892@end example
27893@end quotation
27894
27895Of course that approach is not appropriate for this particular
27896example, since indeed there is a problematic reference. In this
27897case we can take one of two other approaches.
27898
27899The first possibility is to move the instantiation of unchecked
27900conversion to the unit in which the type is declared. In
27901this example, we would move the instantiation of
27902@cite{Unchecked_Conversion} from the body of package
27903@cite{p2} to the spec of package @cite{p1}. Now the
27904warning disappears. That's because any use of the
27905access type knows there is a suspicious unchecked
27906conversion, and the strict aliasing optimization
27907is automatically suppressed for the type.
27908
27909If it is not practical to move the unchecked conversion to the same unit
27910in which the destination access type is declared (perhaps because the
27911source type is not visible in that unit), you may use pragma
27912@cite{No_Strict_Aliasing} for the type. This pragma must occur in the
27913same declarative sequence as the declaration of the access type:
27914
27915@quotation
27916
27917@example
27918type a2 is access int2;
27919pragma No_Strict_Aliasing (a2);
27920@end example
27921@end quotation
27922
27923Here again, the compiler now knows that the strict aliasing optimization
27924should be suppressed for any reference to type @cite{a2} and the
27925expected behavior is obtained.
27926
27927Finally, note that although the compiler can generate warnings for
27928simple cases of unchecked conversions, there are tricker and more
27929indirect ways of creating type incorrect aliases which the compiler
27930cannot detect. Examples are the use of address overlays and unchecked
27931conversions involving composite types containing access types as
27932components. In such cases, no warnings are generated, but there can
27933still be aliasing problems. One safe coding practice is to forbid the
27934use of address clauses for type overlaying, and to allow unchecked
27935conversion only for primitive types. This is not really a significant
27936restriction since any possible desired effect can be achieved by
27937unchecked conversion of access values.
27938
27939The aliasing analysis done in strict aliasing mode can certainly
27940have significant benefits. We have seen cases of large scale
27941application code where the time is increased by up to 5% by turning
27942this optimization off. If you have code that includes significant
27943usage of unchecked conversion, you might want to just stick with
27944@emph{-O1} and avoid the entire issue. If you get adequate
27945performance at this level of optimization level, that's probably
27946the safest approach. If tests show that you really need higher
27947levels of optimization, then you can experiment with @emph{-O2}
27948and @emph{-O2 -fno-strict-aliasing} to see how much effect this
27949has on size and speed of the code. If you really need to use
27950@emph{-O2} with strict aliasing in effect, then you should
27951review any uses of unchecked conversion of access types,
27952particularly if you are getting the warnings described above.
27953
27954@node Aliased Variables and Optimization,Atomic Variables and Optimization,Optimization and Strict Aliasing,Performance Considerations
27955@anchor{gnat_ugn/gnat_and_program_execution aliased-variables-and-optimization}@anchor{23b}@anchor{gnat_ugn/gnat_and_program_execution id39}@anchor{23c}
27956@subsubsection Aliased Variables and Optimization
27957
27958
27959@geindex Aliasing
27960
27961There are scenarios in which programs may
27962use low level techniques to modify variables
27963that otherwise might be considered to be unassigned. For example,
27964a variable can be passed to a procedure by reference, which takes
27965the address of the parameter and uses the address to modify the
27966variable's value, even though it is passed as an IN parameter.
27967Consider the following example:
27968
27969@quotation
27970
27971@example
27972procedure P is
27973   Max_Length : constant Natural := 16;
27974   type Char_Ptr is access all Character;
27975
27976   procedure Get_String(Buffer: Char_Ptr; Size : Integer);
27977   pragma Import (C, Get_String, "get_string");
27978
27979   Name : aliased String (1 .. Max_Length) := (others => ' ');
27980   Temp : Char_Ptr;
27981
27982   function Addr (S : String) return Char_Ptr is
27983      function To_Char_Ptr is
27984        new Ada.Unchecked_Conversion (System.Address, Char_Ptr);
27985   begin
27986      return To_Char_Ptr (S (S'First)'Address);
27987   end;
27988
27989begin
27990   Temp := Addr (Name);
27991   Get_String (Temp, Max_Length);
27992end;
27993@end example
27994@end quotation
27995
27996where Get_String is a C function that uses the address in Temp to
27997modify the variable @cite{Name}. This code is dubious, and arguably
27998erroneous, and the compiler would be entitled to assume that
27999@cite{Name} is never modified, and generate code accordingly.
28000
28001However, in practice, this would cause some existing code that
28002seems to work with no optimization to start failing at high
28003levels of optimzization.
28004
28005What the compiler does for such cases is to assume that marking
28006a variable as aliased indicates that some "funny business" may
28007be going on. The optimizer recognizes the aliased keyword and
28008inhibits optimizations that assume the value cannot be assigned.
28009This means that the above example will in fact "work" reliably,
28010that is, it will produce the expected results.
28011
28012@node Atomic Variables and Optimization,Passive Task Optimization,Aliased Variables and Optimization,Performance Considerations
28013@anchor{gnat_ugn/gnat_and_program_execution atomic-variables-and-optimization}@anchor{23d}@anchor{gnat_ugn/gnat_and_program_execution id40}@anchor{23e}
28014@subsubsection Atomic Variables and Optimization
28015
28016
28017@geindex Atomic
28018
28019There are two considerations with regard to performance when
28020atomic variables are used.
28021
28022First, the RM only guarantees that access to atomic variables
28023be atomic, it has nothing to say about how this is achieved,
28024though there is a strong implication that this should not be
28025achieved by explicit locking code. Indeed GNAT will never
28026generate any locking code for atomic variable access (it will
28027simply reject any attempt to make a variable or type atomic
28028if the atomic access cannot be achieved without such locking code).
28029
28030That being said, it is important to understand that you cannot
28031assume that the entire variable will always be accessed. Consider
28032this example:
28033
28034@quotation
28035
28036@example
28037type R is record
28038   A,B,C,D : Character;
28039end record;
28040for R'Size use 32;
28041for R'Alignment use 4;
28042
28043RV : R;
28044pragma Atomic (RV);
28045X : Character;
28046...
28047X := RV.B;
28048@end example
28049@end quotation
28050
28051You cannot assume that the reference to @cite{RV.B}
28052will read the entire 32-bit
28053variable with a single load instruction. It is perfectly legitimate if
28054the hardware allows it to do a byte read of just the B field. This read
28055is still atomic, which is all the RM requires. GNAT can and does take
28056advantage of this, depending on the architecture and optimization level.
28057Any assumption to the contrary is non-portable and risky. Even if you
28058examine the assembly language and see a full 32-bit load, this might
28059change in a future version of the compiler.
28060
28061If your application requires that all accesses to @cite{RV} in this
28062example be full 32-bit loads, you need to make a copy for the access
28063as in:
28064
28065@quotation
28066
28067@example
28068declare
28069   RV_Copy : constant R := RV;
28070begin
28071   X := RV_Copy.B;
28072end;
28073@end example
28074@end quotation
28075
28076Now the reference to RV must read the whole variable.
28077Actually one can imagine some compiler which figures
28078out that the whole copy is not required (because only
28079the B field is actually accessed), but GNAT
28080certainly won't do that, and we don't know of any
28081compiler that would not handle this right, and the
28082above code will in practice work portably across
28083all architectures (that permit the Atomic declaration).
28084
28085The second issue with atomic variables has to do with
28086the possible requirement of generating synchronization
28087code. For more details on this, consult the sections on
28088the pragmas Enable/Disable_Atomic_Synchronization in the
28089GNAT Reference Manual. If performance is critical, and
28090such synchronization code is not required, it may be
28091useful to disable it.
28092
28093@node Passive Task Optimization,,Atomic Variables and Optimization,Performance Considerations
28094@anchor{gnat_ugn/gnat_and_program_execution id41}@anchor{23f}@anchor{gnat_ugn/gnat_and_program_execution passive-task-optimization}@anchor{240}
28095@subsubsection Passive Task Optimization
28096
28097
28098@geindex Passive Task
28099
28100A passive task is one which is sufficiently simple that
28101in theory a compiler could recognize it an implement it
28102efficiently without creating a new thread. The original design
28103of Ada 83 had in mind this kind of passive task optimization, but
28104only a few Ada 83 compilers attempted it. The problem was that
28105it was difficult to determine the exact conditions under which
28106the optimization was possible. The result is a very fragile
28107optimization where a very minor change in the program can
28108suddenly silently make a task non-optimizable.
28109
28110With the revisiting of this issue in Ada 95, there was general
28111agreement that this approach was fundamentally flawed, and the
28112notion of protected types was introduced. When using protected
28113types, the restrictions are well defined, and you KNOW that the
28114operations will be optimized, and furthermore this optimized
28115performance is fully portable.
28116
28117Although it would theoretically be possible for GNAT to attempt to
28118do this optimization, but it really doesn't make sense in the
28119context of Ada 95, and none of the Ada 95 compilers implement
28120this optimization as far as we know. In particular GNAT never
28121attempts to perform this optimization.
28122
28123In any new Ada 95 code that is written, you should always
28124use protected types in place of tasks that might be able to
28125be optimized in this manner.
28126Of course this does not help if you have legacy Ada 83 code
28127that depends on this optimization, but it is unusual to encounter
28128a case where the performance gains from this optimization
28129are significant.
28130
28131Your program should work correctly without this optimization. If
28132you have performance problems, then the most practical
28133approach is to figure out exactly where these performance problems
28134arise, and update those particular tasks to be protected types. Note
28135that typically clients of the tasks who call entries, will not have
28136to be modified, only the task definition itself.
28137
28138@node Text_IO Suggestions,Reducing Size of Executables with Unused Subprogram/Data Elimination,Performance Considerations,Improving Performance
28139@anchor{gnat_ugn/gnat_and_program_execution text-io-suggestions}@anchor{241}@anchor{gnat_ugn/gnat_and_program_execution id42}@anchor{242}
28140@subsection @cite{Text_IO} Suggestions
28141
28142
28143@geindex Text_IO and performance
28144
28145The @cite{Ada.Text_IO} package has fairly high overheads due in part to
28146the requirement of maintaining page and line counts. If performance
28147is critical, a recommendation is to use @cite{Stream_IO} instead of
28148@cite{Text_IO} for volume output, since this package has less overhead.
28149
28150If @cite{Text_IO} must be used, note that by default output to the standard
28151output and standard error files is unbuffered (this provides better
28152behavior when output statements are used for debugging, or if the
28153progress of a program is observed by tracking the output, e.g. by
28154using the Unix @emph{tail -f} command to watch redirected output.
28155
28156If you are generating large volumes of output with @cite{Text_IO} and
28157performance is an important factor, use a designated file instead
28158of the standard output file, or change the standard output file to
28159be buffered using @cite{Interfaces.C_Streams.setvbuf}.
28160
28161@node Reducing Size of Executables with Unused Subprogram/Data Elimination,,Text_IO Suggestions,Improving Performance
28162@anchor{gnat_ugn/gnat_and_program_execution id43}@anchor{243}@anchor{gnat_ugn/gnat_and_program_execution reducing-size-of-executables-with-unused-subprogram-data-elimination}@anchor{244}
28163@subsection Reducing Size of Executables with Unused Subprogram/Data Elimination
28164
28165
28166@geindex Uunused subprogram/data elimination
28167
28168This section describes how you can eliminate unused subprograms and data from
28169your executable just by setting options at compilation time.
28170
28171@menu
28172* About unused subprogram/data elimination::
28173* Compilation options::
28174* Example of unused subprogram/data elimination::
28175
28176@end menu
28177
28178@node About unused subprogram/data elimination,Compilation options,,Reducing Size of Executables with Unused Subprogram/Data Elimination
28179@anchor{gnat_ugn/gnat_and_program_execution id44}@anchor{245}@anchor{gnat_ugn/gnat_and_program_execution about-unused-subprogram-data-elimination}@anchor{246}
28180@subsubsection About unused subprogram/data elimination
28181
28182
28183By default, an executable contains all code and data of its composing objects
28184(directly linked or coming from statically linked libraries), even data or code
28185never used by this executable.
28186
28187This feature will allow you to eliminate such unused code from your
28188executable, making it smaller (in disk and in memory).
28189
28190This functionality is available on all Linux platforms except for the IA-64
28191architecture and on all cross platforms using the ELF binary file format.
28192In both cases GNU binutils version 2.16 or later are required to enable it.
28193
28194@node Compilation options,Example of unused subprogram/data elimination,About unused subprogram/data elimination,Reducing Size of Executables with Unused Subprogram/Data Elimination
28195@anchor{gnat_ugn/gnat_and_program_execution id45}@anchor{247}@anchor{gnat_ugn/gnat_and_program_execution compilation-options}@anchor{248}
28196@subsubsection Compilation options
28197
28198
28199The operation of eliminating the unused code and data from the final executable
28200is directly performed by the linker.
28201
28202@geindex -ffunction-sections (gcc)
28203
28204@geindex -fdata-sections (gcc)
28205
28206In order to do this, it has to work with objects compiled with the
28207following options:
28208@emph{-ffunction-sections} @emph{-fdata-sections}.
28209
28210These options are usable with C and Ada files.
28211They will place respectively each
28212function or data in a separate section in the resulting object file.
28213
28214Once the objects and static libraries are created with these options, the
28215linker can perform the dead code elimination. You can do this by setting
28216the @emph{-Wl,--gc-sections} option to gcc command or in the
28217@emph{-largs} section of @emph{gnatmake}. This will perform a
28218garbage collection of code and data never referenced.
28219
28220If the linker performs a partial link (@emph{-r} linker option), then you
28221will need to provide the entry point using the @emph{-e} / @emph{--entry}
28222linker option.
28223
28224Note that objects compiled without the @emph{-ffunction-sections} and
28225@emph{-fdata-sections} options can still be linked with the executable.
28226However, no dead code elimination will be performed on those objects (they will
28227be linked as is).
28228
28229The GNAT static library is now compiled with -ffunction-sections and
28230-fdata-sections on some platforms. This allows you to eliminate the unused code
28231and data of the GNAT library from your executable.
28232
28233@node Example of unused subprogram/data elimination,,Compilation options,Reducing Size of Executables with Unused Subprogram/Data Elimination
28234@anchor{gnat_ugn/gnat_and_program_execution id46}@anchor{249}@anchor{gnat_ugn/gnat_and_program_execution example-of-unused-subprogram-data-elimination}@anchor{24a}
28235@subsubsection Example of unused subprogram/data elimination
28236
28237
28238Here is a simple example:
28239
28240@quotation
28241
28242@example
28243with Aux;
28244
28245procedure Test is
28246begin
28247   Aux.Used (10);
28248end Test;
28249
28250package Aux is
28251   Used_Data   : Integer;
28252   Unused_Data : Integer;
28253
28254   procedure Used   (Data : Integer);
28255   procedure Unused (Data : Integer);
28256end Aux;
28257
28258package body Aux is
28259   procedure Used (Data : Integer) is
28260   begin
28261      Used_Data := Data;
28262   end Used;
28263
28264   procedure Unused (Data : Integer) is
28265   begin
28266      Unused_Data := Data;
28267   end Unused;
28268end Aux;
28269@end example
28270@end quotation
28271
28272@cite{Unused} and @cite{Unused_Data} are never referenced in this code
28273excerpt, and hence they may be safely removed from the final executable.
28274
28275@quotation
28276
28277@example
28278$ gnatmake test
28279
28280$ nm test | grep used
28281020015f0 T aux__unused
2828202005d88 B aux__unused_data
28283020015cc T aux__used
2828402005d84 B aux__used_data
28285
28286$ gnatmake test -cargs -fdata-sections -ffunction-sections \\
28287     -largs -Wl,--gc-sections
28288
28289$ nm test | grep used
2829002005350 T aux__used
282910201ffe0 B aux__used_data
28292@end example
28293@end quotation
28294
28295It can be observed that the procedure @cite{Unused} and the object
28296@cite{Unused_Data} are removed by the linker when using the
28297appropriate options.
28298
28299@geindex Overflow checks
28300
28301@geindex Checks (overflow)
28302
28303
28304@node Overflow Check Handling in GNAT,Performing Dimensionality Analysis in GNAT,Improving Performance,GNAT and Program Execution
28305@anchor{gnat_ugn/gnat_and_program_execution id54}@anchor{1f6}@anchor{gnat_ugn/gnat_and_program_execution overflow-check-handling-in-gnat}@anchor{29}
28306@section Overflow Check Handling in GNAT
28307
28308
28309This section explains how to control the handling of overflow checks.
28310
28311@menu
28312* Background::
28313* Management of Overflows in GNAT::
28314* Specifying the Desired Mode::
28315* Default Settings::
28316* Implementation Notes::
28317
28318@end menu
28319
28320@node Background,Management of Overflows in GNAT,,Overflow Check Handling in GNAT
28321@anchor{gnat_ugn/gnat_and_program_execution id55}@anchor{24b}@anchor{gnat_ugn/gnat_and_program_execution background}@anchor{24c}
28322@subsection Background
28323
28324
28325Overflow checks are checks that the compiler may make to ensure
28326that intermediate results are not out of range. For example:
28327
28328@quotation
28329
28330@example
28331A : Integer;
28332...
28333A := A + 1;
28334@end example
28335@end quotation
28336
28337If @cite{A} has the value @cite{Integer'Last}, then the addition may cause
28338overflow since the result is out of range of the type @cite{Integer}.
28339In this case @cite{Constraint_Error} will be raised if checks are
28340enabled.
28341
28342A trickier situation arises in examples like the following:
28343
28344@quotation
28345
28346@example
28347A, C : Integer;
28348...
28349A := (A + 1) + C;
28350@end example
28351@end quotation
28352
28353where @cite{A} is @cite{Integer'Last} and @cite{C} is @cite{-1}.
28354Now the final result of the expression on the right hand side is
28355@cite{Integer'Last} which is in range, but the question arises whether the
28356intermediate addition of @cite{(A + 1)} raises an overflow error.
28357
28358The (perhaps surprising) answer is that the Ada language
28359definition does not answer this question. Instead it leaves
28360it up to the implementation to do one of two things if overflow
28361checks are enabled.
28362
28363
28364@itemize *
28365
28366@item
28367raise an exception (@cite{Constraint_Error}), or
28368
28369@item
28370yield the correct mathematical result which is then used in
28371subsequent operations.
28372@end itemize
28373
28374If the compiler chooses the first approach, then the assignment of this
28375example will indeed raise @cite{Constraint_Error} if overflow checking is
28376enabled, or result in erroneous execution if overflow checks are suppressed.
28377
28378But if the compiler
28379chooses the second approach, then it can perform both additions yielding
28380the correct mathematical result, which is in range, so no exception
28381will be raised, and the right result is obtained, regardless of whether
28382overflow checks are suppressed.
28383
28384Note that in the first example an
28385exception will be raised in either case, since if the compiler
28386gives the correct mathematical result for the addition, it will
28387be out of range of the target type of the assignment, and thus
28388fails the range check.
28389
28390This lack of specified behavior in the handling of overflow for
28391intermediate results is a source of non-portability, and can thus
28392be problematic when programs are ported. Most typically this arises
28393in a situation where the original compiler did not raise an exception,
28394and then the application is moved to a compiler where the check is
28395performed on the intermediate result and an unexpected exception is
28396raised.
28397
28398Furthermore, when using Ada 2012's preconditions and other
28399assertion forms, another issue arises. Consider:
28400
28401@quotation
28402
28403@example
28404procedure P (A, B : Integer) with
28405  Pre => A + B <= Integer'Last;
28406@end example
28407@end quotation
28408
28409One often wants to regard arithmetic in a context like this from
28410a mathematical point of view. So for example, if the two actual parameters
28411for a call to @cite{P} are both @cite{Integer'Last}, then
28412the precondition should be regarded as False. If we are executing
28413in a mode with run-time checks enabled for preconditions, then we would
28414like this precondition to fail, rather than raising an exception
28415because of the intermediate overflow.
28416
28417However, the language definition leaves the specification of
28418whether the above condition fails (raising @cite{Assert_Error}) or
28419causes an intermediate overflow (raising @cite{Constraint_Error})
28420up to the implementation.
28421
28422The situation is worse in a case such as the following:
28423
28424@quotation
28425
28426@example
28427procedure Q (A, B, C : Integer) with
28428  Pre => A + B + C <= Integer'Last;
28429@end example
28430@end quotation
28431
28432Consider the call
28433
28434@quotation
28435
28436@example
28437Q (A => Integer'Last, B => 1, C => -1);
28438@end example
28439@end quotation
28440
28441From a mathematical point of view the precondition
28442is True, but at run time we may (but are not guaranteed to) get an
28443exception raised because of the intermediate overflow (and we really
28444would prefer this precondition to be considered True at run time).
28445
28446@node Management of Overflows in GNAT,Specifying the Desired Mode,Background,Overflow Check Handling in GNAT
28447@anchor{gnat_ugn/gnat_and_program_execution id56}@anchor{24d}@anchor{gnat_ugn/gnat_and_program_execution management-of-overflows-in-gnat}@anchor{24e}
28448@subsection Management of Overflows in GNAT
28449
28450
28451To deal with the portability issue, and with the problem of
28452mathematical versus run-time interpretation of the expressions in
28453assertions, GNAT provides comprehensive control over the handling
28454of intermediate overflow. GNAT can operate in three modes, and
28455furthemore, permits separate selection of operating modes for
28456the expressions within assertions (here the term 'assertions'
28457is used in the technical sense, which includes preconditions and so forth)
28458and for expressions appearing outside assertions.
28459
28460The three modes are:
28461
28462
28463@itemize *
28464
28465@item
28466@emph{Use base type for intermediate operations} (@cite{STRICT})
28467
28468In this mode, all intermediate results for predefined arithmetic
28469operators are computed using the base type, and the result must
28470be in range of the base type. If this is not the
28471case then either an exception is raised (if overflow checks are
28472enabled) or the execution is erroneous (if overflow checks are suppressed).
28473This is the normal default mode.
28474
28475@item
28476@emph{Most intermediate overflows avoided} (@cite{MINIMIZED})
28477
28478In this mode, the compiler attempts to avoid intermediate overflows by
28479using a larger integer type, typically @cite{Long_Long_Integer},
28480as the type in which arithmetic is
28481performed for predefined arithmetic operators. This may be slightly more
28482expensive at
28483run time (compared to suppressing intermediate overflow checks), though
28484the cost is negligible on modern 64-bit machines. For the examples given
28485earlier, no intermediate overflows would have resulted in exceptions,
28486since the intermediate results are all in the range of
28487@cite{Long_Long_Integer} (typically 64-bits on nearly all implementations
28488of GNAT). In addition, if checks are enabled, this reduces the number of
28489checks that must be made, so this choice may actually result in an
28490improvement in space and time behavior.
28491
28492However, there are cases where @cite{Long_Long_Integer} is not large
28493enough, consider the following example:
28494
28495@quotation
28496
28497@example
28498procedure R (A, B, C, D : Integer) with
28499  Pre => (A**2 * B**2) / (C**2 * D**2) <= 10;
28500@end example
28501@end quotation
28502
28503where @cite{A} = @cite{B} = @cite{C} = @cite{D} = @cite{Integer'Last}.
28504Now the intermediate results are
28505out of the range of @cite{Long_Long_Integer} even though the final result
28506is in range and the precondition is True (from a mathematical point
28507of view). In such a case, operating in this mode, an overflow occurs
28508for the intermediate computation (which is why this mode
28509says @emph{most} intermediate overflows are avoided). In this case,
28510an exception is raised if overflow checks are enabled, and the
28511execution is erroneous if overflow checks are suppressed.
28512
28513@item
28514@emph{All intermediate overflows avoided} (@cite{ELIMINATED})
28515
28516In this mode, the compiler  avoids all intermediate overflows
28517by using arbitrary precision arithmetic as required. In this
28518mode, the above example with @cite{A**2 * B**2} would
28519not cause intermediate overflow, because the intermediate result
28520would be evaluated using sufficient precision, and the result
28521of evaluating the precondition would be True.
28522
28523This mode has the advantage of avoiding any intermediate
28524overflows, but at the expense of significant run-time overhead,
28525including the use of a library (included automatically in this
28526mode) for multiple-precision arithmetic.
28527
28528This mode provides cleaner semantics for assertions, since now
28529the run-time behavior emulates true arithmetic behavior for the
28530predefined arithmetic operators, meaning that there is never a
28531conflict between the mathematical view of the assertion, and its
28532run-time behavior.
28533
28534Note that in this mode, the behavior is unaffected by whether or
28535not overflow checks are suppressed, since overflow does not occur.
28536It is possible for gigantic intermediate expressions to raise
28537@cite{Storage_Error} as a result of attempting to compute the
28538results of such expressions (e.g. @cite{Integer'Last ** Integer'Last})
28539but overflow is impossible.
28540@end itemize
28541
28542Note that these modes apply only to the evaluation of predefined
28543arithmetic, membership, and comparison operators for signed integer
28544aritmetic.
28545
28546For fixed-point arithmetic, checks can be suppressed. But if checks
28547are enabled
28548then fixed-point values are always checked for overflow against the
28549base type for intermediate expressions (that is such checks always
28550operate in the equivalent of @cite{STRICT} mode).
28551
28552For floating-point, on nearly all architectures, @cite{Machine_Overflows}
28553is False, and IEEE infinities are generated, so overflow exceptions
28554are never raised. If you want to avoid infinities, and check that
28555final results of expressions are in range, then you can declare a
28556constrained floating-point type, and range checks will be carried
28557out in the normal manner (with infinite values always failing all
28558range checks).
28559
28560@node Specifying the Desired Mode,Default Settings,Management of Overflows in GNAT,Overflow Check Handling in GNAT
28561@anchor{gnat_ugn/gnat_and_program_execution specifying-the-desired-mode}@anchor{100}@anchor{gnat_ugn/gnat_and_program_execution id57}@anchor{24f}
28562@subsection Specifying the Desired Mode
28563
28564
28565@geindex pragma Overflow_Mode
28566
28567The desired mode of for handling intermediate overflow can be specified using
28568either the @cite{Overflow_Mode} pragma or an equivalent compiler switch.
28569The pragma has the form
28570
28571@quotation
28572
28573@example
28574pragma Overflow_Mode ([General =>] MODE [, [Assertions =>] MODE]);
28575@end example
28576@end quotation
28577
28578where @cite{MODE} is one of
28579
28580
28581@itemize *
28582
28583@item
28584@cite{STRICT}:  intermediate overflows checked (using base type)
28585
28586@item
28587@cite{MINIMIZED}: minimize intermediate overflows
28588
28589@item
28590@cite{ELIMINATED}: eliminate intermediate overflows
28591@end itemize
28592
28593The case is ignored, so @cite{MINIMIZED}, @cite{Minimized} and
28594@cite{minimized} all have the same effect.
28595
28596If only the @cite{General} parameter is present, then the given @cite{MODE}
28597applies
28598to expressions both within and outside assertions. If both arguments
28599are present, then @cite{General} applies to expressions outside assertions,
28600and @cite{Assertions} applies to expressions within assertions. For example:
28601
28602@quotation
28603
28604@example
28605pragma Overflow_Mode
28606  (General => Minimized, Assertions => Eliminated);
28607@end example
28608@end quotation
28609
28610specifies that general expressions outside assertions be evaluated
28611in 'minimize intermediate overflows' mode, and expressions within
28612assertions be evaluated in 'eliminate intermediate overflows' mode.
28613This is often a reasonable choice, avoiding excessive overhead
28614outside assertions, but assuring a high degree of portability
28615when importing code from another compiler, while incurring
28616the extra overhead for assertion expressions to ensure that
28617the behavior at run time matches the expected mathematical
28618behavior.
28619
28620The @cite{Overflow_Mode} pragma has the same scoping and placement
28621rules as pragma @cite{Suppress}, so it can occur either as a
28622configuration pragma, specifying a default for the whole
28623program, or in a declarative scope, where it applies to the
28624remaining declarations and statements in that scope.
28625
28626Note that pragma @cite{Overflow_Mode} does not affect whether
28627overflow checks are enabled or suppressed. It only controls the
28628method used to compute intermediate values. To control whether
28629overflow checking is enabled or suppressed, use pragma @cite{Suppress}
28630or @cite{Unsuppress} in the usual manner
28631
28632@geindex -gnato? (gcc)
28633
28634@geindex -gnato?? (gcc)
28635
28636Additionally, a compiler switch @emph{-gnato?} or @emph{-gnato??}
28637can be used to control the checking mode default (which can be subsequently
28638overridden using pragmas).
28639
28640Here @code{?} is one of the digits @code{1} through @code{3}:
28641
28642@quotation
28643
28644
28645@multitable {xxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
28646@item
28647
28648@code{1}
28649
28650@tab
28651
28652use base type for intermediate operations (@cite{STRICT})
28653
28654@item
28655
28656@code{2}
28657
28658@tab
28659
28660minimize intermediate overflows (@cite{MINIMIZED})
28661
28662@item
28663
28664@code{3}
28665
28666@tab
28667
28668eliminate intermediate overflows (@cite{ELIMINATED})
28669
28670@end multitable
28671
28672@end quotation
28673
28674As with the pragma, if only one digit appears then it applies to all
28675cases; if two digits are given, then the first applies outside
28676assertions, and the second within assertions. Thus the equivalent
28677of the example pragma above would be
28678@emph{-gnato23}.
28679
28680If no digits follow the @emph{-gnato}, then it is equivalent to
28681@emph{-gnato11},
28682causing all intermediate operations to be computed using the base
28683type (@cite{STRICT} mode).
28684
28685@node Default Settings,Implementation Notes,Specifying the Desired Mode,Overflow Check Handling in GNAT
28686@anchor{gnat_ugn/gnat_and_program_execution id58}@anchor{250}@anchor{gnat_ugn/gnat_and_program_execution default-settings}@anchor{251}
28687@subsection Default Settings
28688
28689
28690The default mode for overflow checks is
28691
28692@quotation
28693
28694@example
28695General => Strict
28696@end example
28697@end quotation
28698
28699which causes all computations both inside and outside assertions to use
28700the base type.
28701
28702This retains compatibility with previous versions of
28703GNAT which suppressed overflow checks by default and always
28704used the base type for computation of intermediate results.
28705
28706@c Sphinx allows no emphasis within :index: role. As a workaround we
28707@c point the index to "switch" and use emphasis for "-gnato".
28708
28709The
28710@geindex -gnato (gcc)
28711switch @emph{-gnato} (with no digits following)
28712is equivalent to
28713
28714@quotation
28715
28716@example
28717General => Strict
28718@end example
28719@end quotation
28720
28721which causes overflow checking of all intermediate overflows
28722both inside and outside assertions against the base type.
28723
28724The pragma @cite{Suppress (Overflow_Check)} disables overflow
28725checking, but it has no effect on the method used for computing
28726intermediate results.
28727
28728The pragma @cite{Unsuppress (Overflow_Check)} enables overflow
28729checking, but it has no effect on the method used for computing
28730intermediate results.
28731
28732@node Implementation Notes,,Default Settings,Overflow Check Handling in GNAT
28733@anchor{gnat_ugn/gnat_and_program_execution implementation-notes}@anchor{252}@anchor{gnat_ugn/gnat_and_program_execution id59}@anchor{253}
28734@subsection Implementation Notes
28735
28736
28737In practice on typical 64-bit machines, the @cite{MINIMIZED} mode is
28738reasonably efficient, and can be generally used. It also helps
28739to ensure compatibility with code imported from some other
28740compiler to GNAT.
28741
28742Setting all intermediate overflows checking (@cite{CHECKED} mode)
28743makes sense if you want to
28744make sure that your code is compatible with any other possible
28745Ada implementation. This may be useful in ensuring portability
28746for code that is to be exported to some other compiler than GNAT.
28747
28748The Ada standard allows the reassociation of expressions at
28749the same precedence level if no parentheses are present. For
28750example, @cite{A+B+C} parses as though it were @cite{(A+B)+C}, but
28751the compiler can reintepret this as @cite{A+(B+C)}, possibly
28752introducing or eliminating an overflow exception. The GNAT
28753compiler never takes advantage of this freedom, and the
28754expression @cite{A+B+C} will be evaluated as @cite{(A+B)+C}.
28755If you need the other order, you can write the parentheses
28756explicitly @cite{A+(B+C)} and GNAT will respect this order.
28757
28758The use of @cite{ELIMINATED} mode will cause the compiler to
28759automatically include an appropriate arbitrary precision
28760integer arithmetic package. The compiler will make calls
28761to this package, though only in cases where it cannot be
28762sure that @cite{Long_Long_Integer} is sufficient to guard against
28763intermediate overflows. This package does not use dynamic
28764alllocation, but it does use the secondary stack, so an
28765appropriate secondary stack package must be present (this
28766is always true for standard full Ada, but may require
28767specific steps for restricted run times such as ZFP).
28768
28769Although @cite{ELIMINATED} mode causes expressions to use arbitrary
28770precision arithmetic, avoiding overflow, the final result
28771must be in an appropriate range. This is true even if the
28772final result is of type @cite{[Long_[Long_]]Integer'Base}, which
28773still has the same bounds as its associated constrained
28774type at run-time.
28775
28776Currently, the @cite{ELIMINATED} mode is only available on target
28777platforms for which @cite{Long_Long_Integer} is 64-bits (nearly all GNAT
28778platforms).
28779
28780@node Performing Dimensionality Analysis in GNAT,Stack Related Facilities,Overflow Check Handling in GNAT,GNAT and Program Execution
28781@anchor{gnat_ugn/gnat_and_program_execution performing-dimensionality-analysis-in-gnat}@anchor{2a}@anchor{gnat_ugn/gnat_and_program_execution id60}@anchor{1f7}
28782@section Performing Dimensionality Analysis in GNAT
28783
28784
28785@geindex Dimensionality analysis
28786
28787The GNAT compiler supports dimensionality checking. The user can
28788specify physical units for objects, and the compiler will verify that uses
28789of these objects are compatible with their dimensions, in a fashion that is
28790familiar to engineering practice. The dimensions of algebraic expressions
28791(including powers with static exponents) are computed from their constituents.
28792
28793@geindex Dimension_System aspect
28794
28795@geindex Dimension aspect
28796
28797This feature depends on Ada 2012 aspect specifications, and is available from
28798version 7.0.1 of GNAT onwards.
28799The GNAT-specific aspect @cite{Dimension_System}
28800allows you to define a system of units; the aspect @cite{Dimension}
28801then allows the user to declare dimensioned quantities within a given system.
28802(These aspects are described in the @emph{Implementation Defined Aspects}
28803chapter of the @emph{GNAT Reference Manual}).
28804
28805The major advantage of this model is that it does not require the declaration of
28806multiple operators for all possible combinations of types: it is only necessary
28807to use the proper subtypes in object declarations.
28808
28809@geindex System.Dim.Mks package (GNAT library)
28810
28811@geindex MKS_Type type
28812
28813The simplest way to impose dimensionality checking on a computation is to make
28814use of the package @cite{System.Dim.Mks},
28815which is part of the GNAT library. This
28816package defines a floating-point type @cite{MKS_Type},
28817for which a sequence of
28818dimension names are specified, together with their conventional abbreviations.
28819The following should be read together with the full specification of the
28820package, in file @code{s-dimmks.ads}.
28821
28822@quotation
28823
28824@geindex s-dimmks.ads file
28825
28826@example
28827type Mks_Type is new Long_Long_Float
28828  with
28829   Dimension_System => (
28830     (Unit_Name => Meter,    Unit_Symbol => 'm',   Dim_Symbol => 'L'),
28831     (Unit_Name => Kilogram, Unit_Symbol => "kg",  Dim_Symbol => 'M'),
28832     (Unit_Name => Second,   Unit_Symbol => 's',   Dim_Symbol => 'T'),
28833     (Unit_Name => Ampere,   Unit_Symbol => 'A',   Dim_Symbol => 'I'),
28834     (Unit_Name => Kelvin,   Unit_Symbol => 'K',   Dim_Symbol => "Theta"),
28835     (Unit_Name => Mole,     Unit_Symbol => "mol", Dim_Symbol => 'N'),
28836     (Unit_Name => Candela,  Unit_Symbol => "cd",  Dim_Symbol => 'J'));
28837@end example
28838@end quotation
28839
28840The package then defines a series of subtypes that correspond to these
28841conventional units. For example:
28842
28843@quotation
28844
28845@example
28846subtype Length is Mks_Type
28847  with
28848   Dimension => (Symbol => 'm', Meter  => 1, others => 0);
28849@end example
28850@end quotation
28851
28852and similarly for @cite{Mass}, @cite{Time}, @cite{Electric_Current},
28853@cite{Thermodynamic_Temperature}, @cite{Amount_Of_Substance}, and
28854@cite{Luminous_Intensity} (the standard set of units of the SI system).
28855
28856The package also defines conventional names for values of each unit, for
28857example:
28858
28859@quotation
28860
28861@c code-block":: ada
28862@c
28863@c m   : constant Length           := 1.0;
28864@c kg  : constant Mass             := 1.0;
28865@c s   : constant Time             := 1.0;
28866@c A   : constant Electric_Current := 1.0;
28867@end quotation
28868
28869as well as useful multiples of these units:
28870
28871@quotation
28872
28873@example
28874 cm  : constant Length := 1.0E-02;
28875 g   : constant Mass   := 1.0E-03;
28876 min : constant Time   := 60.0;
28877 day : constant Time   := 60.0 * 24.0 * min;
28878...
28879@end example
28880@end quotation
28881
28882Using this package, you can then define a derived unit by
28883providing the aspect that
28884specifies its dimensions within the MKS system, as well as the string to
28885be used for output of a value of that unit:
28886
28887@quotation
28888
28889@example
28890subtype Acceleration is Mks_Type
28891  with Dimension => ("m/sec^2",
28892                     Meter => 1,
28893                     Second => -2,
28894                     others => 0);
28895@end example
28896@end quotation
28897
28898Here is a complete example of use:
28899
28900@quotation
28901
28902@example
28903with System.Dim.MKS; use System.Dim.Mks;
28904with System.Dim.Mks_IO; use System.Dim.Mks_IO;
28905with Text_IO; use Text_IO;
28906procedure Free_Fall is
28907  subtype Acceleration is Mks_Type
28908    with Dimension => ("m/sec^2", 1, 0, -2, others => 0);
28909  G : constant acceleration := 9.81 * m / (s ** 2);
28910  T : Time := 10.0*s;
28911  Distance : Length;
28912
28913begin
28914  Put ("Gravitational constant: ");
28915  Put (G, Aft => 2, Exp => 0); Put_Line ("");
28916  Distance := 0.5 * G * T ** 2;
28917  Put ("distance travelled in 10 seconds of free fall ");
28918  Put (Distance, Aft => 2, Exp => 0);
28919  Put_Line ("");
28920end Free_Fall;
28921@end example
28922@end quotation
28923
28924Execution of this program yields:
28925
28926@quotation
28927
28928@example
28929Gravitational constant:  9.81 m/sec^2
28930distance travelled in 10 seconds of free fall 490.50 m
28931@end example
28932@end quotation
28933
28934However, incorrect assignments such as:
28935
28936@quotation
28937
28938@example
28939Distance := 5.0;
28940Distance := 5.0 * kg:
28941@end example
28942@end quotation
28943
28944are rejected with the following diagnoses:
28945
28946@quotation
28947
28948@example
28949Distance := 5.0;
28950   >>> dimensions mismatch in assignment
28951   >>> left-hand side has dimension [L]
28952   >>> right-hand side is dimensionless
28953
28954Distance := 5.0 * kg:
28955   >>> dimensions mismatch in assignment
28956   >>> left-hand side has dimension [L]
28957   >>> right-hand side has dimension [M]
28958@end example
28959@end quotation
28960
28961The dimensions of an expression are properly displayed, even if there is
28962no explicit subtype for it. If we add to the program:
28963
28964@quotation
28965
28966@example
28967Put ("Final velocity: ");
28968Put (G * T, Aft =>2, Exp =>0);
28969Put_Line ("");
28970@end example
28971@end quotation
28972
28973then the output includes:
28974
28975@quotation
28976
28977@example
28978Final velocity: 98.10 m.s**(-1)
28979@end example
28980@end quotation
28981
28982@node Stack Related Facilities,Memory Management Issues,Performing Dimensionality Analysis in GNAT,GNAT and Program Execution
28983@anchor{gnat_ugn/gnat_and_program_execution id61}@anchor{1f8}@anchor{gnat_ugn/gnat_and_program_execution stack-related-facilities}@anchor{2b}
28984@section Stack Related Facilities
28985
28986
28987This section describes some useful tools associated with stack
28988checking and analysis. In
28989particular, it deals with dynamic and static stack usage measurements.
28990
28991@menu
28992* Stack Overflow Checking::
28993* Static Stack Usage Analysis::
28994* Dynamic Stack Usage Analysis::
28995
28996@end menu
28997
28998@node Stack Overflow Checking,Static Stack Usage Analysis,,Stack Related Facilities
28999@anchor{gnat_ugn/gnat_and_program_execution id62}@anchor{254}@anchor{gnat_ugn/gnat_and_program_execution stack-overflow-checking}@anchor{fc}
29000@subsection Stack Overflow Checking
29001
29002
29003@geindex Stack Overflow Checking
29004
29005@geindex -fstack-check (gcc)
29006
29007For most operating systems, @emph{gcc} does not perform stack overflow
29008checking by default. This means that if the main environment task or
29009some other task exceeds the available stack space, then unpredictable
29010behavior will occur. Most native systems offer some level of protection by
29011adding a guard page at the end of each task stack. This mechanism is usually
29012not enough for dealing properly with stack overflow situations because
29013a large local variable could "jump" above the guard page.
29014Furthermore, when the
29015guard page is hit, there may not be any space left on the stack for executing
29016the exception propagation code. Enabling stack checking avoids
29017such situations.
29018
29019To activate stack checking, compile all units with the gcc option
29020@cite{-fstack-check}. For example:
29021
29022@quotation
29023
29024@example
29025$ gcc -c -fstack-check package1.adb
29026@end example
29027@end quotation
29028
29029Units compiled with this option will generate extra instructions to check
29030that any use of the stack (for procedure calls or for declaring local
29031variables in declare blocks) does not exceed the available stack space.
29032If the space is exceeded, then a @cite{Storage_Error} exception is raised.
29033
29034For declared tasks, the stack size is controlled by the size
29035given in an applicable @cite{Storage_Size} pragma or by the value specified
29036at bind time with @code{-d} (@ref{126,,Switches for gnatbind}) or is set to
29037the default size as defined in the GNAT runtime otherwise.
29038
29039@geindex GNAT_STACK_LIMIT
29040
29041For the environment task, the stack size depends on
29042system defaults and is unknown to the compiler. Stack checking
29043may still work correctly if a fixed
29044size stack is allocated, but this cannot be guaranteed.
29045To ensure that a clean exception is signalled for stack
29046overflow, set the environment variable
29047@geindex GNAT_STACK_LIMIT
29048@geindex environment variable; GNAT_STACK_LIMIT
29049@code{GNAT_STACK_LIMIT} to indicate the maximum
29050stack area that can be used, as in:
29051
29052@quotation
29053
29054@example
29055$ SET GNAT_STACK_LIMIT 1600
29056@end example
29057@end quotation
29058
29059The limit is given in kilobytes, so the above declaration would
29060set the stack limit of the environment task to 1.6 megabytes.
29061Note that the only purpose of this usage is to limit the amount
29062of stack used by the environment task. If it is necessary to
29063increase the amount of stack for the environment task, then this
29064is an operating systems issue, and must be addressed with the
29065appropriate operating systems commands.
29066
29067@node Static Stack Usage Analysis,Dynamic Stack Usage Analysis,Stack Overflow Checking,Stack Related Facilities
29068@anchor{gnat_ugn/gnat_and_program_execution static-stack-usage-analysis}@anchor{fd}@anchor{gnat_ugn/gnat_and_program_execution id63}@anchor{255}
29069@subsection Static Stack Usage Analysis
29070
29071
29072@geindex Static Stack Usage Analysis
29073
29074@geindex -fstack-usage
29075
29076A unit compiled with @code{-fstack-usage} will generate an extra file
29077that specifies
29078the maximum amount of stack used, on a per-function basis.
29079The file has the same
29080basename as the target object file with a @code{.su} extension.
29081Each line of this file is made up of three fields:
29082
29083
29084@itemize *
29085
29086@item
29087The name of the function.
29088
29089@item
29090A number of bytes.
29091
29092@item
29093One or more qualifiers: @cite{static}, @cite{dynamic}, @cite{bounded}.
29094@end itemize
29095
29096The second field corresponds to the size of the known part of the function
29097frame.
29098
29099The qualifier @cite{static} means that the function frame size
29100is purely static.
29101It usually means that all local variables have a static size.
29102In this case, the second field is a reliable measure of the function stack
29103utilization.
29104
29105The qualifier @cite{dynamic} means that the function frame size is not static.
29106It happens mainly when some local variables have a dynamic size. When this
29107qualifier appears alone, the second field is not a reliable measure
29108of the function stack analysis. When it is qualified with  @cite{bounded}, it
29109means that the second field is a reliable maximum of the function stack
29110utilization.
29111
29112A unit compiled with @code{-Wstack-usage} will issue a warning for each
29113subprogram whose stack usage might be larger than the specified amount of
29114bytes.  The wording is in keeping with the qualifier documented above.
29115
29116@node Dynamic Stack Usage Analysis,,Static Stack Usage Analysis,Stack Related Facilities
29117@anchor{gnat_ugn/gnat_and_program_execution id64}@anchor{256}@anchor{gnat_ugn/gnat_and_program_execution dynamic-stack-usage-analysis}@anchor{128}
29118@subsection Dynamic Stack Usage Analysis
29119
29120
29121It is possible to measure the maximum amount of stack used by a task, by
29122adding a switch to @emph{gnatbind}, as:
29123
29124@quotation
29125
29126@example
29127$ gnatbind -u0 file
29128@end example
29129@end quotation
29130
29131With this option, at each task termination, its stack usage is  output on
29132@code{stderr}.
29133It is not always convenient to output the stack usage when the program
29134is still running. Hence, it is possible to delay this output until program
29135termination. for a given number of tasks specified as the argument of the
29136@code{-u} option. For instance:
29137
29138@quotation
29139
29140@example
29141$ gnatbind -u100 file
29142@end example
29143@end quotation
29144
29145will buffer the stack usage information of the first 100 tasks to terminate and
29146output this info at program termination. Results are displayed in four
29147columns:
29148
29149@quotation
29150
29151@example
29152Index | Task Name | Stack Size | Stack Usage
29153@end example
29154@end quotation
29155
29156where:
29157
29158
29159@itemize *
29160
29161@item
29162@emph{Index} is a number associated with each task.
29163
29164@item
29165@emph{Task Name} is the name of the task analyzed.
29166
29167@item
29168@emph{Stack Size} is the maximum size for the stack.
29169
29170@item
29171@emph{Stack Usage} is the measure done by the stack analyzer.
29172In order to prevent overflow, the stack
29173is not entirely analyzed, and it's not possible to know exactly how
29174much has actually been used.
29175@end itemize
29176
29177The environment task stack, e.g., the stack that contains the main unit, is
29178only processed when the environment variable GNAT_STACK_LIMIT is set.
29179
29180The package @cite{GNAT.Task_Stack_Usage} provides facilities to get
29181stack usage reports at run-time. See its body for the details.
29182
29183@node Memory Management Issues,,Stack Related Facilities,GNAT and Program Execution
29184@anchor{gnat_ugn/gnat_and_program_execution id65}@anchor{1f9}@anchor{gnat_ugn/gnat_and_program_execution memory-management-issues}@anchor{2c}
29185@section Memory Management Issues
29186
29187
29188This section describes some useful memory pools provided in the GNAT library
29189and in particular the GNAT Debug Pool facility, which can be used to detect
29190incorrect uses of access values (including 'dangling references').
29191
29192
29193@menu
29194* Some Useful Memory Pools::
29195* The GNAT Debug Pool Facility::
29196
29197@end menu
29198
29199@node Some Useful Memory Pools,The GNAT Debug Pool Facility,,Memory Management Issues
29200@anchor{gnat_ugn/gnat_and_program_execution id66}@anchor{257}@anchor{gnat_ugn/gnat_and_program_execution some-useful-memory-pools}@anchor{258}
29201@subsection Some Useful Memory Pools
29202
29203
29204@geindex Memory Pool
29205
29206@geindex storage
29207@geindex pool
29208
29209The @cite{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
29210storage pool. Allocations use the standard system call @cite{malloc} while
29211deallocations use the standard system call @cite{free}. No reclamation is
29212performed when the pool goes out of scope. For performance reasons, the
29213standard default Ada allocators/deallocators do not use any explicit storage
29214pools but if they did, they could use this storage pool without any change in
29215behavior. That is why this storage pool is used  when the user
29216manages to make the default implicit allocator explicit as in this example:
29217
29218@quotation
29219
29220@example
29221type T1 is access Something;
29222 -- no Storage pool is defined for T2
29223
29224type T2 is access Something_Else;
29225for T2'Storage_Pool use T1'Storage_Pool;
29226-- the above is equivalent to
29227for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
29228@end example
29229@end quotation
29230
29231The @cite{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
29232pool. The allocation strategy is similar to @cite{Pool_Local}'s
29233except that the all
29234storage allocated with this pool is reclaimed when the pool object goes out of
29235scope. This pool provides a explicit mechanism similar to the implicit one
29236provided by several Ada 83 compilers for allocations performed through a local
29237access type and whose purpose was to reclaim memory when exiting the
29238scope of a given local access. As an example, the following program does not
29239leak memory even though it does not perform explicit deallocation:
29240
29241@quotation
29242
29243@example
29244with System.Pool_Local;
29245procedure Pooloc1 is
29246   procedure Internal is
29247      type A is access Integer;
29248      X : System.Pool_Local.Unbounded_Reclaim_Pool;
29249      for A'Storage_Pool use X;
29250      v : A;
29251   begin
29252      for I in  1 .. 50 loop
29253         v := new Integer;
29254      end loop;
29255   end Internal;
29256begin
29257   for I in  1 .. 100 loop
29258      Internal;
29259   end loop;
29260end Pooloc1;
29261@end example
29262@end quotation
29263
29264The @cite{System.Pool_Size} package implements the Stack_Bounded_Pool used when
29265@cite{Storage_Size} is specified for an access type.
29266The whole storage for the pool is
29267allocated at once, usually on the stack at the point where the access type is
29268elaborated. It is automatically reclaimed when exiting the scope where the
29269access type is defined. This package is not intended to be used directly by the
29270user and it is implicitly used for each such declaration:
29271
29272@quotation
29273
29274@example
29275type T1 is access Something;
29276for T1'Storage_Size use 10_000;
29277@end example
29278@end quotation
29279
29280@node The GNAT Debug Pool Facility,,Some Useful Memory Pools,Memory Management Issues
29281@anchor{gnat_ugn/gnat_and_program_execution id67}@anchor{259}@anchor{gnat_ugn/gnat_and_program_execution the-gnat-debug-pool-facility}@anchor{25a}
29282@subsection The GNAT Debug Pool Facility
29283
29284
29285@geindex Debug Pool
29286
29287@geindex storage
29288@geindex pool
29289@geindex memory corruption
29290
29291The use of unchecked deallocation and unchecked conversion can easily
29292lead to incorrect memory references. The problems generated by such
29293references are usually difficult to tackle because the symptoms can be
29294very remote from the origin of the problem. In such cases, it is
29295very helpful to detect the problem as early as possible. This is the
29296purpose of the Storage Pool provided by @cite{GNAT.Debug_Pools}.
29297
29298In order to use the GNAT specific debugging pool, the user must
29299associate a debug pool object with each of the access types that may be
29300related to suspected memory problems. See Ada Reference Manual 13.11.
29301
29302@quotation
29303
29304@example
29305type Ptr is access Some_Type;
29306Pool : GNAT.Debug_Pools.Debug_Pool;
29307for Ptr'Storage_Pool use Pool;
29308@end example
29309@end quotation
29310
29311@cite{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
29312pool: the @cite{Checked_Pool}. Such pools, like standard Ada storage pools,
29313allow the user to redefine allocation and deallocation strategies. They
29314also provide a checkpoint for each dereference, through the use of
29315the primitive operation @cite{Dereference} which is implicitly called at
29316each dereference of an access value.
29317
29318Once an access type has been associated with a debug pool, operations on
29319values of the type may raise four distinct exceptions,
29320which correspond to four potential kinds of memory corruption:
29321
29322
29323@itemize *
29324
29325@item
29326@cite{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
29327
29328@item
29329@cite{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
29330
29331@item
29332@cite{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
29333
29334@item
29335@cite{GNAT.Debug_Pools.Freeing_Deallocated_Storage}
29336@end itemize
29337
29338For types associated with a Debug_Pool, dynamic allocation is performed using
29339the standard GNAT allocation routine. References to all allocated chunks of
29340memory are kept in an internal dictionary. Several deallocation strategies are
29341provided, whereupon the user can choose to release the memory to the system,
29342keep it allocated for further invalid access checks, or fill it with an easily
29343recognizable pattern for debug sessions. The memory pattern is the old IBM
29344hexadecimal convention: @cite{16#DEADBEEF#}.
29345
29346See the documentation in the file g-debpoo.ads for more information on the
29347various strategies.
29348
29349Upon each dereference, a check is made that the access value denotes a
29350properly allocated memory location. Here is a complete example of use of
29351@cite{Debug_Pools}, that includes typical instances of  memory corruption:
29352
29353@quotation
29354
29355@example
29356with Gnat.Io; use Gnat.Io;
29357with Unchecked_Deallocation;
29358with Unchecked_Conversion;
29359with GNAT.Debug_Pools;
29360with System.Storage_Elements;
29361with Ada.Exceptions; use Ada.Exceptions;
29362procedure Debug_Pool_Test is
29363
29364   type T is access Integer;
29365   type U is access all T;
29366
29367   P : GNAT.Debug_Pools.Debug_Pool;
29368   for T'Storage_Pool use P;
29369
29370   procedure Free is new Unchecked_Deallocation (Integer, T);
29371   function UC is new Unchecked_Conversion (U, T);
29372   A, B : aliased T;
29373
29374   procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
29375
29376begin
29377   Info (P);
29378   A := new Integer;
29379   B := new Integer;
29380   B := A;
29381   Info (P);
29382   Free (A);
29383   begin
29384      Put_Line (Integer'Image(B.all));
29385   exception
29386      when E : others => Put_Line ("raised: " & Exception_Name (E));
29387   end;
29388   begin
29389      Free (B);
29390   exception
29391      when E : others => Put_Line ("raised: " & Exception_Name (E));
29392   end;
29393   B := UC(A'Access);
29394   begin
29395      Put_Line (Integer'Image(B.all));
29396   exception
29397      when E : others => Put_Line ("raised: " & Exception_Name (E));
29398   end;
29399   begin
29400      Free (B);
29401   exception
29402      when E : others => Put_Line ("raised: " & Exception_Name (E));
29403   end;
29404   Info (P);
29405end Debug_Pool_Test;
29406@end example
29407@end quotation
29408
29409The debug pool mechanism provides the following precise diagnostics on the
29410execution of this erroneous program:
29411
29412@quotation
29413
29414@example
29415Debug Pool info:
29416  Total allocated bytes :  0
29417  Total deallocated bytes :  0
29418  Current Water Mark:  0
29419  High Water Mark:  0
29420
29421Debug Pool info:
29422  Total allocated bytes :  8
29423  Total deallocated bytes :  0
29424  Current Water Mark:  8
29425  High Water Mark:  8
29426
29427raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
29428raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
29429raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
29430raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
29431Debug Pool info:
29432  Total allocated bytes :  8
29433  Total deallocated bytes :  4
29434  Current Water Mark:  4
29435  High Water Mark:  8
29436@end example
29437@end quotation
29438
29439
29440@c -- Non-breaking space in running text
29441@c -- E.g. Ada |nbsp| 95
29442
29443@node Platform-Specific Information,Example of Binder Output File,GNAT and Program Execution,Top
29444@anchor{gnat_ugn/platform_specific_information platform-specific-information}@anchor{f}@anchor{gnat_ugn/platform_specific_information doc}@anchor{25b}@anchor{gnat_ugn/platform_specific_information id1}@anchor{25c}
29445@chapter Platform-Specific Information
29446
29447
29448This appendix contains information relating to the implementation
29449of run-time libraries on various platforms and also covers
29450topics related to the GNAT implementation on Windows and Mac OS.
29451
29452@menu
29453* Run-Time Libraries::
29454* Specifying a Run-Time Library::
29455* Microsoft Windows Topics::
29456* Mac OS Topics::
29457
29458@end menu
29459
29460@node Run-Time Libraries,Specifying a Run-Time Library,,Platform-Specific Information
29461@anchor{gnat_ugn/platform_specific_information id2}@anchor{25d}@anchor{gnat_ugn/platform_specific_information run-time-libraries}@anchor{2d}
29462@section Run-Time Libraries
29463
29464
29465@geindex Tasking and threads libraries
29466
29467@geindex Threads libraries and tasking
29468
29469@geindex Run-time libraries (platform-specific information)
29470
29471The GNAT run-time implementation may vary with respect to both the
29472underlying threads library and the exception handling scheme.
29473For threads support, one or more of the following are supplied:
29474
29475
29476@itemize *
29477
29478@item
29479@strong{native threads library}, a binding to the thread package from
29480the underlying operating system
29481
29482@item
29483@strong{pthreads library} (Sparc Solaris only), a binding to the Solaris
29484POSIX thread package
29485@end itemize
29486
29487For exception handling, either or both of two models are supplied:
29488
29489@quotation
29490
29491@geindex Zero-Cost Exceptions
29492
29493@geindex ZCX (Zero-Cost Exceptions)
29494@end quotation
29495
29496
29497@itemize *
29498
29499@item
29500@strong{Zero-Cost Exceptions} ("ZCX"),
29501which uses binder-generated tables that
29502are interrogated at run time to locate a handler.
29503
29504@geindex setjmp/longjmp Exception Model
29505
29506@geindex SJLJ (setjmp/longjmp Exception Model)
29507
29508@item
29509@strong{setjmp / longjmp} ('SJLJ'),
29510which uses dynamically-set data to establish
29511the set of handlers
29512@end itemize
29513
29514Most programs should experience a substantial speed improvement by
29515being compiled with a ZCX run-time.
29516This is especially true for
29517tasking applications or applications with many exception handlers.@}
29518
29519This section summarizes which combinations of threads and exception support
29520are supplied on various GNAT platforms.
29521It then shows how to select a particular library either
29522permanently or temporarily,
29523explains the properties of (and tradeoffs among) the various threads
29524libraries, and provides some additional
29525information about several specific platforms.
29526
29527@menu
29528* Summary of Run-Time Configurations::
29529
29530@end menu
29531
29532@node Summary of Run-Time Configurations,,,Run-Time Libraries
29533@anchor{gnat_ugn/platform_specific_information summary-of-run-time-configurations}@anchor{25e}@anchor{gnat_ugn/platform_specific_information id3}@anchor{25f}
29534@subsection Summary of Run-Time Configurations
29535
29536
29537
29538@multitable {xxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxx}
29539@headitem
29540
29541Platform
29542
29543@tab
29544
29545Run-Time
29546
29547@tab
29548
29549Tasking
29550
29551@tab
29552
29553Exceptions
29554
29555@item
29556
29557ppc-aix
29558
29559@tab
29560
29561rts-native
29562(default)
29563
29564@tab
29565
29566native AIX threads
29567
29568@tab
29569
29570ZCX
29571
29572@item
29573
29574rts-sjlj
29575
29576@tab
29577
29578native AIX threads
29579
29580@tab
29581
29582SJLJ
29583
29584@item
29585
29586sparc-solaris
29587
29588@tab
29589
29590rts-native
29591(default)
29592
29593@tab
29594
29595native Solaris
29596threads library
29597
29598@tab
29599
29600ZCX
29601
29602@item
29603
29604rts-pthread
29605
29606@tab
29607
29608pthread library
29609
29610@tab
29611
29612ZCX
29613
29614@item
29615
29616rts-sjlj
29617
29618@tab
29619
29620native Solaris
29621threads library
29622
29623@tab
29624
29625SJLJ
29626
29627@item
29628
29629sparc64-solaris
29630
29631@tab
29632
29633rts-native
29634(default)
29635
29636@tab
29637
29638native Solaris
29639threads library
29640
29641@tab
29642
29643ZCX
29644
29645@item
29646
29647x86-linux
29648
29649@tab
29650
29651rts-native
29652(default)
29653
29654@tab
29655
29656pthread library
29657
29658@tab
29659
29660ZCX
29661
29662@item
29663
29664rts-sjlj
29665
29666@tab
29667
29668pthread library
29669
29670@tab
29671
29672SJLJ
29673
29674@item
29675
29676x86-lynx
29677
29678@tab
29679
29680rts-native
29681(default)
29682
29683@tab
29684
29685native LynxOS threads
29686
29687@tab
29688
29689SJLJ
29690
29691@item
29692
29693x86-solaris
29694
29695@tab
29696
29697rts-native
29698(default)
29699
29700@tab
29701
29702native Solaris
29703threads library
29704
29705@tab
29706
29707ZCX
29708
29709@item
29710
29711rts-sjlj
29712
29713@tab
29714
29715native Solaris
29716threads library
29717
29718@tab
29719
29720SJLJ
29721
29722@item
29723
29724x86-windows
29725
29726@tab
29727
29728rts-native
29729(default)
29730
29731@tab
29732
29733native Win32 threads
29734
29735@tab
29736
29737ZCX
29738
29739@item
29740
29741rts-sjlj
29742
29743@tab
29744
29745native Win32 threads
29746
29747@tab
29748
29749SJLJ
29750
29751@item
29752
29753x86_64-linux
29754
29755@tab
29756
29757rts-native
29758(default)
29759
29760@tab
29761
29762pthread library
29763
29764@tab
29765
29766ZCX
29767
29768@item
29769
29770rts-sjlj
29771
29772@tab
29773
29774pthread library
29775
29776@tab
29777
29778SJLJ
29779
29780@end multitable
29781
29782
29783@node Specifying a Run-Time Library,Microsoft Windows Topics,Run-Time Libraries,Platform-Specific Information
29784@anchor{gnat_ugn/platform_specific_information specifying-a-run-time-library}@anchor{260}@anchor{gnat_ugn/platform_specific_information id4}@anchor{261}
29785@section Specifying a Run-Time Library
29786
29787
29788The @code{adainclude} subdirectory containing the sources of the GNAT
29789run-time library, and the @code{adalib} subdirectory containing the
29790@code{ALI} files and the static and/or shared GNAT library, are located
29791in the gcc target-dependent area:
29792
29793@quotation
29794
29795@example
29796target=$prefix/lib/gcc/gcc-*dumpmachine*/gcc-*dumpversion*/
29797@end example
29798@end quotation
29799
29800As indicated above, on some platforms several run-time libraries are supplied.
29801These libraries are installed in the target dependent area and
29802contain a complete source and binary subdirectory. The detailed description
29803below explains the differences between the different libraries in terms of
29804their thread support.
29805
29806The default run-time library (when GNAT is installed) is @emph{rts-native}.
29807This default run time is selected by the means of soft links.
29808For example on x86-linux:
29809
29810@example
29811--
29812--  $(target-dir)
29813--      |
29814--      +--- adainclude----------+
29815--      |                        |
29816--      +--- adalib-----------+  |
29817--      |                     |  |
29818--      +--- rts-native       |  |
29819--      |    |                |  |
29820--      |    +--- adainclude <---+
29821--      |    |                |
29822--      |    +--- adalib <----+
29823--      |
29824--      +--- rts-sjlj
29825--           |
29826--           +--- adainclude
29827--           |
29828--           +--- adalib
29829@end example
29830
29831If the @emph{rts-sjlj} library is to be selected on a permanent basis,
29832these soft links can be modified with the following commands:
29833
29834@quotation
29835
29836@example
29837$ cd $target
29838$ rm -f adainclude adalib
29839$ ln -s rts-sjlj/adainclude adainclude
29840$ ln -s rts-sjlj/adalib adalib
29841@end example
29842@end quotation
29843
29844Alternatively, you can specify @code{rts-sjlj/adainclude} in the file
29845@code{$target/ada_source_path} and @code{rts-sjlj/adalib} in
29846@code{$target/ada_object_path}.
29847
29848@geindex --RTS option
29849
29850Selecting another run-time library temporarily can be
29851achieved by using the @emph{--RTS} switch, e.g., @emph{--RTS=sjlj}
29852@anchor{gnat_ugn/platform_specific_information choosing-the-scheduling-policy}@anchor{262}
29853@geindex SCHED_FIFO scheduling policy
29854
29855@geindex SCHED_RR scheduling policy
29856
29857@geindex SCHED_OTHER scheduling policy
29858
29859@menu
29860* Choosing the Scheduling Policy::
29861* Solaris-Specific Considerations::
29862* Solaris Threads Issues::
29863* AIX-Specific Considerations::
29864
29865@end menu
29866
29867@node Choosing the Scheduling Policy,Solaris-Specific Considerations,,Specifying a Run-Time Library
29868@anchor{gnat_ugn/platform_specific_information id5}@anchor{263}
29869@subsection Choosing the Scheduling Policy
29870
29871
29872When using a POSIX threads implementation, you have a choice of several
29873scheduling policies: @cite{SCHED_FIFO}, @cite{SCHED_RR} and @cite{SCHED_OTHER}.
29874
29875Typically, the default is @cite{SCHED_OTHER}, while using @cite{SCHED_FIFO}
29876or @cite{SCHED_RR} requires special (e.g., root) privileges.
29877
29878@geindex pragma Time_Slice
29879
29880@geindex -T0 option
29881
29882@geindex pragma Task_Dispatching_Policy
29883
29884By default, GNAT uses the @cite{SCHED_OTHER} policy. To specify
29885@cite{SCHED_FIFO},
29886you can use one of the following:
29887
29888
29889@itemize *
29890
29891@item
29892@cite{pragma Time_Slice (0.0)}
29893
29894@item
29895the corresponding binder option @emph{-T0}
29896
29897@item
29898@cite{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
29899@end itemize
29900
29901To specify @cite{SCHED_RR},
29902you should use @cite{pragma Time_Slice} with a
29903value greater than 0.0, or else use the corresponding @emph{-T}
29904binder option.
29905
29906@geindex Solaris Sparc threads libraries
29907
29908@node Solaris-Specific Considerations,Solaris Threads Issues,Choosing the Scheduling Policy,Specifying a Run-Time Library
29909@anchor{gnat_ugn/platform_specific_information id6}@anchor{264}@anchor{gnat_ugn/platform_specific_information solaris-specific-considerations}@anchor{265}
29910@subsection Solaris-Specific Considerations
29911
29912
29913This section addresses some topics related to the various threads libraries
29914on Sparc Solaris.
29915
29916@geindex rts-pthread threads library
29917
29918@node Solaris Threads Issues,AIX-Specific Considerations,Solaris-Specific Considerations,Specifying a Run-Time Library
29919@anchor{gnat_ugn/platform_specific_information id7}@anchor{266}@anchor{gnat_ugn/platform_specific_information solaris-threads-issues}@anchor{267}
29920@subsection Solaris Threads Issues
29921
29922
29923GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
29924library based on POSIX threads --- @emph{rts-pthread}.
29925
29926@geindex PTHREAD_PRIO_INHERIT policy (under rts-pthread)
29927
29928@geindex PTHREAD_PRIO_PROTECT policy (under rts-pthread)
29929
29930@geindex pragma Locking_Policy (under rts-pthread)
29931
29932@geindex Inheritance_Locking (under rts-pthread)
29933
29934@geindex Ceiling_Locking (under rts-pthread)
29935
29936This run-time library has the advantage of being mostly shared across all
29937POSIX-compliant thread implementations, and it also provides under
29938Solaris 8 the @cite{PTHREAD_PRIO_INHERIT}
29939and @cite{PTHREAD_PRIO_PROTECT}
29940semantics that can be selected using the predefined pragma
29941@cite{Locking_Policy}
29942with respectively
29943@cite{Inheritance_Locking} and @cite{Ceiling_Locking} as the policy.
29944
29945As explained above, the native run-time library is based on the Solaris thread
29946library (@cite{libthread}) and is the default library.
29947
29948@geindex GNAT_PROCESSOR environment variable (on Sparc Solaris)
29949
29950When the Solaris threads library is used (this is the default), programs
29951compiled with GNAT can automatically take advantage of
29952and can thus execute on multiple processors.
29953The user can alternatively specify a processor on which the program should run
29954to emulate a single-processor system. The multiprocessor / uniprocessor choice
29955is made by
29956setting the environment variable
29957@geindex GNAT_PROCESSOR
29958@geindex environment variable; GNAT_PROCESSOR
29959@code{GNAT_PROCESSOR}
29960to one of the following:
29961
29962@quotation
29963
29964
29965@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
29966@headitem
29967
29968@code{GNAT_PROCESSOR} Value
29969
29970@tab
29971
29972Effect
29973
29974@item
29975
29976@emph{-2}
29977
29978@tab
29979
29980Use the default configuration (run the program on all
29981available processors) - this is the same as having @cite{GNAT_PROCESSOR}
29982unset
29983
29984@item
29985
29986@emph{-1}
29987
29988@tab
29989
29990Let the run-time implementation choose one processor and run the
29991program on that processor
29992
29993@item
29994
29995@emph{0 .. Last_Proc}
29996
29997@tab
29998
29999Run the program on the specified processor.
30000@cite{Last_Proc} is equal to @cite{_SC_NPROCESSORS_CONF - 1}
30001(where @cite{_SC_NPROCESSORS_CONF} is a system variable).
30002
30003@end multitable
30004
30005@end quotation
30006
30007@node AIX-Specific Considerations,,Solaris Threads Issues,Specifying a Run-Time Library
30008@anchor{gnat_ugn/platform_specific_information aix-specific-considerations}@anchor{268}@anchor{gnat_ugn/platform_specific_information id8}@anchor{269}
30009@subsection AIX-Specific Considerations
30010
30011
30012@geindex AIX resolver library
30013
30014On AIX, the resolver library initializes some internal structure on
30015the first call to @cite{get*by*} functions, which are used to implement
30016@cite{GNAT.Sockets.Get_Host_By_Name} and
30017@cite{GNAT.Sockets.Get_Host_By_Address}.
30018If such initialization occurs within an Ada task, and the stack size for
30019the task is the default size, a stack overflow may occur.
30020
30021To avoid this overflow, the user should either ensure that the first call
30022to @cite{GNAT.Sockets.Get_Host_By_Name} or
30023@cite{GNAT.Sockets.Get_Host_By_Addrss}
30024occurs in the environment task, or use @cite{pragma Storage_Size} to
30025specify a sufficiently large size for the stack of the task that contains
30026this call.
30027
30028@geindex Windows NT
30029
30030@geindex Windows 95
30031
30032@geindex Windows 98
30033
30034@node Microsoft Windows Topics,Mac OS Topics,Specifying a Run-Time Library,Platform-Specific Information
30035@anchor{gnat_ugn/platform_specific_information microsoft-windows-topics}@anchor{2e}@anchor{gnat_ugn/platform_specific_information id9}@anchor{26a}
30036@section Microsoft Windows Topics
30037
30038
30039This section describes topics that are specific to the Microsoft Windows
30040platforms.
30041
30042
30043
30044
30045
30046@menu
30047* Using GNAT on Windows::
30048* Using a network installation of GNAT::
30049* CONSOLE and WINDOWS subsystems::
30050* Temporary Files::
30051* Mixed-Language Programming on Windows::
30052* Windows Specific Add-Ons::
30053
30054@end menu
30055
30056@node Using GNAT on Windows,Using a network installation of GNAT,,Microsoft Windows Topics
30057@anchor{gnat_ugn/platform_specific_information using-gnat-on-windows}@anchor{26b}@anchor{gnat_ugn/platform_specific_information id10}@anchor{26c}
30058@subsection Using GNAT on Windows
30059
30060
30061One of the strengths of the GNAT technology is that its tool set
30062(@emph{gcc}, @emph{gnatbind}, @emph{gnatlink}, @emph{gnatmake}, the
30063@cite{gdb} debugger, etc.) is used in the same way regardless of the
30064platform.
30065
30066On Windows this tool set is complemented by a number of Microsoft-specific
30067tools that have been provided to facilitate interoperability with Windows
30068when this is required. With these tools:
30069
30070
30071@itemize *
30072
30073@item
30074You can build applications using the @cite{CONSOLE} or @cite{WINDOWS}
30075subsystems.
30076
30077@item
30078You can use any Dynamically Linked Library (DLL) in your Ada code (both
30079relocatable and non-relocatable DLLs are supported).
30080
30081@item
30082You can build Ada DLLs for use in other applications. These applications
30083can be written in a language other than Ada (e.g., C, C++, etc). Again both
30084relocatable and non-relocatable Ada DLLs are supported.
30085
30086@item
30087You can include Windows resources in your Ada application.
30088
30089@item
30090You can use or create COM/DCOM objects.
30091@end itemize
30092
30093Immediately below are listed all known general GNAT-for-Windows restrictions.
30094Other restrictions about specific features like Windows Resources and DLLs
30095are listed in separate sections below.
30096
30097
30098@itemize *
30099
30100@item
30101It is not possible to use @cite{GetLastError} and @cite{SetLastError}
30102when tasking, protected records, or exceptions are used. In these
30103cases, in order to implement Ada semantics, the GNAT run-time system
30104calls certain Win32 routines that set the last error variable to 0 upon
30105success. It should be possible to use @cite{GetLastError} and
30106@cite{SetLastError} when tasking, protected record, and exception
30107features are not used, but it is not guaranteed to work.
30108
30109@item
30110It is not possible to link against Microsoft C++ libraries except for
30111import libraries. Interfacing must be done by the mean of DLLs.
30112
30113@item
30114It is possible to link against Microsoft C libraries. Yet the preferred
30115solution is to use C/C++ compiler that comes with GNAT, since it
30116doesn't require having two different development environments and makes the
30117inter-language debugging experience smoother.
30118
30119@item
30120When the compilation environment is located on FAT32 drives, users may
30121experience recompilations of the source files that have not changed if
30122Daylight Saving Time (DST) state has changed since the last time files
30123were compiled. NTFS drives do not have this problem.
30124
30125@item
30126No components of the GNAT toolset use any entries in the Windows
30127registry. The only entries that can be created are file associations and
30128PATH settings, provided the user has chosen to create them at installation
30129time, as well as some minimal book-keeping information needed to correctly
30130uninstall or integrate different GNAT products.
30131@end itemize
30132
30133@node Using a network installation of GNAT,CONSOLE and WINDOWS subsystems,Using GNAT on Windows,Microsoft Windows Topics
30134@anchor{gnat_ugn/platform_specific_information id11}@anchor{26d}@anchor{gnat_ugn/platform_specific_information using-a-network-installation-of-gnat}@anchor{26e}
30135@subsection Using a network installation of GNAT
30136
30137
30138Make sure the system on which GNAT is installed is accessible from the
30139current machine, i.e., the install location is shared over the network.
30140Shared resources are accessed on Windows by means of UNC paths, which
30141have the format @cite{\\server\sharename\path}
30142
30143In order to use such a network installation, simply add the UNC path of the
30144@code{bin} directory of your GNAT installation in front of your PATH. For
30145example, if GNAT is installed in @code{\GNAT} directory of a share location
30146called @code{c-drive} on a machine @code{LOKI}, the following command will
30147make it available:
30148
30149@quotation
30150
30151@example
30152$ path \\loki\c-drive\gnat\bin;%path%`
30153@end example
30154@end quotation
30155
30156Be aware that every compilation using the network installation results in the
30157transfer of large amounts of data across the network and will likely cause
30158serious performance penalty.
30159
30160@node CONSOLE and WINDOWS subsystems,Temporary Files,Using a network installation of GNAT,Microsoft Windows Topics
30161@anchor{gnat_ugn/platform_specific_information id12}@anchor{26f}@anchor{gnat_ugn/platform_specific_information console-and-windows-subsystems}@anchor{270}
30162@subsection CONSOLE and WINDOWS subsystems
30163
30164
30165@geindex CONSOLE Subsystem
30166
30167@geindex WINDOWS Subsystem
30168
30169@geindex -mwindows
30170
30171There are two main subsystems under Windows. The @cite{CONSOLE} subsystem
30172(which is the default subsystem) will always create a console when
30173launching the application. This is not something desirable when the
30174application has a Windows GUI. To get rid of this console the
30175application must be using the @cite{WINDOWS} subsystem. To do so
30176the @emph{-mwindows} linker option must be specified.
30177
30178@quotation
30179
30180@example
30181$ gnatmake winprog -largs -mwindows
30182@end example
30183@end quotation
30184
30185@node Temporary Files,Mixed-Language Programming on Windows,CONSOLE and WINDOWS subsystems,Microsoft Windows Topics
30186@anchor{gnat_ugn/platform_specific_information id13}@anchor{271}@anchor{gnat_ugn/platform_specific_information temporary-files}@anchor{272}
30187@subsection Temporary Files
30188
30189
30190@geindex Temporary files
30191
30192It is possible to control where temporary files gets created by setting
30193the
30194@geindex TMP
30195@geindex environment variable; TMP
30196@code{TMP} environment variable. The file will be created:
30197
30198
30199@itemize *
30200
30201@item
30202Under the directory pointed to by the
30203@geindex TMP
30204@geindex environment variable; TMP
30205@code{TMP} environment variable if
30206this directory exists.
30207
30208@item
30209Under @code{c:\temp}, if the
30210@geindex TMP
30211@geindex environment variable; TMP
30212@code{TMP} environment variable is not
30213set (or not pointing to a directory) and if this directory exists.
30214
30215@item
30216Under the current working directory otherwise.
30217@end itemize
30218
30219This allows you to determine exactly where the temporary
30220file will be created. This is particularly useful in networked
30221environments where you may not have write access to some
30222directories.
30223
30224@node Mixed-Language Programming on Windows,Windows Specific Add-Ons,Temporary Files,Microsoft Windows Topics
30225@anchor{gnat_ugn/platform_specific_information mixed-language-programming-on-windows}@anchor{273}@anchor{gnat_ugn/platform_specific_information id14}@anchor{274}
30226@subsection Mixed-Language Programming on Windows
30227
30228
30229Developing pure Ada applications on Windows is no different than on
30230other GNAT-supported platforms. However, when developing or porting an
30231application that contains a mix of Ada and C/C++, the choice of your
30232Windows C/C++ development environment conditions your overall
30233interoperability strategy.
30234
30235If you use @emph{gcc} or Microsoft C to compile the non-Ada part of
30236your application, there are no Windows-specific restrictions that
30237affect the overall interoperability with your Ada code. If you do want
30238to use the Microsoft tools for your C++ code, you have two choices:
30239
30240
30241@itemize *
30242
30243@item
30244Encapsulate your C++ code in a DLL to be linked with your Ada
30245application. In this case, use the Microsoft or whatever environment to
30246build the DLL and use GNAT to build your executable
30247(@ref{275,,Using DLLs with GNAT}).
30248
30249@item
30250Or you can encapsulate your Ada code in a DLL to be linked with the
30251other part of your application. In this case, use GNAT to build the DLL
30252(@ref{276,,Building DLLs with GNAT Project files}) and use the Microsoft
30253or whatever environment to build your executable.
30254@end itemize
30255
30256In addition to the description about C main in
30257@ref{46,,Mixed Language Programming} section, if the C main uses a
30258stand-alone library it is required on x86-windows to
30259setup the SEH context. For this the C main must looks like this:
30260
30261@quotation
30262
30263@example
30264/* main.c */
30265extern void adainit (void);
30266extern void adafinal (void);
30267extern void __gnat_initialize(void*);
30268extern void call_to_ada (void);
30269
30270int main (int argc, char *argv[])
30271@{
30272  int SEH [2];
30273
30274  /* Initialize the SEH context */
30275  __gnat_initialize (&SEH);
30276
30277  adainit();
30278
30279  /* Then call Ada services in the stand-alone library */
30280
30281  call_to_ada();
30282
30283  adafinal();
30284@}
30285@end example
30286@end quotation
30287
30288Note that this is not needed on x86_64-windows where the Windows
30289native SEH support is used.
30290
30291@menu
30292* Windows Calling Conventions::
30293* Introduction to Dynamic Link Libraries (DLLs): Introduction to Dynamic Link Libraries DLLs.
30294* Using DLLs with GNAT::
30295* Building DLLs with GNAT Project files::
30296* Building DLLs with GNAT::
30297* Building DLLs with gnatdll::
30298* Ada DLLs and Finalization::
30299* Creating a Spec for Ada DLLs::
30300* GNAT and Windows Resources::
30301* Using GNAT DLLs from Microsoft Visual Studio Applications::
30302* Debugging a DLL::
30303* Setting Stack Size from gnatlink::
30304* Setting Heap Size from gnatlink::
30305
30306@end menu
30307
30308@node Windows Calling Conventions,Introduction to Dynamic Link Libraries DLLs,,Mixed-Language Programming on Windows
30309@anchor{gnat_ugn/platform_specific_information windows-calling-conventions}@anchor{277}@anchor{gnat_ugn/platform_specific_information id15}@anchor{278}
30310@subsubsection Windows Calling Conventions
30311
30312
30313@geindex Stdcall
30314
30315@geindex APIENTRY
30316
30317This section pertain only to Win32. On Win64 there is a single native
30318calling convention. All convention specifiers are ignored on this
30319platform.
30320
30321When a subprogram @cite{F} (caller) calls a subprogram @cite{G}
30322(callee), there are several ways to push @cite{G}'s parameters on the
30323stack and there are several possible scenarios to clean up the stack
30324upon @cite{G}'s return. A calling convention is an agreed upon software
30325protocol whereby the responsibilities between the caller (@cite{F}) and
30326the callee (@cite{G}) are clearly defined. Several calling conventions
30327are available for Windows:
30328
30329
30330@itemize *
30331
30332@item
30333@cite{C} (Microsoft defined)
30334
30335@item
30336@cite{Stdcall} (Microsoft defined)
30337
30338@item
30339@cite{Win32} (GNAT specific)
30340
30341@item
30342@cite{DLL} (GNAT specific)
30343@end itemize
30344
30345@menu
30346* C Calling Convention::
30347* Stdcall Calling Convention::
30348* Win32 Calling Convention::
30349* DLL Calling Convention::
30350
30351@end menu
30352
30353@node C Calling Convention,Stdcall Calling Convention,,Windows Calling Conventions
30354@anchor{gnat_ugn/platform_specific_information c-calling-convention}@anchor{279}@anchor{gnat_ugn/platform_specific_information id16}@anchor{27a}
30355@subsubsection @cite{C} Calling Convention
30356
30357
30358This is the default calling convention used when interfacing to C/C++
30359routines compiled with either @emph{gcc} or Microsoft Visual C++.
30360
30361In the @cite{C} calling convention subprogram parameters are pushed on the
30362stack by the caller from right to left. The caller itself is in charge of
30363cleaning up the stack after the call. In addition, the name of a routine
30364with @cite{C} calling convention is mangled by adding a leading underscore.
30365
30366The name to use on the Ada side when importing (or exporting) a routine
30367with @cite{C} calling convention is the name of the routine. For
30368instance the C function:
30369
30370@quotation
30371
30372@example
30373int get_val (long);
30374@end example
30375@end quotation
30376
30377should be imported from Ada as follows:
30378
30379@quotation
30380
30381@example
30382function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30383pragma Import (C, Get_Val, External_Name => "get_val");
30384@end example
30385@end quotation
30386
30387Note that in this particular case the @cite{External_Name} parameter could
30388have been omitted since, when missing, this parameter is taken to be the
30389name of the Ada entity in lower case. When the @cite{Link_Name} parameter
30390is missing, as in the above example, this parameter is set to be the
30391@cite{External_Name} with a leading underscore.
30392
30393When importing a variable defined in C, you should always use the @cite{C}
30394calling convention unless the object containing the variable is part of a
30395DLL (in which case you should use the @cite{Stdcall} calling
30396convention, @ref{27b,,Stdcall Calling Convention}).
30397
30398@node Stdcall Calling Convention,Win32 Calling Convention,C Calling Convention,Windows Calling Conventions
30399@anchor{gnat_ugn/platform_specific_information stdcall-calling-convention}@anchor{27b}@anchor{gnat_ugn/platform_specific_information id17}@anchor{27c}
30400@subsubsection @cite{Stdcall} Calling Convention
30401
30402
30403This convention, which was the calling convention used for Pascal
30404programs, is used by Microsoft for all the routines in the Win32 API for
30405efficiency reasons. It must be used to import any routine for which this
30406convention was specified.
30407
30408In the @cite{Stdcall} calling convention subprogram parameters are pushed
30409on the stack by the caller from right to left. The callee (and not the
30410caller) is in charge of cleaning the stack on routine exit. In addition,
30411the name of a routine with @cite{Stdcall} calling convention is mangled by
30412adding a leading underscore (as for the @cite{C} calling convention) and a
30413trailing @code{@@@emph{nn}}, where @cite{nn} is the overall size (in
30414bytes) of the parameters passed to the routine.
30415
30416The name to use on the Ada side when importing a C routine with a
30417@cite{Stdcall} calling convention is the name of the C routine. The leading
30418underscore and trailing @code{@@@emph{nn}} are added automatically by
30419the compiler. For instance the Win32 function:
30420
30421@quotation
30422
30423@example
30424APIENTRY int get_val (long);
30425@end example
30426@end quotation
30427
30428should be imported from Ada as follows:
30429
30430@quotation
30431
30432@example
30433function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30434pragma Import (Stdcall, Get_Val);
30435--  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
30436@end example
30437@end quotation
30438
30439As for the @cite{C} calling convention, when the @cite{External_Name}
30440parameter is missing, it is taken to be the name of the Ada entity in lower
30441case. If instead of writing the above import pragma you write:
30442
30443@quotation
30444
30445@example
30446function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30447pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
30448@end example
30449@end quotation
30450
30451then the imported routine is @cite{_retrieve_val@@4}. However, if instead
30452of specifying the @cite{External_Name} parameter you specify the
30453@cite{Link_Name} as in the following example:
30454
30455@quotation
30456
30457@example
30458function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30459pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
30460@end example
30461@end quotation
30462
30463then the imported routine is @cite{retrieve_val}, that is, there is no
30464decoration at all. No leading underscore and no Stdcall suffix
30465@code{@@@emph{nn}}.
30466
30467This is especially important as in some special cases a DLL's entry
30468point name lacks a trailing @code{@@@emph{nn}} while the exported
30469name generated for a call has it.
30470
30471It is also possible to import variables defined in a DLL by using an
30472import pragma for a variable. As an example, if a DLL contains a
30473variable defined as:
30474
30475@quotation
30476
30477@example
30478int my_var;
30479@end example
30480@end quotation
30481
30482then, to access this variable from Ada you should write:
30483
30484@quotation
30485
30486@example
30487My_Var : Interfaces.C.int;
30488pragma Import (Stdcall, My_Var);
30489@end example
30490@end quotation
30491
30492Note that to ease building cross-platform bindings this convention
30493will be handled as a @cite{C} calling convention on non-Windows platforms.
30494
30495@node Win32 Calling Convention,DLL Calling Convention,Stdcall Calling Convention,Windows Calling Conventions
30496@anchor{gnat_ugn/platform_specific_information id18}@anchor{27d}@anchor{gnat_ugn/platform_specific_information win32-calling-convention}@anchor{27e}
30497@subsubsection @cite{Win32} Calling Convention
30498
30499
30500This convention, which is GNAT-specific is fully equivalent to the
30501@cite{Stdcall} calling convention described above.
30502
30503@node DLL Calling Convention,,Win32 Calling Convention,Windows Calling Conventions
30504@anchor{gnat_ugn/platform_specific_information id19}@anchor{27f}@anchor{gnat_ugn/platform_specific_information dll-calling-convention}@anchor{280}
30505@subsubsection @cite{DLL} Calling Convention
30506
30507
30508This convention, which is GNAT-specific is fully equivalent to the
30509@cite{Stdcall} calling convention described above.
30510
30511@node Introduction to Dynamic Link Libraries DLLs,Using DLLs with GNAT,Windows Calling Conventions,Mixed-Language Programming on Windows
30512@anchor{gnat_ugn/platform_specific_information id20}@anchor{281}@anchor{gnat_ugn/platform_specific_information introduction-to-dynamic-link-libraries-dlls}@anchor{282}
30513@subsubsection Introduction to Dynamic Link Libraries (DLLs)
30514
30515
30516@geindex DLL
30517
30518A Dynamically Linked Library (DLL) is a library that can be shared by
30519several applications running under Windows. A DLL can contain any number of
30520routines and variables.
30521
30522One advantage of DLLs is that you can change and enhance them without
30523forcing all the applications that depend on them to be relinked or
30524recompiled. However, you should be aware than all calls to DLL routines are
30525slower since, as you will understand below, such calls are indirect.
30526
30527To illustrate the remainder of this section, suppose that an application
30528wants to use the services of a DLL @code{API.dll}. To use the services
30529provided by @code{API.dll} you must statically link against the DLL or
30530an import library which contains a jump table with an entry for each
30531routine and variable exported by the DLL. In the Microsoft world this
30532import library is called @code{API.lib}. When using GNAT this import
30533library is called either @code{libAPI.dll.a}, @code{libapi.dll.a},
30534@code{libAPI.a} or @code{libapi.a} (names are case insensitive).
30535
30536After you have linked your application with the DLL or the import library
30537and you run your application, here is what happens:
30538
30539
30540@itemize *
30541
30542@item
30543Your application is loaded into memory.
30544
30545@item
30546The DLL @code{API.dll} is mapped into the address space of your
30547application. This means that:
30548
30549
30550@itemize -
30551
30552@item
30553The DLL will use the stack of the calling thread.
30554
30555@item
30556The DLL will use the virtual address space of the calling process.
30557
30558@item
30559The DLL will allocate memory from the virtual address space of the calling
30560process.
30561
30562@item
30563Handles (pointers) can be safely exchanged between routines in the DLL
30564routines and routines in the application using the DLL.
30565@end itemize
30566
30567@item
30568The entries in the jump table (from the import library @code{libAPI.dll.a}
30569or @code{API.lib} or automatically created when linking against a DLL)
30570which is part of your application are initialized with the addresses
30571of the routines and variables in @code{API.dll}.
30572
30573@item
30574If present in @code{API.dll}, routines @cite{DllMain} or
30575@cite{DllMainCRTStartup} are invoked. These routines typically contain
30576the initialization code needed for the well-being of the routines and
30577variables exported by the DLL.
30578@end itemize
30579
30580There is an additional point which is worth mentioning. In the Windows
30581world there are two kind of DLLs: relocatable and non-relocatable
30582DLLs. Non-relocatable DLLs can only be loaded at a very specific address
30583in the target application address space. If the addresses of two
30584non-relocatable DLLs overlap and these happen to be used by the same
30585application, a conflict will occur and the application will run
30586incorrectly. Hence, when possible, it is always preferable to use and
30587build relocatable DLLs. Both relocatable and non-relocatable DLLs are
30588supported by GNAT. Note that the @emph{-s} linker option (see GNU Linker
30589User's Guide) removes the debugging symbols from the DLL but the DLL can
30590still be relocated.
30591
30592As a side note, an interesting difference between Microsoft DLLs and
30593Unix shared libraries, is the fact that on most Unix systems all public
30594routines are exported by default in a Unix shared library, while under
30595Windows it is possible (but not required) to list exported routines in
30596a definition file (see @ref{283,,The Definition File}).
30597
30598@node Using DLLs with GNAT,Building DLLs with GNAT Project files,Introduction to Dynamic Link Libraries DLLs,Mixed-Language Programming on Windows
30599@anchor{gnat_ugn/platform_specific_information id21}@anchor{284}@anchor{gnat_ugn/platform_specific_information using-dlls-with-gnat}@anchor{275}
30600@subsubsection Using DLLs with GNAT
30601
30602
30603To use the services of a DLL, say @code{API.dll}, in your Ada application
30604you must have:
30605
30606
30607@itemize *
30608
30609@item
30610The Ada spec for the routines and/or variables you want to access in
30611@code{API.dll}. If not available this Ada spec must be built from the C/C++
30612header files provided with the DLL.
30613
30614@item
30615The import library (@code{libAPI.dll.a} or @code{API.lib}). As previously
30616mentioned an import library is a statically linked library containing the
30617import table which will be filled at load time to point to the actual
30618@code{API.dll} routines. Sometimes you don't have an import library for the
30619DLL you want to use. The following sections will explain how to build
30620one. Note that this is optional.
30621
30622@item
30623The actual DLL, @code{API.dll}.
30624@end itemize
30625
30626Once you have all the above, to compile an Ada application that uses the
30627services of @code{API.dll} and whose main subprogram is @cite{My_Ada_App},
30628you simply issue the command
30629
30630@quotation
30631
30632@example
30633$ gnatmake my_ada_app -largs -lAPI
30634@end example
30635@end quotation
30636
30637The argument @emph{-largs -lAPI} at the end of the @emph{gnatmake} command
30638tells the GNAT linker to look for an import library. The linker will
30639look for a library name in this specific order:
30640
30641
30642@itemize *
30643
30644@item
30645@code{libAPI.dll.a}
30646
30647@item
30648@code{API.dll.a}
30649
30650@item
30651@code{libAPI.a}
30652
30653@item
30654@code{API.lib}
30655
30656@item
30657@code{libAPI.dll}
30658
30659@item
30660@code{API.dll}
30661@end itemize
30662
30663The first three are the GNU style import libraries. The third is the
30664Microsoft style import libraries. The last two are the actual DLL names.
30665
30666Note that if the Ada package spec for @code{API.dll} contains the
30667following pragma
30668
30669@quotation
30670
30671@example
30672pragma Linker_Options ("-lAPI");
30673@end example
30674@end quotation
30675
30676you do not have to add @emph{-largs -lAPI} at the end of the
30677@emph{gnatmake} command.
30678
30679If any one of the items above is missing you will have to create it
30680yourself. The following sections explain how to do so using as an
30681example a fictitious DLL called @code{API.dll}.
30682
30683@menu
30684* Creating an Ada Spec for the DLL Services::
30685* Creating an Import Library::
30686
30687@end menu
30688
30689@node Creating an Ada Spec for the DLL Services,Creating an Import Library,,Using DLLs with GNAT
30690@anchor{gnat_ugn/platform_specific_information creating-an-ada-spec-for-the-dll-services}@anchor{285}@anchor{gnat_ugn/platform_specific_information id22}@anchor{286}
30691@subsubsection Creating an Ada Spec for the DLL Services
30692
30693
30694A DLL typically comes with a C/C++ header file which provides the
30695definitions of the routines and variables exported by the DLL. The Ada
30696equivalent of this header file is a package spec that contains definitions
30697for the imported entities. If the DLL you intend to use does not come with
30698an Ada spec you have to generate one such spec yourself. For example if
30699the header file of @code{API.dll} is a file @code{api.h} containing the
30700following two definitions:
30701
30702@quotation
30703
30704@example
30705int some_var;
30706int get (char *);
30707@end example
30708@end quotation
30709
30710then the equivalent Ada spec could be:
30711
30712@quotation
30713
30714@example
30715with Interfaces.C.Strings;
30716package API is
30717   use Interfaces;
30718
30719   Some_Var : C.int;
30720   function Get (Str : C.Strings.Chars_Ptr) return C.int;
30721
30722private
30723   pragma Import (C, Get);
30724   pragma Import (DLL, Some_Var);
30725end API;
30726@end example
30727@end quotation
30728
30729@node Creating an Import Library,,Creating an Ada Spec for the DLL Services,Using DLLs with GNAT
30730@anchor{gnat_ugn/platform_specific_information id23}@anchor{287}@anchor{gnat_ugn/platform_specific_information creating-an-import-library}@anchor{288}
30731@subsubsection Creating an Import Library
30732
30733
30734@geindex Import library
30735
30736If a Microsoft-style import library @code{API.lib} or a GNAT-style
30737import library @code{libAPI.dll.a} or @code{libAPI.a} is available
30738with @code{API.dll} you can skip this section. You can also skip this
30739section if @code{API.dll} or @code{libAPI.dll} is built with GNU tools
30740as in this case it is possible to link directly against the
30741DLL. Otherwise read on.
30742
30743@geindex Definition file
30744@anchor{gnat_ugn/platform_specific_information the-definition-file}@anchor{283}
30745@subsubheading The Definition File
30746
30747
30748As previously mentioned, and unlike Unix systems, the list of symbols
30749that are exported from a DLL must be provided explicitly in Windows.
30750The main goal of a definition file is precisely that: list the symbols
30751exported by a DLL. A definition file (usually a file with a @cite{.def}
30752suffix) has the following structure:
30753
30754@quotation
30755
30756@example
30757[LIBRARY `name`]
30758[DESCRIPTION `string`]
30759EXPORTS
30760   `symbol1`
30761   `symbol2`
30762   ...
30763@end example
30764@end quotation
30765
30766
30767@table @asis
30768
30769@item @emph{LIBRARY `name`}
30770
30771This section, which is optional, gives the name of the DLL.
30772
30773@item @emph{DESCRIPTION `string`}
30774
30775This section, which is optional, gives a description string that will be
30776embedded in the import library.
30777
30778@item @emph{EXPORTS}
30779
30780This section gives the list of exported symbols (procedures, functions or
30781variables). For instance in the case of @code{API.dll} the @cite{EXPORTS}
30782section of @code{API.def} looks like:
30783
30784@example
30785EXPORTS
30786   some_var
30787   get
30788@end example
30789@end table
30790
30791Note that you must specify the correct suffix (@code{@@@emph{nn}})
30792(see @ref{277,,Windows Calling Conventions}) for a Stdcall
30793calling convention function in the exported symbols list.
30794
30795There can actually be other sections in a definition file, but these
30796sections are not relevant to the discussion at hand.
30797@anchor{gnat_ugn/platform_specific_information create-def-file-automatically}@anchor{289}
30798@subsubheading Creating a Definition File Automatically
30799
30800
30801You can automatically create the definition file @code{API.def}
30802(see @ref{283,,The Definition File}) from a DLL.
30803For that use the @cite{dlltool} program as follows:
30804
30805@quotation
30806
30807@example
30808$ dlltool API.dll -z API.def --export-all-symbols
30809@end example
30810
30811Note that if some routines in the DLL have the @cite{Stdcall} convention
30812(@ref{277,,Windows Calling Conventions}) with stripped @code{@@@emph{nn}}
30813suffix then you'll have to edit @code{api.def} to add it, and specify
30814@emph{-k} to @emph{gnatdll} when creating the import library.
30815
30816Here are some hints to find the right @code{@@@emph{nn}} suffix.
30817
30818
30819@itemize -
30820
30821@item
30822If you have the Microsoft import library (.lib), it is possible to get
30823the right symbols by using Microsoft @cite{dumpbin} tool (see the
30824corresponding Microsoft documentation for further details).
30825
30826@example
30827$ dumpbin /exports api.lib
30828@end example
30829
30830@item
30831If you have a message about a missing symbol at link time the compiler
30832tells you what symbol is expected. You just have to go back to the
30833definition file and add the right suffix.
30834@end itemize
30835@end quotation
30836@anchor{gnat_ugn/platform_specific_information gnat-style-import-library}@anchor{28a}
30837@subsubheading GNAT-Style Import Library
30838
30839
30840To create a static import library from @code{API.dll} with the GNAT tools
30841you should create the .def file, then use @cite{gnatdll} tool
30842(see @ref{28b,,Using gnatdll}) as follows:
30843
30844@quotation
30845
30846@example
30847$ gnatdll -e API.def -d API.dll
30848@end example
30849
30850@cite{gnatdll} takes as input a definition file @code{API.def} and the
30851name of the DLL containing the services listed in the definition file
30852@code{API.dll}. The name of the static import library generated is
30853computed from the name of the definition file as follows: if the
30854definition file name is @cite{xyz`}.def`, the import library name will
30855be @cite{lib`@w{`}xyz`}.a`. Note that in the previous example option
30856@emph{-e} could have been removed because the name of the definition
30857file (before the '@cite{.def}' suffix) is the same as the name of the
30858DLL (@ref{28b,,Using gnatdll} for more information about @cite{gnatdll}).
30859@end quotation
30860@anchor{gnat_ugn/platform_specific_information msvs-style-import-library}@anchor{28c}
30861@subsubheading Microsoft-Style Import Library
30862
30863
30864A Microsoft import library is needed only if you plan to make an
30865Ada DLL available to applications developed with Microsoft
30866tools (@ref{273,,Mixed-Language Programming on Windows}).
30867
30868To create a Microsoft-style import library for @code{API.dll} you
30869should create the .def file, then build the actual import library using
30870Microsoft's @cite{lib} utility:
30871
30872@quotation
30873
30874@example
30875$ lib -machine:IX86 -def:API.def -out:API.lib
30876@end example
30877
30878If you use the above command the definition file @code{API.def} must
30879contain a line giving the name of the DLL:
30880
30881@example
30882LIBRARY      "API"
30883@end example
30884
30885See the Microsoft documentation for further details about the usage of
30886@cite{lib}.
30887@end quotation
30888
30889@node Building DLLs with GNAT Project files,Building DLLs with GNAT,Using DLLs with GNAT,Mixed-Language Programming on Windows
30890@anchor{gnat_ugn/platform_specific_information id24}@anchor{28d}@anchor{gnat_ugn/platform_specific_information building-dlls-with-gnat-project-files}@anchor{276}
30891@subsubsection Building DLLs with GNAT Project files
30892
30893
30894@geindex DLLs
30895@geindex building
30896
30897There is nothing specific to Windows in the build process.
30898@ref{8a,,Library Projects}.
30899
30900Due to a system limitation, it is not possible under Windows to create threads
30901when inside the @cite{DllMain} routine which is used for auto-initialization
30902of shared libraries, so it is not possible to have library level tasks in SALs.
30903
30904@node Building DLLs with GNAT,Building DLLs with gnatdll,Building DLLs with GNAT Project files,Mixed-Language Programming on Windows
30905@anchor{gnat_ugn/platform_specific_information building-dlls-with-gnat}@anchor{28e}@anchor{gnat_ugn/platform_specific_information id25}@anchor{28f}
30906@subsubsection Building DLLs with GNAT
30907
30908
30909@geindex DLLs
30910@geindex building
30911
30912This section explain how to build DLLs using the GNAT built-in DLL
30913support. With the following procedure it is straight forward to build
30914and use DLLs with GNAT.
30915
30916
30917@itemize *
30918
30919@item
30920Building object files.
30921The first step is to build all objects files that are to be included
30922into the DLL. This is done by using the standard @emph{gnatmake} tool.
30923
30924@item
30925Building the DLL.
30926To build the DLL you must use @emph{gcc}'s @emph{-shared} and
30927@emph{-shared-libgcc} options. It is quite simple to use this method:
30928
30929@example
30930$ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o ...
30931@end example
30932
30933It is important to note that in this case all symbols found in the
30934object files are automatically exported. It is possible to restrict
30935the set of symbols to export by passing to @emph{gcc} a definition
30936file (see @ref{283,,The Definition File}).
30937For example:
30938
30939@example
30940$ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o ...
30941@end example
30942
30943If you use a definition file you must export the elaboration procedures
30944for every package that required one. Elaboration procedures are named
30945using the package name followed by "_E".
30946
30947@item
30948Preparing DLL to be used.
30949For the DLL to be used by client programs the bodies must be hidden
30950from it and the .ali set with read-only attribute. This is very important
30951otherwise GNAT will recompile all packages and will not actually use
30952the code in the DLL. For example:
30953
30954@example
30955$ mkdir apilib
30956$ copy *.ads *.ali api.dll apilib
30957$ attrib +R apilib\\*.ali
30958@end example
30959@end itemize
30960
30961At this point it is possible to use the DLL by directly linking
30962against it. Note that you must use the GNAT shared runtime when using
30963GNAT shared libraries. This is achieved by using @emph{-shared} binder's
30964option.
30965
30966@quotation
30967
30968@example
30969$ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
30970@end example
30971@end quotation
30972
30973@node Building DLLs with gnatdll,Ada DLLs and Finalization,Building DLLs with GNAT,Mixed-Language Programming on Windows
30974@anchor{gnat_ugn/platform_specific_information building-dlls-with-gnatdll}@anchor{290}@anchor{gnat_ugn/platform_specific_information id26}@anchor{291}
30975@subsubsection Building DLLs with gnatdll
30976
30977
30978@geindex DLLs
30979@geindex building
30980
30981Note that it is preferred to use GNAT Project files
30982(@ref{276,,Building DLLs with GNAT Project files}) or the built-in GNAT
30983DLL support (@ref{28e,,Building DLLs with GNAT}) or to build DLLs.
30984
30985This section explains how to build DLLs containing Ada code using
30986@cite{gnatdll}. These DLLs will be referred to as Ada DLLs in the
30987remainder of this section.
30988
30989The steps required to build an Ada DLL that is to be used by Ada as well as
30990non-Ada applications are as follows:
30991
30992
30993@itemize *
30994
30995@item
30996You need to mark each Ada @emph{entity} exported by the DLL with a @cite{C} or
30997@cite{Stdcall} calling convention to avoid any Ada name mangling for the
30998entities exported by the DLL
30999(see @ref{292,,Exporting Ada Entities}). You can
31000skip this step if you plan to use the Ada DLL only from Ada applications.
31001
31002@item
31003Your Ada code must export an initialization routine which calls the routine
31004@cite{adainit} generated by @emph{gnatbind} to perform the elaboration of
31005the Ada code in the DLL (@ref{293,,Ada DLLs and Elaboration}). The initialization
31006routine exported by the Ada DLL must be invoked by the clients of the DLL
31007to initialize the DLL.
31008
31009@item
31010When useful, the DLL should also export a finalization routine which calls
31011routine @cite{adafinal} generated by @emph{gnatbind} to perform the
31012finalization of the Ada code in the DLL (@ref{294,,Ada DLLs and Finalization}).
31013The finalization routine exported by the Ada DLL must be invoked by the
31014clients of the DLL when the DLL services are no further needed.
31015
31016@item
31017You must provide a spec for the services exported by the Ada DLL in each
31018of the programming languages to which you plan to make the DLL available.
31019
31020@item
31021You must provide a definition file listing the exported entities
31022(@ref{283,,The Definition File}).
31023
31024@item
31025Finally you must use @cite{gnatdll} to produce the DLL and the import
31026library (@ref{28b,,Using gnatdll}).
31027@end itemize
31028
31029Note that a relocatable DLL stripped using the @cite{strip}
31030binutils tool will not be relocatable anymore. To build a DLL without
31031debug information pass @cite{-largs -s} to @cite{gnatdll}. This
31032restriction does not apply to a DLL built using a Library Project.
31033See @ref{8a,,Library Projects}.
31034
31035@c Limitations_When_Using_Ada_DLLs_from Ada:
31036
31037@menu
31038* Limitations When Using Ada DLLs from Ada::
31039* Exporting Ada Entities::
31040* Ada DLLs and Elaboration::
31041
31042@end menu
31043
31044@node Limitations When Using Ada DLLs from Ada,Exporting Ada Entities,,Building DLLs with gnatdll
31045@anchor{gnat_ugn/platform_specific_information limitations-when-using-ada-dlls-from-ada}@anchor{295}
31046@subsubsection Limitations When Using Ada DLLs from Ada
31047
31048
31049When using Ada DLLs from Ada applications there is a limitation users
31050should be aware of. Because on Windows the GNAT run time is not in a DLL of
31051its own, each Ada DLL includes a part of the GNAT run time. Specifically,
31052each Ada DLL includes the services of the GNAT run time that are necessary
31053to the Ada code inside the DLL. As a result, when an Ada program uses an
31054Ada DLL there are two independent GNAT run times: one in the Ada DLL and
31055one in the main program.
31056
31057It is therefore not possible to exchange GNAT run-time objects between the
31058Ada DLL and the main Ada program. Example of GNAT run-time objects are file
31059handles (e.g., @cite{Text_IO.File_Type}), tasks types, protected objects
31060types, etc.
31061
31062It is completely safe to exchange plain elementary, array or record types,
31063Windows object handles, etc.
31064
31065@node Exporting Ada Entities,Ada DLLs and Elaboration,Limitations When Using Ada DLLs from Ada,Building DLLs with gnatdll
31066@anchor{gnat_ugn/platform_specific_information exporting-ada-entities}@anchor{292}@anchor{gnat_ugn/platform_specific_information id27}@anchor{296}
31067@subsubsection Exporting Ada Entities
31068
31069
31070@geindex Export table
31071
31072Building a DLL is a way to encapsulate a set of services usable from any
31073application. As a result, the Ada entities exported by a DLL should be
31074exported with the @cite{C} or @cite{Stdcall} calling conventions to avoid
31075any Ada name mangling. As an example here is an Ada package
31076@cite{API}, spec and body, exporting two procedures, a function, and a
31077variable:
31078
31079@quotation
31080
31081@example
31082with Interfaces.C; use Interfaces;
31083package API is
31084   Count : C.int := 0;
31085   function Factorial (Val : C.int) return C.int;
31086
31087   procedure Initialize_API;
31088   procedure Finalize_API;
31089   --  Initialization & Finalization routines. More in the next section.
31090private
31091   pragma Export (C, Initialize_API);
31092   pragma Export (C, Finalize_API);
31093   pragma Export (C, Count);
31094   pragma Export (C, Factorial);
31095end API;
31096@end example
31097
31098@example
31099package body API is
31100   function Factorial (Val : C.int) return C.int is
31101      Fact : C.int := 1;
31102   begin
31103      Count := Count + 1;
31104      for K in 1 .. Val loop
31105         Fact := Fact * K;
31106      end loop;
31107      return Fact;
31108   end Factorial;
31109
31110   procedure Initialize_API is
31111      procedure Adainit;
31112      pragma Import (C, Adainit);
31113   begin
31114      Adainit;
31115   end Initialize_API;
31116
31117   procedure Finalize_API is
31118      procedure Adafinal;
31119      pragma Import (C, Adafinal);
31120   begin
31121      Adafinal;
31122   end Finalize_API;
31123end API;
31124@end example
31125@end quotation
31126
31127If the Ada DLL you are building will only be used by Ada applications
31128you do not have to export Ada entities with a @cite{C} or @cite{Stdcall}
31129convention. As an example, the previous package could be written as
31130follows:
31131
31132@quotation
31133
31134@example
31135package API is
31136   Count : Integer := 0;
31137   function Factorial (Val : Integer) return Integer;
31138
31139   procedure Initialize_API;
31140   procedure Finalize_API;
31141   --  Initialization and Finalization routines.
31142end API;
31143@end example
31144
31145@example
31146package body API is
31147   function Factorial (Val : Integer) return Integer is
31148      Fact : Integer := 1;
31149   begin
31150      Count := Count + 1;
31151      for K in 1 .. Val loop
31152         Fact := Fact * K;
31153      end loop;
31154      return Fact;
31155   end Factorial;
31156
31157   ...
31158   --  The remainder of this package body is unchanged.
31159end API;
31160@end example
31161@end quotation
31162
31163Note that if you do not export the Ada entities with a @cite{C} or
31164@cite{Stdcall} convention you will have to provide the mangled Ada names
31165in the definition file of the Ada DLL
31166(@ref{297,,Creating the Definition File}).
31167
31168@node Ada DLLs and Elaboration,,Exporting Ada Entities,Building DLLs with gnatdll
31169@anchor{gnat_ugn/platform_specific_information ada-dlls-and-elaboration}@anchor{293}@anchor{gnat_ugn/platform_specific_information id28}@anchor{298}
31170@subsubsection Ada DLLs and Elaboration
31171
31172
31173@geindex DLLs and elaboration
31174
31175The DLL that you are building contains your Ada code as well as all the
31176routines in the Ada library that are needed by it. The first thing a
31177user of your DLL must do is elaborate the Ada code
31178(@ref{11,,Elaboration Order Handling in GNAT}).
31179
31180To achieve this you must export an initialization routine
31181(@cite{Initialize_API} in the previous example), which must be invoked
31182before using any of the DLL services. This elaboration routine must call
31183the Ada elaboration routine @cite{adainit} generated by the GNAT binder
31184(@ref{ba,,Binding with Non-Ada Main Programs}). See the body of
31185@cite{Initialize_Api} for an example. Note that the GNAT binder is
31186automatically invoked during the DLL build process by the @cite{gnatdll}
31187tool (@ref{28b,,Using gnatdll}).
31188
31189When a DLL is loaded, Windows systematically invokes a routine called
31190@cite{DllMain}. It would therefore be possible to call @cite{adainit}
31191directly from @cite{DllMain} without having to provide an explicit
31192initialization routine. Unfortunately, it is not possible to call
31193@cite{adainit} from the @cite{DllMain} if your program has library level
31194tasks because access to the @cite{DllMain} entry point is serialized by
31195the system (that is, only a single thread can execute 'through' it at a
31196time), which means that the GNAT run time will deadlock waiting for the
31197newly created task to complete its initialization.
31198
31199@node Ada DLLs and Finalization,Creating a Spec for Ada DLLs,Building DLLs with gnatdll,Mixed-Language Programming on Windows
31200@anchor{gnat_ugn/platform_specific_information id29}@anchor{299}@anchor{gnat_ugn/platform_specific_information ada-dlls-and-finalization}@anchor{294}
31201@subsubsection Ada DLLs and Finalization
31202
31203
31204@geindex DLLs and finalization
31205
31206When the services of an Ada DLL are no longer needed, the client code should
31207invoke the DLL finalization routine, if available. The DLL finalization
31208routine is in charge of releasing all resources acquired by the DLL. In the
31209case of the Ada code contained in the DLL, this is achieved by calling
31210routine @cite{adafinal} generated by the GNAT binder
31211(@ref{ba,,Binding with Non-Ada Main Programs}).
31212See the body of @cite{Finalize_Api} for an
31213example. As already pointed out the GNAT binder is automatically invoked
31214during the DLL build process by the @cite{gnatdll} tool
31215(@ref{28b,,Using gnatdll}).
31216
31217@node Creating a Spec for Ada DLLs,GNAT and Windows Resources,Ada DLLs and Finalization,Mixed-Language Programming on Windows
31218@anchor{gnat_ugn/platform_specific_information id30}@anchor{29a}@anchor{gnat_ugn/platform_specific_information creating-a-spec-for-ada-dlls}@anchor{29b}
31219@subsubsection Creating a Spec for Ada DLLs
31220
31221
31222To use the services exported by the Ada DLL from another programming
31223language (e.g., C), you have to translate the specs of the exported Ada
31224entities in that language. For instance in the case of @cite{API.dll},
31225the corresponding C header file could look like:
31226
31227@quotation
31228
31229@example
31230extern int *_imp__count;
31231#define count (*_imp__count)
31232int factorial (int);
31233@end example
31234@end quotation
31235
31236It is important to understand that when building an Ada DLL to be used by
31237other Ada applications, you need two different specs for the packages
31238contained in the DLL: one for building the DLL and the other for using
31239the DLL. This is because the @cite{DLL} calling convention is needed to
31240use a variable defined in a DLL, but when building the DLL, the variable
31241must have either the @cite{Ada} or @cite{C} calling convention. As an
31242example consider a DLL comprising the following package @cite{API}:
31243
31244@quotation
31245
31246@example
31247package API is
31248   Count : Integer := 0;
31249   ...
31250   --  Remainder of the package omitted.
31251end API;
31252@end example
31253@end quotation
31254
31255After producing a DLL containing package @cite{API}, the spec that
31256must be used to import @cite{API.Count} from Ada code outside of the
31257DLL is:
31258
31259@quotation
31260
31261@example
31262package API is
31263   Count : Integer;
31264   pragma Import (DLL, Count);
31265end API;
31266@end example
31267@end quotation
31268
31269@menu
31270* Creating the Definition File::
31271* Using gnatdll::
31272
31273@end menu
31274
31275@node Creating the Definition File,Using gnatdll,,Creating a Spec for Ada DLLs
31276@anchor{gnat_ugn/platform_specific_information creating-the-definition-file}@anchor{297}@anchor{gnat_ugn/platform_specific_information id31}@anchor{29c}
31277@subsubsection Creating the Definition File
31278
31279
31280The definition file is the last file needed to build the DLL. It lists
31281the exported symbols. As an example, the definition file for a DLL
31282containing only package @cite{API} (where all the entities are exported
31283with a @cite{C} calling convention) is:
31284
31285@quotation
31286
31287@example
31288EXPORTS
31289    count
31290    factorial
31291    finalize_api
31292    initialize_api
31293@end example
31294@end quotation
31295
31296If the @cite{C} calling convention is missing from package @cite{API},
31297then the definition file contains the mangled Ada names of the above
31298entities, which in this case are:
31299
31300@quotation
31301
31302@example
31303EXPORTS
31304    api__count
31305    api__factorial
31306    api__finalize_api
31307    api__initialize_api
31308@end example
31309@end quotation
31310
31311@node Using gnatdll,,Creating the Definition File,Creating a Spec for Ada DLLs
31312@anchor{gnat_ugn/platform_specific_information using-gnatdll}@anchor{28b}@anchor{gnat_ugn/platform_specific_information id32}@anchor{29d}
31313@subsubsection Using @cite{gnatdll}
31314
31315
31316@geindex gnatdll
31317
31318@cite{gnatdll} is a tool to automate the DLL build process once all the Ada
31319and non-Ada sources that make up your DLL have been compiled.
31320@cite{gnatdll} is actually in charge of two distinct tasks: build the
31321static import library for the DLL and the actual DLL. The form of the
31322@cite{gnatdll} command is
31323
31324@quotation
31325
31326@example
31327$ gnatdll [`switches`] `list-of-files` [-largs `opts`]
31328@end example
31329@end quotation
31330
31331where @cite{list-of-files} is a list of ALI and object files. The object
31332file list must be the exact list of objects corresponding to the non-Ada
31333sources whose services are to be included in the DLL. The ALI file list
31334must be the exact list of ALI files for the corresponding Ada sources
31335whose services are to be included in the DLL. If @cite{list-of-files} is
31336missing, only the static import library is generated.
31337
31338You may specify any of the following switches to @cite{gnatdll}:
31339
31340@quotation
31341
31342@geindex -a (gnatdll)
31343@end quotation
31344
31345
31346@table @asis
31347
31348@item @code{-a[@emph{address}]}
31349
31350Build a non-relocatable DLL at @cite{address}. If @cite{address} is not
31351specified the default address @cite{0x11000000} will be used. By default,
31352when this switch is missing, @cite{gnatdll} builds relocatable DLL. We
31353advise the reader to build relocatable DLL.
31354
31355@geindex -b (gnatdll)
31356
31357@item @code{-b @emph{address}}
31358
31359Set the relocatable DLL base address. By default the address is
31360@cite{0x11000000}.
31361
31362@geindex -bargs (gnatdll)
31363
31364@item @code{-bargs @emph{opts}}
31365
31366Binder options. Pass @cite{opts} to the binder.
31367
31368@geindex -d (gnatdll)
31369
31370@item @code{-d @emph{dllfile}}
31371
31372@cite{dllfile} is the name of the DLL. This switch must be present for
31373@cite{gnatdll} to do anything. The name of the generated import library is
31374obtained algorithmically from @cite{dllfile} as shown in the following
31375example: if @cite{dllfile} is @cite{xyz.dll}, the import library name is
31376@cite{libxyz.dll.a}. The name of the definition file to use (if not specified
31377by option @emph{-e}) is obtained algorithmically from @cite{dllfile}
31378as shown in the following example:
31379if @cite{dllfile} is @cite{xyz.dll}, the definition
31380file used is @cite{xyz.def}.
31381
31382@geindex -e (gnatdll)
31383
31384@item @code{-e @emph{deffile}}
31385
31386@cite{deffile} is the name of the definition file.
31387
31388@geindex -g (gnatdll)
31389
31390@item @code{-g}
31391
31392Generate debugging information. This information is stored in the object
31393file and copied from there to the final DLL file by the linker,
31394where it can be read by the debugger. You must use the
31395@emph{-g} switch if you plan on using the debugger or the symbolic
31396stack traceback.
31397
31398@geindex -h (gnatdll)
31399
31400@item @code{-h}
31401
31402Help mode. Displays @cite{gnatdll} switch usage information.
31403
31404@geindex -I (gnatdll)
31405
31406@item @code{-I@emph{dir}}
31407
31408Direct @cite{gnatdll} to search the @cite{dir} directory for source and
31409object files needed to build the DLL.
31410(@ref{8e,,Search Paths and the Run-Time Library (RTL)}).
31411
31412@geindex -k (gnatdll)
31413
31414@item @code{-k}
31415
31416Removes the @code{@@@emph{nn}} suffix from the import library's exported
31417names, but keeps them for the link names. You must specify this
31418option if you want to use a @cite{Stdcall} function in a DLL for which
31419the @code{@@@emph{nn}} suffix has been removed. This is the case for most
31420of the Windows NT DLL for example. This option has no effect when
31421@emph{-n} option is specified.
31422
31423@geindex -l (gnatdll)
31424
31425@item @code{-l @emph{file}}
31426
31427The list of ALI and object files used to build the DLL are listed in
31428@cite{file}, instead of being given in the command line. Each line in
31429@cite{file} contains the name of an ALI or object file.
31430
31431@geindex -n (gnatdll)
31432
31433@item @code{-n}
31434
31435No Import. Do not create the import library.
31436
31437@geindex -q (gnatdll)
31438
31439@item @code{-q}
31440
31441Quiet mode. Do not display unnecessary messages.
31442
31443@geindex -v (gnatdll)
31444
31445@item @code{-v}
31446
31447Verbose mode. Display extra information.
31448
31449@geindex -largs (gnatdll)
31450
31451@item @code{-largs @emph{opts}}
31452
31453Linker options. Pass @cite{opts} to the linker.
31454@end table
31455
31456@subsubheading @cite{gnatdll} Example
31457
31458
31459As an example the command to build a relocatable DLL from @code{api.adb}
31460once @code{api.adb} has been compiled and @code{api.def} created is
31461
31462@quotation
31463
31464@example
31465$ gnatdll -d api.dll api.ali
31466@end example
31467@end quotation
31468
31469The above command creates two files: @code{libapi.dll.a} (the import
31470library) and @code{api.dll} (the actual DLL). If you want to create
31471only the DLL, just type:
31472
31473@quotation
31474
31475@example
31476$ gnatdll -d api.dll -n api.ali
31477@end example
31478@end quotation
31479
31480Alternatively if you want to create just the import library, type:
31481
31482@quotation
31483
31484@example
31485$ gnatdll -d api.dll
31486@end example
31487@end quotation
31488
31489@subsubheading @cite{gnatdll} behind the Scenes
31490
31491
31492This section details the steps involved in creating a DLL. @cite{gnatdll}
31493does these steps for you. Unless you are interested in understanding what
31494goes on behind the scenes, you should skip this section.
31495
31496We use the previous example of a DLL containing the Ada package @cite{API},
31497to illustrate the steps necessary to build a DLL. The starting point is a
31498set of objects that will make up the DLL and the corresponding ALI
31499files. In the case of this example this means that @code{api.o} and
31500@code{api.ali} are available. To build a relocatable DLL, @cite{gnatdll} does
31501the following:
31502
31503
31504@itemize *
31505
31506@item
31507@cite{gnatdll} builds the base file (@code{api.base}). A base file gives
31508the information necessary to generate relocation information for the
31509DLL.
31510
31511@example
31512$ gnatbind -n api
31513$ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
31514@end example
31515
31516In addition to the base file, the @emph{gnatlink} command generates an
31517output file @code{api.jnk} which can be discarded. The @emph{-mdll} switch
31518asks @emph{gnatlink} to generate the routines @cite{DllMain} and
31519@cite{DllMainCRTStartup} that are called by the Windows loader when the DLL
31520is loaded into memory.
31521
31522@item
31523@cite{gnatdll} uses @cite{dlltool} (see @ref{29e,,Using dlltool}) to build the
31524export table (@code{api.exp}). The export table contains the relocation
31525information in a form which can be used during the final link to ensure
31526that the Windows loader is able to place the DLL anywhere in memory.
31527
31528@example
31529$ dlltool --dllname api.dll --def api.def --base-file api.base \\
31530          --output-exp api.exp
31531@end example
31532
31533@item
31534@cite{gnatdll} builds the base file using the new export table. Note that
31535@emph{gnatbind} must be called once again since the binder generated file
31536has been deleted during the previous call to @emph{gnatlink}.
31537
31538@example
31539$ gnatbind -n api
31540$ gnatlink api -o api.jnk api.exp -mdll
31541      -Wl,--base-file,api.base
31542@end example
31543
31544@item
31545@cite{gnatdll} builds the new export table using the new base file and
31546generates the DLL import library @code{libAPI.dll.a}.
31547
31548@example
31549$ dlltool --dllname api.dll --def api.def --base-file api.base \\
31550          --output-exp api.exp --output-lib libAPI.a
31551@end example
31552
31553@item
31554Finally @cite{gnatdll} builds the relocatable DLL using the final export
31555table.
31556
31557@example
31558$ gnatbind -n api
31559$ gnatlink api api.exp -o api.dll -mdll
31560@end example
31561@end itemize
31562@anchor{gnat_ugn/platform_specific_information using-dlltool}@anchor{29e}
31563@subsubheading Using @cite{dlltool}
31564
31565
31566@cite{dlltool} is the low-level tool used by @cite{gnatdll} to build
31567DLLs and static import libraries. This section summarizes the most
31568common @cite{dlltool} switches. The form of the @cite{dlltool} command
31569is
31570
31571@quotation
31572
31573@example
31574$ dlltool [`switches`]
31575@end example
31576@end quotation
31577
31578@cite{dlltool} switches include:
31579
31580@geindex --base-file (dlltool)
31581
31582
31583@table @asis
31584
31585@item @code{--base-file @emph{basefile}}
31586
31587Read the base file @cite{basefile} generated by the linker. This switch
31588is used to create a relocatable DLL.
31589@end table
31590
31591@geindex --def (dlltool)
31592
31593
31594@table @asis
31595
31596@item @code{--def @emph{deffile}}
31597
31598Read the definition file.
31599@end table
31600
31601@geindex --dllname (dlltool)
31602
31603
31604@table @asis
31605
31606@item @code{--dllname @emph{name}}
31607
31608Gives the name of the DLL. This switch is used to embed the name of the
31609DLL in the static import library generated by @cite{dlltool} with switch
31610@emph{--output-lib}.
31611@end table
31612
31613@geindex -k (dlltool)
31614
31615
31616@table @asis
31617
31618@item @code{-k}
31619
31620Kill @code{@@@emph{nn}} from exported names
31621(@ref{277,,Windows Calling Conventions}
31622for a discussion about @cite{Stdcall}-style symbols.
31623@end table
31624
31625@geindex --help (dlltool)
31626
31627
31628@table @asis
31629
31630@item @code{--help}
31631
31632Prints the @cite{dlltool} switches with a concise description.
31633@end table
31634
31635@geindex --output-exp (dlltool)
31636
31637
31638@table @asis
31639
31640@item @code{--output-exp @emph{exportfile}}
31641
31642Generate an export file @cite{exportfile}. The export file contains the
31643export table (list of symbols in the DLL) and is used to create the DLL.
31644@end table
31645
31646@geindex --output-lib (dlltool)
31647
31648
31649@table @asis
31650
31651@item @code{--output-lib @emph{libfile}}
31652
31653Generate a static import library @cite{libfile}.
31654@end table
31655
31656@geindex -v (dlltool)
31657
31658
31659@table @asis
31660
31661@item @code{-v}
31662
31663Verbose mode.
31664@end table
31665
31666@geindex --as (dlltool)
31667
31668
31669@table @asis
31670
31671@item @code{--as @emph{assembler-name}}
31672
31673Use @cite{assembler-name} as the assembler. The default is @cite{as}.
31674@end table
31675
31676@node GNAT and Windows Resources,Using GNAT DLLs from Microsoft Visual Studio Applications,Creating a Spec for Ada DLLs,Mixed-Language Programming on Windows
31677@anchor{gnat_ugn/platform_specific_information gnat-and-windows-resources}@anchor{29f}@anchor{gnat_ugn/platform_specific_information id33}@anchor{2a0}
31678@subsubsection GNAT and Windows Resources
31679
31680
31681@geindex Resources
31682@geindex windows
31683
31684Resources are an easy way to add Windows specific objects to your
31685application. The objects that can be added as resources include:
31686
31687
31688@itemize *
31689
31690@item
31691menus
31692
31693@item
31694accelerators
31695
31696@item
31697dialog boxes
31698
31699@item
31700string tables
31701
31702@item
31703bitmaps
31704
31705@item
31706cursors
31707
31708@item
31709icons
31710
31711@item
31712fonts
31713
31714@item
31715version information
31716@end itemize
31717
31718For example, a version information resource can be defined as follow and
31719embedded into an executable or DLL:
31720
31721A version information resource can be used to embed information into an
31722executable or a DLL. These information can be viewed using the file properties
31723from the Windows Explorer. Here is an example of a version information
31724resource:
31725
31726@quotation
31727
31728@example
317291 VERSIONINFO
31730FILEVERSION     1,0,0,0
31731PRODUCTVERSION  1,0,0,0
31732BEGIN
31733  BLOCK "StringFileInfo"
31734  BEGIN
31735    BLOCK "080904E4"
31736    BEGIN
31737      VALUE "CompanyName", "My Company Name"
31738      VALUE "FileDescription", "My application"
31739      VALUE "FileVersion", "1.0"
31740      VALUE "InternalName", "my_app"
31741      VALUE "LegalCopyright", "My Name"
31742      VALUE "OriginalFilename", "my_app.exe"
31743      VALUE "ProductName", "My App"
31744      VALUE "ProductVersion", "1.0"
31745    END
31746  END
31747
31748  BLOCK "VarFileInfo"
31749  BEGIN
31750    VALUE "Translation", 0x809, 1252
31751  END
31752END
31753@end example
31754@end quotation
31755
31756The value @cite{0809} (langID) is for the U.K English language and
31757@cite{04E4} (charsetID), which is equal to @cite{1252} decimal, for
31758multilingual.
31759
31760This section explains how to build, compile and use resources. Note that this
31761section does not cover all resource objects, for a complete description see
31762the corresponding Microsoft documentation.
31763
31764@menu
31765* Building Resources::
31766* Compiling Resources::
31767* Using Resources::
31768
31769@end menu
31770
31771@node Building Resources,Compiling Resources,,GNAT and Windows Resources
31772@anchor{gnat_ugn/platform_specific_information building-resources}@anchor{2a1}@anchor{gnat_ugn/platform_specific_information id34}@anchor{2a2}
31773@subsubsection Building Resources
31774
31775
31776@geindex Resources
31777@geindex building
31778
31779A resource file is an ASCII file. By convention resource files have an
31780@code{.rc} extension.
31781The easiest way to build a resource file is to use Microsoft tools
31782such as @cite{imagedit.exe} to build bitmaps, icons and cursors and
31783@cite{dlgedit.exe} to build dialogs.
31784It is always possible to build an @code{.rc} file yourself by writing a
31785resource script.
31786
31787It is not our objective to explain how to write a resource file. A
31788complete description of the resource script language can be found in the
31789Microsoft documentation.
31790
31791@node Compiling Resources,Using Resources,Building Resources,GNAT and Windows Resources
31792@anchor{gnat_ugn/platform_specific_information compiling-resources}@anchor{2a3}@anchor{gnat_ugn/platform_specific_information id35}@anchor{2a4}
31793@subsubsection Compiling Resources
31794
31795
31796@geindex rc
31797
31798@geindex windres
31799
31800@geindex Resources
31801@geindex compiling
31802
31803This section describes how to build a GNAT-compatible (COFF) object file
31804containing the resources. This is done using the Resource Compiler
31805@cite{windres} as follows:
31806
31807@quotation
31808
31809@example
31810$ windres -i myres.rc -o myres.o
31811@end example
31812@end quotation
31813
31814By default @cite{windres} will run @emph{gcc} to preprocess the @code{.rc}
31815file. You can specify an alternate preprocessor (usually named
31816@code{cpp.exe}) using the @cite{windres} @emph{--preprocessor}
31817parameter. A list of all possible options may be obtained by entering
31818the command @cite{windres} @emph{--help}.
31819
31820It is also possible to use the Microsoft resource compiler @cite{rc.exe}
31821to produce a @code{.res} file (binary resource file). See the
31822corresponding Microsoft documentation for further details. In this case
31823you need to use @cite{windres} to translate the @code{.res} file to a
31824GNAT-compatible object file as follows:
31825
31826@quotation
31827
31828@example
31829$ windres -i myres.res -o myres.o
31830@end example
31831@end quotation
31832
31833@node Using Resources,,Compiling Resources,GNAT and Windows Resources
31834@anchor{gnat_ugn/platform_specific_information id36}@anchor{2a5}@anchor{gnat_ugn/platform_specific_information using-resources}@anchor{2a6}
31835@subsubsection Using Resources
31836
31837
31838@geindex Resources
31839@geindex using
31840
31841To include the resource file in your program just add the
31842GNAT-compatible object file for the resource(s) to the linker
31843arguments. With @emph{gnatmake} this is done by using the @emph{-largs}
31844option:
31845
31846@quotation
31847
31848@example
31849$ gnatmake myprog -largs myres.o
31850@end example
31851@end quotation
31852
31853@node Using GNAT DLLs from Microsoft Visual Studio Applications,Debugging a DLL,GNAT and Windows Resources,Mixed-Language Programming on Windows
31854@anchor{gnat_ugn/platform_specific_information using-gnat-dll-from-msvs}@anchor{2a7}@anchor{gnat_ugn/platform_specific_information using-gnat-dlls-from-microsoft-visual-studio-applications}@anchor{2a8}
31855@subsubsection Using GNAT DLLs from Microsoft Visual Studio Applications
31856
31857
31858@geindex Microsoft Visual Studio
31859@geindex use with GNAT DLLs
31860
31861This section describes a common case of mixed GNAT/Microsoft Visual Studio
31862application development, where the main program is developed using MSVS, and
31863is linked with a DLL developed using GNAT. Such a mixed application should
31864be developed following the general guidelines outlined above; below is the
31865cookbook-style sequence of steps to follow:
31866
31867
31868@enumerate
31869
31870@item
31871First develop and build the GNAT shared library using a library project
31872(let's assume the project is @cite{mylib.gpr}, producing the library @cite{libmylib.dll}):
31873@end enumerate
31874
31875@quotation
31876
31877@example
31878$ gprbuild -p mylib.gpr
31879@end example
31880@end quotation
31881
31882
31883@enumerate 2
31884
31885@item
31886Produce a .def file for the symbols you need to interface with, either by
31887hand or automatically with possibly some manual adjustments
31888(see @ref{289,,Creating Definition File Automatically}):
31889@end enumerate
31890
31891@quotation
31892
31893@example
31894$ dlltool libmylib.dll -z libmylib.def --export-all-symbols
31895@end example
31896@end quotation
31897
31898
31899@enumerate 3
31900
31901@item
31902Make sure that MSVS command-line tools are accessible on the path.
31903
31904@item
31905Create the Microsoft-style import library (see @ref{28c,,MSVS-Style Import Library}):
31906@end enumerate
31907
31908@quotation
31909
31910@example
31911$ lib -machine:IX86 -def:libmylib.def -out:libmylib.lib
31912@end example
31913@end quotation
31914
31915If you are using a 64-bit toolchain, the above becomes...
31916
31917@quotation
31918
31919@example
31920$ lib -machine:X64 -def:libmylib.def -out:libmylib.lib
31921@end example
31922@end quotation
31923
31924
31925@enumerate 5
31926
31927@item
31928Build the C main
31929@end enumerate
31930
31931@quotation
31932
31933@example
31934$ cl /O2 /MD main.c libmylib.lib
31935@end example
31936@end quotation
31937
31938
31939@enumerate 6
31940
31941@item
31942Before running the executable, make sure you have set the PATH to the DLL,
31943or copy the DLL into into the directory containing the .exe.
31944@end enumerate
31945
31946@node Debugging a DLL,Setting Stack Size from gnatlink,Using GNAT DLLs from Microsoft Visual Studio Applications,Mixed-Language Programming on Windows
31947@anchor{gnat_ugn/platform_specific_information id37}@anchor{2a9}@anchor{gnat_ugn/platform_specific_information debugging-a-dll}@anchor{2aa}
31948@subsubsection Debugging a DLL
31949
31950
31951@geindex DLL debugging
31952
31953Debugging a DLL is similar to debugging a standard program. But
31954we have to deal with two different executable parts: the DLL and the
31955program that uses it. We have the following four possibilities:
31956
31957
31958@itemize *
31959
31960@item
31961The program and the DLL are built with @cite{GCC/GNAT}.
31962
31963@item
31964The program is built with foreign tools and the DLL is built with
31965@cite{GCC/GNAT}.
31966
31967@item
31968The program is built with @cite{GCC/GNAT} and the DLL is built with
31969foreign tools.
31970@end itemize
31971
31972In this section we address only cases one and two above.
31973There is no point in trying to debug
31974a DLL with @cite{GNU/GDB}, if there is no GDB-compatible debugging
31975information in it. To do so you must use a debugger compatible with the
31976tools suite used to build the DLL.
31977
31978@menu
31979* Program and DLL Both Built with GCC/GNAT::
31980* Program Built with Foreign Tools and DLL Built with GCC/GNAT::
31981
31982@end menu
31983
31984@node Program and DLL Both Built with GCC/GNAT,Program Built with Foreign Tools and DLL Built with GCC/GNAT,,Debugging a DLL
31985@anchor{gnat_ugn/platform_specific_information program-and-dll-both-built-with-gcc-gnat}@anchor{2ab}@anchor{gnat_ugn/platform_specific_information id38}@anchor{2ac}
31986@subsubsection Program and DLL Both Built with GCC/GNAT
31987
31988
31989This is the simplest case. Both the DLL and the program have @cite{GDB}
31990compatible debugging information. It is then possible to break anywhere in
31991the process. Let's suppose here that the main procedure is named
31992@cite{ada_main} and that in the DLL there is an entry point named
31993@cite{ada_dll}.
31994
31995The DLL (@ref{282,,Introduction to Dynamic Link Libraries (DLLs)}) and
31996program must have been built with the debugging information (see GNAT -g
31997switch). Here are the step-by-step instructions for debugging it:
31998
31999
32000@itemize *
32001
32002@item
32003Launch @cite{GDB} on the main program.
32004
32005@example
32006$ gdb -nw ada_main
32007@end example
32008
32009@item
32010Start the program and stop at the beginning of the main procedure
32011
32012@example
32013(gdb) start
32014@end example
32015
32016This step is required to be able to set a breakpoint inside the DLL. As long
32017as the program is not run, the DLL is not loaded. This has the
32018consequence that the DLL debugging information is also not loaded, so it is not
32019possible to set a breakpoint in the DLL.
32020
32021@item
32022Set a breakpoint inside the DLL
32023
32024@example
32025(gdb) break ada_dll
32026(gdb) cont
32027@end example
32028@end itemize
32029
32030At this stage a breakpoint is set inside the DLL. From there on
32031you can use the standard approach to debug the whole program
32032(@ref{26,,Running and Debugging Ada Programs}).
32033
32034@node Program Built with Foreign Tools and DLL Built with GCC/GNAT,,Program and DLL Both Built with GCC/GNAT,Debugging a DLL
32035@anchor{gnat_ugn/platform_specific_information program-built-with-foreign-tools-and-dll-built-with-gcc-gnat}@anchor{2ad}@anchor{gnat_ugn/platform_specific_information id39}@anchor{2ae}
32036@subsubsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
32037
32038
32039In this case things are slightly more complex because it is not possible to
32040start the main program and then break at the beginning to load the DLL and the
32041associated DLL debugging information. It is not possible to break at the
32042beginning of the program because there is no @cite{GDB} debugging information,
32043and therefore there is no direct way of getting initial control. This
32044section addresses this issue by describing some methods that can be used
32045to break somewhere in the DLL to debug it.
32046
32047First suppose that the main procedure is named @cite{main} (this is for
32048example some C code built with Microsoft Visual C) and that there is a
32049DLL named @cite{test.dll} containing an Ada entry point named
32050@cite{ada_dll}.
32051
32052The DLL (see @ref{282,,Introduction to Dynamic Link Libraries (DLLs)}) must have
32053been built with debugging information (see GNAT @cite{-g} option).
32054
32055@subsubheading Debugging the DLL Directly
32056
32057
32058
32059@itemize *
32060
32061@item
32062Find out the executable starting address
32063
32064@example
32065$ objdump --file-header main.exe
32066@end example
32067
32068The starting address is reported on the last line. For example:
32069
32070@example
32071main.exe:     file format pei-i386
32072architecture: i386, flags 0x0000010a:
32073EXEC_P, HAS_DEBUG, D_PAGED
32074start address 0x00401010
32075@end example
32076
32077@item
32078Launch the debugger on the executable.
32079
32080@example
32081$ gdb main.exe
32082@end example
32083
32084@item
32085Set a breakpoint at the starting address, and launch the program.
32086
32087@example
32088$ (gdb) break *0x00401010
32089$ (gdb) run
32090@end example
32091
32092The program will stop at the given address.
32093
32094@item
32095Set a breakpoint on a DLL subroutine.
32096
32097@example
32098(gdb) break ada_dll.adb:45
32099@end example
32100
32101Or if you want to break using a symbol on the DLL, you need first to
32102select the Ada language (language used by the DLL).
32103
32104@example
32105(gdb) set language ada
32106(gdb) break ada_dll
32107@end example
32108
32109@item
32110Continue the program.
32111
32112@example
32113(gdb) cont
32114@end example
32115
32116This will run the program until it reaches the breakpoint that has been
32117set. From that point you can use the standard way to debug a program
32118as described in (@ref{26,,Running and Debugging Ada Programs}).
32119@end itemize
32120
32121It is also possible to debug the DLL by attaching to a running process.
32122
32123@subsubheading Attaching to a Running Process
32124
32125
32126@geindex DLL debugging
32127@geindex attach to process
32128
32129With @cite{GDB} it is always possible to debug a running process by
32130attaching to it. It is possible to debug a DLL this way. The limitation
32131of this approach is that the DLL must run long enough to perform the
32132attach operation. It may be useful for instance to insert a time wasting
32133loop in the code of the DLL to meet this criterion.
32134
32135
32136@itemize *
32137
32138@item
32139Launch the main program @code{main.exe}.
32140
32141@example
32142$ main
32143@end example
32144
32145@item
32146Use the Windows @emph{Task Manager} to find the process ID. Let's say
32147that the process PID for @code{main.exe} is 208.
32148
32149@item
32150Launch gdb.
32151
32152@example
32153$ gdb
32154@end example
32155
32156@item
32157Attach to the running process to be debugged.
32158
32159@example
32160(gdb) attach 208
32161@end example
32162
32163@item
32164Load the process debugging information.
32165
32166@example
32167(gdb) symbol-file main.exe
32168@end example
32169
32170@item
32171Break somewhere in the DLL.
32172
32173@example
32174(gdb) break ada_dll
32175@end example
32176
32177@item
32178Continue process execution.
32179
32180@example
32181(gdb) cont
32182@end example
32183@end itemize
32184
32185This last step will resume the process execution, and stop at
32186the breakpoint we have set. From there you can use the standard
32187approach to debug a program as described in
32188@ref{26,,Running and Debugging Ada Programs}.
32189
32190@node Setting Stack Size from gnatlink,Setting Heap Size from gnatlink,Debugging a DLL,Mixed-Language Programming on Windows
32191@anchor{gnat_ugn/platform_specific_information setting-stack-size-from-gnatlink}@anchor{13d}@anchor{gnat_ugn/platform_specific_information id40}@anchor{2af}
32192@subsubsection Setting Stack Size from @emph{gnatlink}
32193
32194
32195It is possible to specify the program stack size at link time. On modern
32196versions of Windows, starting with XP, this is mostly useful to set the size of
32197the main stack (environment task). The other task stacks are set with pragma
32198Storage_Size or with the @emph{gnatbind -d} command.
32199
32200Since older versions of Windows (2000, NT4, etc.) do not allow setting the
32201reserve size of individual tasks, the link-time stack size applies to all
32202tasks, and pragma Storage_Size has no effect.
32203In particular, Stack Overflow checks are made against this
32204link-time specified size.
32205
32206This setting can be done with @emph{gnatlink} using either of the following:
32207
32208
32209@itemize *
32210
32211@item
32212@emph{-Xlinker} linker option
32213
32214@example
32215$ gnatlink hello -Xlinker --stack=0x10000,0x1000
32216@end example
32217
32218This sets the stack reserve size to 0x10000 bytes and the stack commit
32219size to 0x1000 bytes.
32220
32221@item
32222@emph{-Wl} linker option
32223
32224@example
32225$ gnatlink hello -Wl,--stack=0x1000000
32226@end example
32227
32228This sets the stack reserve size to 0x1000000 bytes. Note that with
32229@emph{-Wl} option it is not possible to set the stack commit size
32230because the coma is a separator for this option.
32231@end itemize
32232
32233@node Setting Heap Size from gnatlink,,Setting Stack Size from gnatlink,Mixed-Language Programming on Windows
32234@anchor{gnat_ugn/platform_specific_information setting-heap-size-from-gnatlink}@anchor{13e}@anchor{gnat_ugn/platform_specific_information id41}@anchor{2b0}
32235@subsubsection Setting Heap Size from @emph{gnatlink}
32236
32237
32238Under Windows systems, it is possible to specify the program heap size from
32239@emph{gnatlink} using either of the following:
32240
32241
32242@itemize *
32243
32244@item
32245@emph{-Xlinker} linker option
32246
32247@example
32248$ gnatlink hello -Xlinker --heap=0x10000,0x1000
32249@end example
32250
32251This sets the heap reserve size to 0x10000 bytes and the heap commit
32252size to 0x1000 bytes.
32253
32254@item
32255@emph{-Wl} linker option
32256
32257@example
32258$ gnatlink hello -Wl,--heap=0x1000000
32259@end example
32260
32261This sets the heap reserve size to 0x1000000 bytes. Note that with
32262@emph{-Wl} option it is not possible to set the heap commit size
32263because the coma is a separator for this option.
32264@end itemize
32265
32266@node Windows Specific Add-Ons,,Mixed-Language Programming on Windows,Microsoft Windows Topics
32267@anchor{gnat_ugn/platform_specific_information windows-specific-add-ons}@anchor{2b1}@anchor{gnat_ugn/platform_specific_information win32-specific-addons}@anchor{2b2}
32268@subsection Windows Specific Add-Ons
32269
32270
32271This section describes the Windows specific add-ons.
32272
32273@menu
32274* Win32Ada::
32275* wPOSIX::
32276
32277@end menu
32278
32279@node Win32Ada,wPOSIX,,Windows Specific Add-Ons
32280@anchor{gnat_ugn/platform_specific_information win32ada}@anchor{2b3}@anchor{gnat_ugn/platform_specific_information id42}@anchor{2b4}
32281@subsubsection Win32Ada
32282
32283
32284Win32Ada is a binding for the Microsoft Win32 API. This binding can be
32285easily installed from the provided installer. To use the Win32Ada
32286binding you need to use a project file, and adding a single with_clause
32287will give you full access to the Win32Ada binding sources and ensure
32288that the proper libraries are passed to the linker.
32289
32290@quotation
32291
32292@example
32293with "win32ada";
32294project P is
32295   for Sources use ...;
32296end P;
32297@end example
32298@end quotation
32299
32300To build the application you just need to call gprbuild for the
32301application's project, here p.gpr:
32302
32303@quotation
32304
32305@example
32306gprbuild p.gpr
32307@end example
32308@end quotation
32309
32310@node wPOSIX,,Win32Ada,Windows Specific Add-Ons
32311@anchor{gnat_ugn/platform_specific_information id43}@anchor{2b5}@anchor{gnat_ugn/platform_specific_information wposix}@anchor{2b6}
32312@subsubsection wPOSIX
32313
32314
32315wPOSIX is a minimal POSIX binding whose goal is to help with building
32316cross-platforms applications. This binding is not complete though, as
32317the Win32 API does not provide the necessary support for all POSIX APIs.
32318
32319To use the wPOSIX binding you need to use a project file, and adding
32320a single with_clause will give you full access to the wPOSIX binding
32321sources and ensure that the proper libraries are passed to the linker.
32322
32323@quotation
32324
32325@example
32326with "wposix";
32327project P is
32328   for Sources use ...;
32329end P;
32330@end example
32331@end quotation
32332
32333To build the application you just need to call gprbuild for the
32334application's project, here p.gpr:
32335
32336@quotation
32337
32338@example
32339gprbuild p.gpr
32340@end example
32341@end quotation
32342
32343@node Mac OS Topics,,Microsoft Windows Topics,Platform-Specific Information
32344@anchor{gnat_ugn/platform_specific_information mac-os-topics}@anchor{2f}@anchor{gnat_ugn/platform_specific_information id44}@anchor{2b7}
32345@section Mac OS Topics
32346
32347
32348@geindex OS X
32349
32350This section describes topics that are specific to Apple's OS X
32351platform.
32352
32353@menu
32354* Codesigning the Debugger::
32355
32356@end menu
32357
32358@node Codesigning the Debugger,,,Mac OS Topics
32359@anchor{gnat_ugn/platform_specific_information codesigning-the-debugger}@anchor{2b8}
32360@subsection Codesigning the Debugger
32361
32362
32363The Darwin Kernel requires the debugger to have special permissions
32364before it is allowed to control other processes. These permissions
32365are granted by codesigning the GDB executable. Without these
32366permissions, the debugger will report error messages such as:
32367
32368@example
32369Starting program: /x/y/foo
32370Unable to find Mach task port for process-id 28885: (os/kern) failure (0x5).
32371(please check gdb is codesigned - see taskgated(8))
32372@end example
32373
32374Codesigning requires a certificate.  The following procedure explains
32375how to create one:
32376
32377
32378@itemize *
32379
32380@item
32381Start the Keychain Access application (in
32382/Applications/Utilities/Keychain Access.app)
32383
32384@item
32385Select the Keychain Access -> Certificate Assistant ->
32386Create a Certificate... menu
32387
32388@item
32389Then:
32390
32391
32392@itemize *
32393
32394@item
32395Choose a name for the new certificate (this procedure will use
32396"gdb-cert" as an example)
32397
32398@item
32399Set "Identity Type" to "Self Signed Root"
32400
32401@item
32402Set "Certificate Type" to "Code Signing"
32403
32404@item
32405Activate the "Let me override defaults" option
32406@end itemize
32407
32408@item
32409Click several times on "Continue" until the "Specify a Location
32410For The Certificate" screen appears, then set "Keychain" to "System"
32411
32412@item
32413Click on "Continue" until the certificate is created
32414
32415@item
32416Finally, in the view, double-click on the new certificate,
32417and set "When using this certificate" to "Always Trust"
32418
32419@item
32420Exit the Keychain Access application and restart the computer
32421(this is unfortunately required)
32422@end itemize
32423
32424Once a certificate has been created, the debugger can be codesigned
32425as follow. In a Terminal, run the following command:
32426
32427@quotation
32428
32429@example
32430$ codesign -f -s  "gdb-cert"  <gnat_install_prefix>/bin/gdb
32431@end example
32432@end quotation
32433
32434where "gdb-cert" should be replaced by the actual certificate
32435name chosen above, and <gnat_install_prefix> should be replaced by
32436the location where you installed GNAT.  Also, be sure that users are
32437in the Unix group @code{_developer}.
32438
32439@node Example of Binder Output File,Elaboration Order Handling in GNAT,Platform-Specific Information,Top
32440@anchor{gnat_ugn/example_of_binder_output example-of-binder-output-file}@anchor{10}@anchor{gnat_ugn/example_of_binder_output doc}@anchor{2b9}@anchor{gnat_ugn/example_of_binder_output id1}@anchor{2ba}
32441@chapter Example of Binder Output File
32442
32443
32444@geindex Binder output (example)
32445
32446This Appendix displays the source code for the output file
32447generated by @emph{gnatbind} for a simple 'Hello World' program.
32448Comments have been added for clarification purposes.
32449
32450@example
32451--  The package is called Ada_Main unless this name is actually used
32452--  as a unit name in the partition, in which case some other unique
32453--  name is used.
32454
32455pragma Ada_95;
32456with System;
32457package ada_main is
32458   pragma Warnings (Off);
32459
32460   --  The main program saves the parameters (argument count,
32461   --  argument values, environment pointer) in global variables
32462   --  for later access by other units including
32463   --  Ada.Command_Line.
32464
32465   gnat_argc : Integer;
32466   gnat_argv : System.Address;
32467   gnat_envp : System.Address;
32468
32469   --  The actual variables are stored in a library routine. This
32470   --  is useful for some shared library situations, where there
32471   --  are problems if variables are not in the library.
32472
32473   pragma Import (C, gnat_argc);
32474   pragma Import (C, gnat_argv);
32475   pragma Import (C, gnat_envp);
32476
32477   --  The exit status is similarly an external location
32478
32479   gnat_exit_status : Integer;
32480   pragma Import (C, gnat_exit_status);
32481
32482   GNAT_Version : constant String :=
32483                    "GNAT Version: Pro 7.4.0w (20141119-49)" & ASCII.NUL;
32484   pragma Export (C, GNAT_Version, "__gnat_version");
32485
32486   Ada_Main_Program_Name : constant String := "_ada_hello" & ASCII.NUL;
32487   pragma Export (C, Ada_Main_Program_Name, "__gnat_ada_main_program_name");
32488
32489   --  This is the generated adainit routine that performs
32490   --  initialization at the start of execution. In the case
32491   --  where Ada is the main program, this main program makes
32492   --  a call to adainit at program startup.
32493
32494   procedure adainit;
32495   pragma Export (C, adainit, "adainit");
32496
32497   --  This is the generated adafinal routine that performs
32498   --  finalization at the end of execution. In the case where
32499   --  Ada is the main program, this main program makes a call
32500   --  to adafinal at program termination.
32501
32502   procedure adafinal;
32503   pragma Export (C, adafinal, "adafinal");
32504
32505   --  This routine is called at the start of execution. It is
32506   --  a dummy routine that is used by the debugger to breakpoint
32507   --  at the start of execution.
32508
32509   --  This is the actual generated main program (it would be
32510   --  suppressed if the no main program switch were used). As
32511   --  required by standard system conventions, this program has
32512   --  the external name main.
32513
32514   function main
32515     (argc : Integer;
32516      argv : System.Address;
32517      envp : System.Address)
32518      return Integer;
32519   pragma Export (C, main, "main");
32520
32521   --  The following set of constants give the version
32522   --  identification values for every unit in the bound
32523   --  partition. This identification is computed from all
32524   --  dependent semantic units, and corresponds to the
32525   --  string that would be returned by use of the
32526   --  Body_Version or Version attributes.
32527
32528   --  The following Export pragmas export the version numbers
32529   --  with symbolic names ending in B (for body) or S
32530   --  (for spec) so that they can be located in a link. The
32531   --  information provided here is sufficient to track down
32532   --  the exact versions of units used in a given build.
32533
32534   type Version_32 is mod 2 ** 32;
32535   u00001 : constant Version_32 := 16#8ad6e54a#;
32536   pragma Export (C, u00001, "helloB");
32537   u00002 : constant Version_32 := 16#fbff4c67#;
32538   pragma Export (C, u00002, "system__standard_libraryB");
32539   u00003 : constant Version_32 := 16#1ec6fd90#;
32540   pragma Export (C, u00003, "system__standard_libraryS");
32541   u00004 : constant Version_32 := 16#3ffc8e18#;
32542   pragma Export (C, u00004, "adaS");
32543   u00005 : constant Version_32 := 16#28f088c2#;
32544   pragma Export (C, u00005, "ada__text_ioB");
32545   u00006 : constant Version_32 := 16#f372c8ac#;
32546   pragma Export (C, u00006, "ada__text_ioS");
32547   u00007 : constant Version_32 := 16#2c143749#;
32548   pragma Export (C, u00007, "ada__exceptionsB");
32549   u00008 : constant Version_32 := 16#f4f0cce8#;
32550   pragma Export (C, u00008, "ada__exceptionsS");
32551   u00009 : constant Version_32 := 16#a46739c0#;
32552   pragma Export (C, u00009, "ada__exceptions__last_chance_handlerB");
32553   u00010 : constant Version_32 := 16#3aac8c92#;
32554   pragma Export (C, u00010, "ada__exceptions__last_chance_handlerS");
32555   u00011 : constant Version_32 := 16#1d274481#;
32556   pragma Export (C, u00011, "systemS");
32557   u00012 : constant Version_32 := 16#a207fefe#;
32558   pragma Export (C, u00012, "system__soft_linksB");
32559   u00013 : constant Version_32 := 16#467d9556#;
32560   pragma Export (C, u00013, "system__soft_linksS");
32561   u00014 : constant Version_32 := 16#b01dad17#;
32562   pragma Export (C, u00014, "system__parametersB");
32563   u00015 : constant Version_32 := 16#630d49fe#;
32564   pragma Export (C, u00015, "system__parametersS");
32565   u00016 : constant Version_32 := 16#b19b6653#;
32566   pragma Export (C, u00016, "system__secondary_stackB");
32567   u00017 : constant Version_32 := 16#b6468be8#;
32568   pragma Export (C, u00017, "system__secondary_stackS");
32569   u00018 : constant Version_32 := 16#39a03df9#;
32570   pragma Export (C, u00018, "system__storage_elementsB");
32571   u00019 : constant Version_32 := 16#30e40e85#;
32572   pragma Export (C, u00019, "system__storage_elementsS");
32573   u00020 : constant Version_32 := 16#41837d1e#;
32574   pragma Export (C, u00020, "system__stack_checkingB");
32575   u00021 : constant Version_32 := 16#93982f69#;
32576   pragma Export (C, u00021, "system__stack_checkingS");
32577   u00022 : constant Version_32 := 16#393398c1#;
32578   pragma Export (C, u00022, "system__exception_tableB");
32579   u00023 : constant Version_32 := 16#b33e2294#;
32580   pragma Export (C, u00023, "system__exception_tableS");
32581   u00024 : constant Version_32 := 16#ce4af020#;
32582   pragma Export (C, u00024, "system__exceptionsB");
32583   u00025 : constant Version_32 := 16#75442977#;
32584   pragma Export (C, u00025, "system__exceptionsS");
32585   u00026 : constant Version_32 := 16#37d758f1#;
32586   pragma Export (C, u00026, "system__exceptions__machineS");
32587   u00027 : constant Version_32 := 16#b895431d#;
32588   pragma Export (C, u00027, "system__exceptions_debugB");
32589   u00028 : constant Version_32 := 16#aec55d3f#;
32590   pragma Export (C, u00028, "system__exceptions_debugS");
32591   u00029 : constant Version_32 := 16#570325c8#;
32592   pragma Export (C, u00029, "system__img_intB");
32593   u00030 : constant Version_32 := 16#1ffca443#;
32594   pragma Export (C, u00030, "system__img_intS");
32595   u00031 : constant Version_32 := 16#b98c3e16#;
32596   pragma Export (C, u00031, "system__tracebackB");
32597   u00032 : constant Version_32 := 16#831a9d5a#;
32598   pragma Export (C, u00032, "system__tracebackS");
32599   u00033 : constant Version_32 := 16#9ed49525#;
32600   pragma Export (C, u00033, "system__traceback_entriesB");
32601   u00034 : constant Version_32 := 16#1d7cb2f1#;
32602   pragma Export (C, u00034, "system__traceback_entriesS");
32603   u00035 : constant Version_32 := 16#8c33a517#;
32604   pragma Export (C, u00035, "system__wch_conB");
32605   u00036 : constant Version_32 := 16#065a6653#;
32606   pragma Export (C, u00036, "system__wch_conS");
32607   u00037 : constant Version_32 := 16#9721e840#;
32608   pragma Export (C, u00037, "system__wch_stwB");
32609   u00038 : constant Version_32 := 16#2b4b4a52#;
32610   pragma Export (C, u00038, "system__wch_stwS");
32611   u00039 : constant Version_32 := 16#92b797cb#;
32612   pragma Export (C, u00039, "system__wch_cnvB");
32613   u00040 : constant Version_32 := 16#09eddca0#;
32614   pragma Export (C, u00040, "system__wch_cnvS");
32615   u00041 : constant Version_32 := 16#6033a23f#;
32616   pragma Export (C, u00041, "interfacesS");
32617   u00042 : constant Version_32 := 16#ece6fdb6#;
32618   pragma Export (C, u00042, "system__wch_jisB");
32619   u00043 : constant Version_32 := 16#899dc581#;
32620   pragma Export (C, u00043, "system__wch_jisS");
32621   u00044 : constant Version_32 := 16#10558b11#;
32622   pragma Export (C, u00044, "ada__streamsB");
32623   u00045 : constant Version_32 := 16#2e6701ab#;
32624   pragma Export (C, u00045, "ada__streamsS");
32625   u00046 : constant Version_32 := 16#db5c917c#;
32626   pragma Export (C, u00046, "ada__io_exceptionsS");
32627   u00047 : constant Version_32 := 16#12c8cd7d#;
32628   pragma Export (C, u00047, "ada__tagsB");
32629   u00048 : constant Version_32 := 16#ce72c228#;
32630   pragma Export (C, u00048, "ada__tagsS");
32631   u00049 : constant Version_32 := 16#c3335bfd#;
32632   pragma Export (C, u00049, "system__htableB");
32633   u00050 : constant Version_32 := 16#99e5f76b#;
32634   pragma Export (C, u00050, "system__htableS");
32635   u00051 : constant Version_32 := 16#089f5cd0#;
32636   pragma Export (C, u00051, "system__string_hashB");
32637   u00052 : constant Version_32 := 16#3bbb9c15#;
32638   pragma Export (C, u00052, "system__string_hashS");
32639   u00053 : constant Version_32 := 16#807fe041#;
32640   pragma Export (C, u00053, "system__unsigned_typesS");
32641   u00054 : constant Version_32 := 16#d27be59e#;
32642   pragma Export (C, u00054, "system__val_lluB");
32643   u00055 : constant Version_32 := 16#fa8db733#;
32644   pragma Export (C, u00055, "system__val_lluS");
32645   u00056 : constant Version_32 := 16#27b600b2#;
32646   pragma Export (C, u00056, "system__val_utilB");
32647   u00057 : constant Version_32 := 16#b187f27f#;
32648   pragma Export (C, u00057, "system__val_utilS");
32649   u00058 : constant Version_32 := 16#d1060688#;
32650   pragma Export (C, u00058, "system__case_utilB");
32651   u00059 : constant Version_32 := 16#392e2d56#;
32652   pragma Export (C, u00059, "system__case_utilS");
32653   u00060 : constant Version_32 := 16#84a27f0d#;
32654   pragma Export (C, u00060, "interfaces__c_streamsB");
32655   u00061 : constant Version_32 := 16#8bb5f2c0#;
32656   pragma Export (C, u00061, "interfaces__c_streamsS");
32657   u00062 : constant Version_32 := 16#6db6928f#;
32658   pragma Export (C, u00062, "system__crtlS");
32659   u00063 : constant Version_32 := 16#4e6a342b#;
32660   pragma Export (C, u00063, "system__file_ioB");
32661   u00064 : constant Version_32 := 16#ba56a5e4#;
32662   pragma Export (C, u00064, "system__file_ioS");
32663   u00065 : constant Version_32 := 16#b7ab275c#;
32664   pragma Export (C, u00065, "ada__finalizationB");
32665   u00066 : constant Version_32 := 16#19f764ca#;
32666   pragma Export (C, u00066, "ada__finalizationS");
32667   u00067 : constant Version_32 := 16#95817ed8#;
32668   pragma Export (C, u00067, "system__finalization_rootB");
32669   u00068 : constant Version_32 := 16#52d53711#;
32670   pragma Export (C, u00068, "system__finalization_rootS");
32671   u00069 : constant Version_32 := 16#769e25e6#;
32672   pragma Export (C, u00069, "interfaces__cB");
32673   u00070 : constant Version_32 := 16#4a38bedb#;
32674   pragma Export (C, u00070, "interfaces__cS");
32675   u00071 : constant Version_32 := 16#07e6ee66#;
32676   pragma Export (C, u00071, "system__os_libB");
32677   u00072 : constant Version_32 := 16#d7b69782#;
32678   pragma Export (C, u00072, "system__os_libS");
32679   u00073 : constant Version_32 := 16#1a817b8e#;
32680   pragma Export (C, u00073, "system__stringsB");
32681   u00074 : constant Version_32 := 16#639855e7#;
32682   pragma Export (C, u00074, "system__stringsS");
32683   u00075 : constant Version_32 := 16#e0b8de29#;
32684   pragma Export (C, u00075, "system__file_control_blockS");
32685   u00076 : constant Version_32 := 16#b5b2aca1#;
32686   pragma Export (C, u00076, "system__finalization_mastersB");
32687   u00077 : constant Version_32 := 16#69316dc1#;
32688   pragma Export (C, u00077, "system__finalization_mastersS");
32689   u00078 : constant Version_32 := 16#57a37a42#;
32690   pragma Export (C, u00078, "system__address_imageB");
32691   u00079 : constant Version_32 := 16#bccbd9bb#;
32692   pragma Export (C, u00079, "system__address_imageS");
32693   u00080 : constant Version_32 := 16#7268f812#;
32694   pragma Export (C, u00080, "system__img_boolB");
32695   u00081 : constant Version_32 := 16#e8fe356a#;
32696   pragma Export (C, u00081, "system__img_boolS");
32697   u00082 : constant Version_32 := 16#d7aac20c#;
32698   pragma Export (C, u00082, "system__ioB");
32699   u00083 : constant Version_32 := 16#8365b3ce#;
32700   pragma Export (C, u00083, "system__ioS");
32701   u00084 : constant Version_32 := 16#6d4d969a#;
32702   pragma Export (C, u00084, "system__storage_poolsB");
32703   u00085 : constant Version_32 := 16#e87cc305#;
32704   pragma Export (C, u00085, "system__storage_poolsS");
32705   u00086 : constant Version_32 := 16#e34550ca#;
32706   pragma Export (C, u00086, "system__pool_globalB");
32707   u00087 : constant Version_32 := 16#c88d2d16#;
32708   pragma Export (C, u00087, "system__pool_globalS");
32709   u00088 : constant Version_32 := 16#9d39c675#;
32710   pragma Export (C, u00088, "system__memoryB");
32711   u00089 : constant Version_32 := 16#445a22b5#;
32712   pragma Export (C, u00089, "system__memoryS");
32713   u00090 : constant Version_32 := 16#6a859064#;
32714   pragma Export (C, u00090, "system__storage_pools__subpoolsB");
32715   u00091 : constant Version_32 := 16#e3b008dc#;
32716   pragma Export (C, u00091, "system__storage_pools__subpoolsS");
32717   u00092 : constant Version_32 := 16#63f11652#;
32718   pragma Export (C, u00092, "system__storage_pools__subpools__finalizationB");
32719   u00093 : constant Version_32 := 16#fe2f4b3a#;
32720   pragma Export (C, u00093, "system__storage_pools__subpools__finalizationS");
32721
32722   --  BEGIN ELABORATION ORDER
32723   --  ada%s
32724   --  interfaces%s
32725   --  system%s
32726   --  system.case_util%s
32727   --  system.case_util%b
32728   --  system.htable%s
32729   --  system.img_bool%s
32730   --  system.img_bool%b
32731   --  system.img_int%s
32732   --  system.img_int%b
32733   --  system.io%s
32734   --  system.io%b
32735   --  system.parameters%s
32736   --  system.parameters%b
32737   --  system.crtl%s
32738   --  interfaces.c_streams%s
32739   --  interfaces.c_streams%b
32740   --  system.standard_library%s
32741   --  system.exceptions_debug%s
32742   --  system.exceptions_debug%b
32743   --  system.storage_elements%s
32744   --  system.storage_elements%b
32745   --  system.stack_checking%s
32746   --  system.stack_checking%b
32747   --  system.string_hash%s
32748   --  system.string_hash%b
32749   --  system.htable%b
32750   --  system.strings%s
32751   --  system.strings%b
32752   --  system.os_lib%s
32753   --  system.traceback_entries%s
32754   --  system.traceback_entries%b
32755   --  ada.exceptions%s
32756   --  system.soft_links%s
32757   --  system.unsigned_types%s
32758   --  system.val_llu%s
32759   --  system.val_util%s
32760   --  system.val_util%b
32761   --  system.val_llu%b
32762   --  system.wch_con%s
32763   --  system.wch_con%b
32764   --  system.wch_cnv%s
32765   --  system.wch_jis%s
32766   --  system.wch_jis%b
32767   --  system.wch_cnv%b
32768   --  system.wch_stw%s
32769   --  system.wch_stw%b
32770   --  ada.exceptions.last_chance_handler%s
32771   --  ada.exceptions.last_chance_handler%b
32772   --  system.address_image%s
32773   --  system.exception_table%s
32774   --  system.exception_table%b
32775   --  ada.io_exceptions%s
32776   --  ada.tags%s
32777   --  ada.streams%s
32778   --  ada.streams%b
32779   --  interfaces.c%s
32780   --  system.exceptions%s
32781   --  system.exceptions%b
32782   --  system.exceptions.machine%s
32783   --  system.finalization_root%s
32784   --  system.finalization_root%b
32785   --  ada.finalization%s
32786   --  ada.finalization%b
32787   --  system.storage_pools%s
32788   --  system.storage_pools%b
32789   --  system.finalization_masters%s
32790   --  system.storage_pools.subpools%s
32791   --  system.storage_pools.subpools.finalization%s
32792   --  system.storage_pools.subpools.finalization%b
32793   --  system.memory%s
32794   --  system.memory%b
32795   --  system.standard_library%b
32796   --  system.pool_global%s
32797   --  system.pool_global%b
32798   --  system.file_control_block%s
32799   --  system.file_io%s
32800   --  system.secondary_stack%s
32801   --  system.file_io%b
32802   --  system.storage_pools.subpools%b
32803   --  system.finalization_masters%b
32804   --  interfaces.c%b
32805   --  ada.tags%b
32806   --  system.soft_links%b
32807   --  system.os_lib%b
32808   --  system.secondary_stack%b
32809   --  system.address_image%b
32810   --  system.traceback%s
32811   --  ada.exceptions%b
32812   --  system.traceback%b
32813   --  ada.text_io%s
32814   --  ada.text_io%b
32815   --  hello%b
32816   --  END ELABORATION ORDER
32817
32818end ada_main;
32819@end example
32820
32821@example
32822pragma Ada_95;
32823--  The following source file name pragmas allow the generated file
32824--  names to be unique for different main programs. They are needed
32825--  since the package name will always be Ada_Main.
32826
32827pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
32828pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
32829
32830pragma Suppress (Overflow_Check);
32831with Ada.Exceptions;
32832
32833--  Generated package body for Ada_Main starts here
32834
32835package body ada_main is
32836   pragma Warnings (Off);
32837
32838   --  These values are reference counter associated to units which have
32839   --  been elaborated. It is also used to avoid elaborating the
32840   --  same unit twice.
32841
32842   E72 : Short_Integer; pragma Import (Ada, E72, "system__os_lib_E");
32843   E13 : Short_Integer; pragma Import (Ada, E13, "system__soft_links_E");
32844   E23 : Short_Integer; pragma Import (Ada, E23, "system__exception_table_E");
32845   E46 : Short_Integer; pragma Import (Ada, E46, "ada__io_exceptions_E");
32846   E48 : Short_Integer; pragma Import (Ada, E48, "ada__tags_E");
32847   E45 : Short_Integer; pragma Import (Ada, E45, "ada__streams_E");
32848   E70 : Short_Integer; pragma Import (Ada, E70, "interfaces__c_E");
32849   E25 : Short_Integer; pragma Import (Ada, E25, "system__exceptions_E");
32850   E68 : Short_Integer; pragma Import (Ada, E68, "system__finalization_root_E");
32851   E66 : Short_Integer; pragma Import (Ada, E66, "ada__finalization_E");
32852   E85 : Short_Integer; pragma Import (Ada, E85, "system__storage_pools_E");
32853   E77 : Short_Integer; pragma Import (Ada, E77, "system__finalization_masters_E");
32854   E91 : Short_Integer; pragma Import (Ada, E91, "system__storage_pools__subpools_E");
32855   E87 : Short_Integer; pragma Import (Ada, E87, "system__pool_global_E");
32856   E75 : Short_Integer; pragma Import (Ada, E75, "system__file_control_block_E");
32857   E64 : Short_Integer; pragma Import (Ada, E64, "system__file_io_E");
32858   E17 : Short_Integer; pragma Import (Ada, E17, "system__secondary_stack_E");
32859   E06 : Short_Integer; pragma Import (Ada, E06, "ada__text_io_E");
32860
32861   Local_Priority_Specific_Dispatching : constant String := "";
32862   Local_Interrupt_States : constant String := "";
32863
32864   Is_Elaborated : Boolean := False;
32865
32866   procedure finalize_library is
32867   begin
32868      E06 := E06 - 1;
32869      declare
32870         procedure F1;
32871         pragma Import (Ada, F1, "ada__text_io__finalize_spec");
32872      begin
32873         F1;
32874      end;
32875      E77 := E77 - 1;
32876      E91 := E91 - 1;
32877      declare
32878         procedure F2;
32879         pragma Import (Ada, F2, "system__file_io__finalize_body");
32880      begin
32881         E64 := E64 - 1;
32882         F2;
32883      end;
32884      declare
32885         procedure F3;
32886         pragma Import (Ada, F3, "system__file_control_block__finalize_spec");
32887      begin
32888         E75 := E75 - 1;
32889         F3;
32890      end;
32891      E87 := E87 - 1;
32892      declare
32893         procedure F4;
32894         pragma Import (Ada, F4, "system__pool_global__finalize_spec");
32895      begin
32896         F4;
32897      end;
32898      declare
32899         procedure F5;
32900         pragma Import (Ada, F5, "system__storage_pools__subpools__finalize_spec");
32901      begin
32902         F5;
32903      end;
32904      declare
32905         procedure F6;
32906         pragma Import (Ada, F6, "system__finalization_masters__finalize_spec");
32907      begin
32908         F6;
32909      end;
32910      declare
32911         procedure Reraise_Library_Exception_If_Any;
32912         pragma Import (Ada, Reraise_Library_Exception_If_Any, "__gnat_reraise_library_exception_if_any");
32913      begin
32914         Reraise_Library_Exception_If_Any;
32915      end;
32916   end finalize_library;
32917
32918   -------------
32919   -- adainit --
32920   -------------
32921
32922   procedure adainit is
32923
32924      Main_Priority : Integer;
32925      pragma Import (C, Main_Priority, "__gl_main_priority");
32926      Time_Slice_Value : Integer;
32927      pragma Import (C, Time_Slice_Value, "__gl_time_slice_val");
32928      WC_Encoding : Character;
32929      pragma Import (C, WC_Encoding, "__gl_wc_encoding");
32930      Locking_Policy : Character;
32931      pragma Import (C, Locking_Policy, "__gl_locking_policy");
32932      Queuing_Policy : Character;
32933      pragma Import (C, Queuing_Policy, "__gl_queuing_policy");
32934      Task_Dispatching_Policy : Character;
32935      pragma Import (C, Task_Dispatching_Policy, "__gl_task_dispatching_policy");
32936      Priority_Specific_Dispatching : System.Address;
32937      pragma Import (C, Priority_Specific_Dispatching, "__gl_priority_specific_dispatching");
32938      Num_Specific_Dispatching : Integer;
32939      pragma Import (C, Num_Specific_Dispatching, "__gl_num_specific_dispatching");
32940      Main_CPU : Integer;
32941      pragma Import (C, Main_CPU, "__gl_main_cpu");
32942      Interrupt_States : System.Address;
32943      pragma Import (C, Interrupt_States, "__gl_interrupt_states");
32944      Num_Interrupt_States : Integer;
32945      pragma Import (C, Num_Interrupt_States, "__gl_num_interrupt_states");
32946      Unreserve_All_Interrupts : Integer;
32947      pragma Import (C, Unreserve_All_Interrupts, "__gl_unreserve_all_interrupts");
32948      Detect_Blocking : Integer;
32949      pragma Import (C, Detect_Blocking, "__gl_detect_blocking");
32950      Default_Stack_Size : Integer;
32951      pragma Import (C, Default_Stack_Size, "__gl_default_stack_size");
32952      Leap_Seconds_Support : Integer;
32953      pragma Import (C, Leap_Seconds_Support, "__gl_leap_seconds_support");
32954
32955      procedure Runtime_Initialize;
32956      pragma Import (C, Runtime_Initialize, "__gnat_runtime_initialize");
32957
32958      Finalize_Library_Objects : No_Param_Proc;
32959      pragma Import (C, Finalize_Library_Objects, "__gnat_finalize_library_objects");
32960
32961   --  Start of processing for adainit
32962
32963   begin
32964
32965      --  Record various information for this partition.  The values
32966      --  are derived by the binder from information stored in the ali
32967      --  files by the compiler.
32968
32969      if Is_Elaborated then
32970         return;
32971      end if;
32972      Is_Elaborated := True;
32973      Main_Priority := -1;
32974      Time_Slice_Value := -1;
32975      WC_Encoding := 'b';
32976      Locking_Policy := ' ';
32977      Queuing_Policy := ' ';
32978      Task_Dispatching_Policy := ' ';
32979      Priority_Specific_Dispatching :=
32980        Local_Priority_Specific_Dispatching'Address;
32981      Num_Specific_Dispatching := 0;
32982      Main_CPU := -1;
32983      Interrupt_States := Local_Interrupt_States'Address;
32984      Num_Interrupt_States := 0;
32985      Unreserve_All_Interrupts := 0;
32986      Detect_Blocking := 0;
32987      Default_Stack_Size := -1;
32988      Leap_Seconds_Support := 0;
32989
32990      Runtime_Initialize;
32991
32992      Finalize_Library_Objects := finalize_library'access;
32993
32994      --  Now we have the elaboration calls for all units in the partition.
32995      --  The Elab_Spec and Elab_Body attributes generate references to the
32996      --  implicit elaboration procedures generated by the compiler for
32997      --  each unit that requires elaboration. Increment a counter of
32998      --  reference for each unit.
32999
33000      System.Soft_Links'Elab_Spec;
33001      System.Exception_Table'Elab_Body;
33002      E23 := E23 + 1;
33003      Ada.Io_Exceptions'Elab_Spec;
33004      E46 := E46 + 1;
33005      Ada.Tags'Elab_Spec;
33006      Ada.Streams'Elab_Spec;
33007      E45 := E45 + 1;
33008      Interfaces.C'Elab_Spec;
33009      System.Exceptions'Elab_Spec;
33010      E25 := E25 + 1;
33011      System.Finalization_Root'Elab_Spec;
33012      E68 := E68 + 1;
33013      Ada.Finalization'Elab_Spec;
33014      E66 := E66 + 1;
33015      System.Storage_Pools'Elab_Spec;
33016      E85 := E85 + 1;
33017      System.Finalization_Masters'Elab_Spec;
33018      System.Storage_Pools.Subpools'Elab_Spec;
33019      System.Pool_Global'Elab_Spec;
33020      E87 := E87 + 1;
33021      System.File_Control_Block'Elab_Spec;
33022      E75 := E75 + 1;
33023      System.File_Io'Elab_Body;
33024      E64 := E64 + 1;
33025      E91 := E91 + 1;
33026      System.Finalization_Masters'Elab_Body;
33027      E77 := E77 + 1;
33028      E70 := E70 + 1;
33029      Ada.Tags'Elab_Body;
33030      E48 := E48 + 1;
33031      System.Soft_Links'Elab_Body;
33032      E13 := E13 + 1;
33033      System.Os_Lib'Elab_Body;
33034      E72 := E72 + 1;
33035      System.Secondary_Stack'Elab_Body;
33036      E17 := E17 + 1;
33037      Ada.Text_Io'Elab_Spec;
33038      Ada.Text_Io'Elab_Body;
33039      E06 := E06 + 1;
33040   end adainit;
33041
33042   --------------
33043   -- adafinal --
33044   --------------
33045
33046   procedure adafinal is
33047      procedure s_stalib_adafinal;
33048      pragma Import (C, s_stalib_adafinal, "system__standard_library__adafinal");
33049
33050      procedure Runtime_Finalize;
33051      pragma Import (C, Runtime_Finalize, "__gnat_runtime_finalize");
33052
33053   begin
33054      if not Is_Elaborated then
33055         return;
33056      end if;
33057      Is_Elaborated := False;
33058      Runtime_Finalize;
33059      s_stalib_adafinal;
33060   end adafinal;
33061
33062   --  We get to the main program of the partition by using
33063   --  pragma Import because if we try to with the unit and
33064   --  call it Ada style, then not only do we waste time
33065   --  recompiling it, but also, we don't really know the right
33066   --  switches (e.g.@@: identifier character set) to be used
33067   --  to compile it.
33068
33069   procedure Ada_Main_Program;
33070   pragma Import (Ada, Ada_Main_Program, "_ada_hello");
33071
33072   ----------
33073   -- main --
33074   ----------
33075
33076   --  main is actually a function, as in the ANSI C standard,
33077   --  defined to return the exit status. The three parameters
33078   --  are the argument count, argument values and environment
33079   --  pointer.
33080
33081   function main
33082     (argc : Integer;
33083      argv : System.Address;
33084      envp : System.Address)
33085      return Integer
33086   is
33087      --  The initialize routine performs low level system
33088      --  initialization using a standard library routine which
33089      --  sets up signal handling and performs any other
33090      --  required setup. The routine can be found in file
33091      --  a-init.c.
33092
33093      procedure initialize;
33094      pragma Import (C, initialize, "__gnat_initialize");
33095
33096      --  The finalize routine performs low level system
33097      --  finalization using a standard library routine. The
33098      --  routine is found in file a-final.c and in the standard
33099      --  distribution is a dummy routine that does nothing, so
33100      --  really this is a hook for special user finalization.
33101
33102      procedure finalize;
33103      pragma Import (C, finalize, "__gnat_finalize");
33104
33105      --  The following is to initialize the SEH exceptions
33106
33107      SEH : aliased array (1 .. 2) of Integer;
33108
33109      Ensure_Reference : aliased System.Address := Ada_Main_Program_Name'Address;
33110      pragma Volatile (Ensure_Reference);
33111
33112   --  Start of processing for main
33113
33114   begin
33115      --  Save global variables
33116
33117      gnat_argc := argc;
33118      gnat_argv := argv;
33119      gnat_envp := envp;
33120
33121      --  Call low level system initialization
33122
33123      Initialize (SEH'Address);
33124
33125      --  Call our generated Ada initialization routine
33126
33127      adainit;
33128
33129      --  Now we call the main program of the partition
33130
33131      Ada_Main_Program;
33132
33133      --  Perform Ada finalization
33134
33135      adafinal;
33136
33137      --  Perform low level system finalization
33138
33139      Finalize;
33140
33141      --  Return the proper exit status
33142      return (gnat_exit_status);
33143   end;
33144
33145--  This section is entirely comments, so it has no effect on the
33146--  compilation of the Ada_Main package. It provides the list of
33147--  object files and linker options, as well as some standard
33148--  libraries needed for the link. The gnatlink utility parses
33149--  this b~hello.adb file to read these comment lines to generate
33150--  the appropriate command line arguments for the call to the
33151--  system linker. The BEGIN/END lines are used for sentinels for
33152--  this parsing operation.
33153
33154--  The exact file names will of course depend on the environment,
33155--  host/target and location of files on the host system.
33156
33157-- BEGIN Object file/option list
33158   --   ./hello.o
33159   --   -L./
33160   --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
33161   --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
33162-- END Object file/option list
33163
33164end ada_main;
33165@end example
33166
33167The Ada code in the above example is exactly what is generated by the
33168binder. We have added comments to more clearly indicate the function
33169of each part of the generated @cite{Ada_Main} package.
33170
33171The code is standard Ada in all respects, and can be processed by any
33172tools that handle Ada. In particular, it is possible to use the debugger
33173in Ada mode to debug the generated @cite{Ada_Main} package. For example,
33174suppose that for reasons that you do not understand, your program is crashing
33175during elaboration of the body of @cite{Ada.Text_IO}. To locate this bug,
33176you can place a breakpoint on the call:
33177
33178@quotation
33179
33180@example
33181Ada.Text_Io'Elab_Body;
33182@end example
33183@end quotation
33184
33185and trace the elaboration routine for this package to find out where
33186the problem might be (more usually of course you would be debugging
33187elaboration code in your own application).
33188
33189@c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
33190
33191@node Elaboration Order Handling in GNAT,Inline Assembler,Example of Binder Output File,Top
33192@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{2bb}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id1}@anchor{2bc}
33193@chapter Elaboration Order Handling in GNAT
33194
33195
33196@geindex Order of elaboration
33197
33198@geindex Elaboration control
33199
33200This appendix describes the handling of elaboration code in Ada and
33201in GNAT, and discusses how the order of elaboration of program units can
33202be controlled in GNAT, either automatically or with explicit programming
33203features.
33204
33205@menu
33206* Elaboration Code::
33207* Checking the Elaboration Order::
33208* Controlling the Elaboration Order::
33209* Controlling Elaboration in GNAT - Internal Calls::
33210* Controlling Elaboration in GNAT - External Calls::
33211* Default Behavior in GNAT - Ensuring Safety::
33212* Treatment of Pragma Elaborate::
33213* Elaboration Issues for Library Tasks::
33214* Mixing Elaboration Models::
33215* What to Do If the Default Elaboration Behavior Fails::
33216* Elaboration for Indirect Calls::
33217* Summary of Procedures for Elaboration Control::
33218* Other Elaboration Order Considerations::
33219* Determining the Chosen Elaboration Order::
33220
33221@end menu
33222
33223@node Elaboration Code,Checking the Elaboration Order,,Elaboration Order Handling in GNAT
33224@anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-code}@anchor{2bd}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id2}@anchor{2be}
33225@section Elaboration Code
33226
33227
33228Ada provides rather general mechanisms for executing code at elaboration
33229time, that is to say before the main program starts executing. Such code arises
33230in three contexts:
33231
33232
33233@itemize *
33234
33235@item
33236@emph{Initializers for variables}
33237
33238Variables declared at the library level, in package specs or bodies, can
33239require initialization that is performed at elaboration time, as in:
33240
33241@example
33242Sqrt_Half : Float := Sqrt (0.5);
33243@end example
33244
33245@item
33246@emph{Package initialization code}
33247
33248Code in a @cite{BEGIN-END} section at the outer level of a package body is
33249executed as part of the package body elaboration code.
33250
33251@item
33252@emph{Library level task allocators}
33253
33254Tasks that are declared using task allocators at the library level
33255start executing immediately and hence can execute at elaboration time.
33256@end itemize
33257
33258Subprogram calls are possible in any of these contexts, which means that
33259any arbitrary part of the program may be executed as part of the elaboration
33260code. It is even possible to write a program which does all its work at
33261elaboration time, with a null main program, although stylistically this
33262would usually be considered an inappropriate way to structure
33263a program.
33264
33265An important concern arises in the context of elaboration code:
33266we have to be sure that it is executed in an appropriate order. What we
33267have is a series of elaboration code sections, potentially one section
33268for each unit in the program. It is important that these execute
33269in the correct order. Correctness here means that, taking the above
33270example of the declaration of @cite{Sqrt_Half},
33271if some other piece of
33272elaboration code references @cite{Sqrt_Half},
33273then it must run after the
33274section of elaboration code that contains the declaration of
33275@cite{Sqrt_Half}.
33276
33277There would never be any order of elaboration problem if we made a rule
33278that whenever you @emph{with} a unit, you must elaborate both the spec and body
33279of that unit before elaborating the unit doing the @emph{with}ing:
33280
33281@example
33282with Unit_1;
33283package Unit_2 is ...
33284@end example
33285
33286would require that both the body and spec of @cite{Unit_1} be elaborated
33287before the spec of @cite{Unit_2}. However, a rule like that would be far too
33288restrictive. In particular, it would make it impossible to have routines
33289in separate packages that were mutually recursive.
33290
33291You might think that a clever enough compiler could look at the actual
33292elaboration code and determine an appropriate correct order of elaboration,
33293but in the general case, this is not possible. Consider the following
33294example.
33295
33296In the body of @cite{Unit_1}, we have a procedure @cite{Func_1}
33297that references
33298the variable @cite{Sqrt_1}, which is declared in the elaboration code
33299of the body of @cite{Unit_1}:
33300
33301@example
33302Sqrt_1 : Float := Sqrt (0.1);
33303@end example
33304
33305The elaboration code of the body of @cite{Unit_1} also contains:
33306
33307@example
33308if expression_1 = 1 then
33309   Q := Unit_2.Func_2;
33310end if;
33311@end example
33312
33313@cite{Unit_2} is exactly parallel,
33314it has a procedure @cite{Func_2} that references
33315the variable @cite{Sqrt_2}, which is declared in the elaboration code of
33316the body @cite{Unit_2}:
33317
33318@example
33319Sqrt_2 : Float := Sqrt (0.1);
33320@end example
33321
33322The elaboration code of the body of @cite{Unit_2} also contains:
33323
33324@example
33325if expression_2 = 2 then
33326   Q := Unit_1.Func_1;
33327end if;
33328@end example
33329
33330Now the question is, which of the following orders of elaboration is
33331acceptable:
33332
33333@example
33334Spec of Unit_1
33335Spec of Unit_2
33336Body of Unit_1
33337Body of Unit_2
33338@end example
33339
33340or
33341
33342@example
33343Spec of Unit_2
33344Spec of Unit_1
33345Body of Unit_2
33346Body of Unit_1
33347@end example
33348
33349If you carefully analyze the flow here, you will see that you cannot tell
33350at compile time the answer to this question.
33351If @cite{expression_1} is not equal to 1,
33352and @cite{expression_2} is not equal to 2,
33353then either order is acceptable, because neither of the function calls is
33354executed. If both tests evaluate to true, then neither order is acceptable
33355and in fact there is no correct order.
33356
33357If one of the two expressions is true, and the other is false, then one
33358of the above orders is correct, and the other is incorrect. For example,
33359if @cite{expression_1} /= 1 and @cite{expression_2} = 2,
33360then the call to @cite{Func_1}
33361will occur, but not the call to @cite{Func_2.}
33362This means that it is essential
33363to elaborate the body of @cite{Unit_1} before
33364the body of @cite{Unit_2}, so the first
33365order of elaboration is correct and the second is wrong.
33366
33367By making @cite{expression_1} and @cite{expression_2}
33368depend on input data, or perhaps
33369the time of day, we can make it impossible for the compiler or binder
33370to figure out which of these expressions will be true, and hence it
33371is impossible to guarantee a safe order of elaboration at run time.
33372
33373@node Checking the Elaboration Order,Controlling the Elaboration Order,Elaboration Code,Elaboration Order Handling in GNAT
33374@anchor{gnat_ugn/elaboration_order_handling_in_gnat checking-the-elaboration-order}@anchor{2bf}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id3}@anchor{2c0}
33375@section Checking the Elaboration Order
33376
33377
33378In some languages that involve the same kind of elaboration problems,
33379e.g., Java and C++, the programmer needs to take these
33380ordering problems into account, and it is common to
33381write a program in which an incorrect elaboration order  gives
33382surprising results, because it references variables before they
33383are initialized.
33384Ada is designed to be a safe language, and a programmer-beware approach is
33385clearly not sufficient. Consequently, the language provides three lines
33386of defense:
33387
33388
33389@itemize *
33390
33391@item
33392@emph{Standard rules}
33393
33394Some standard rules restrict the possible choice of elaboration
33395order. In particular, if you @emph{with} a unit, then its spec is always
33396elaborated before the unit doing the @emph{with}. Similarly, a parent
33397spec is always elaborated before the child spec, and finally
33398a spec is always elaborated before its corresponding body.
33399@end itemize
33400
33401@geindex Elaboration checks
33402
33403@geindex Checks
33404@geindex elaboration
33405
33406
33407@itemize *
33408
33409@item
33410@emph{Dynamic elaboration checks}
33411
33412Dynamic checks are made at run time, so that if some entity is accessed
33413before it is elaborated (typically  by means of a subprogram call)
33414then the exception (@cite{Program_Error}) is raised.
33415
33416@item
33417@emph{Elaboration control}
33418
33419Facilities are provided for the programmer to specify the desired order
33420of elaboration.
33421@end itemize
33422
33423Let's look at these facilities in more detail. First, the rules for
33424dynamic checking. One possible rule would be simply to say that the
33425exception is raised if you access a variable which has not yet been
33426elaborated. The trouble with this approach is that it could require
33427expensive checks on every variable reference. Instead Ada has two
33428rules which are a little more restrictive, but easier to check, and
33429easier to state:
33430
33431
33432@itemize *
33433
33434@item
33435@emph{Restrictions on calls}
33436
33437A subprogram can only be called at elaboration time if its body
33438has been elaborated. The rules for elaboration given above guarantee
33439that the spec of the subprogram has been elaborated before the
33440call, but not the body. If this rule is violated, then the
33441exception @cite{Program_Error} is raised.
33442
33443@item
33444@emph{Restrictions on instantiations}
33445
33446A generic unit can only be instantiated if the body of the generic
33447unit has been elaborated. Again, the rules for elaboration given above
33448guarantee that the spec of the generic unit has been elaborated
33449before the instantiation, but not the body. If this rule is
33450violated, then the exception @cite{Program_Error} is raised.
33451@end itemize
33452
33453The idea is that if the body has been elaborated, then any variables
33454it references must have been elaborated; by checking for the body being
33455elaborated we guarantee that none of its references causes any
33456trouble. As we noted above, this is a little too restrictive, because a
33457subprogram that has no non-local references in its body may in fact be safe
33458to call. However, it really would be unsafe to rely on this, because
33459it would mean that the caller was aware of details of the implementation
33460in the body. This goes against the basic tenets of Ada.
33461
33462A plausible implementation can be described as follows.
33463A Boolean variable is associated with each subprogram
33464and each generic unit. This variable is initialized to False, and is set to
33465True at the point body is elaborated. Every call or instantiation checks the
33466variable, and raises @cite{Program_Error} if the variable is False.
33467
33468Note that one might think that it would be good enough to have one Boolean
33469variable for each package, but that would not deal with cases of trying
33470to call a body in the same package as the call
33471that has not been elaborated yet.
33472Of course a compiler may be able to do enough analysis to optimize away
33473some of the Boolean variables as unnecessary, and @cite{GNAT} indeed
33474does such optimizations, but still the easiest conceptual model is to
33475think of there being one variable per subprogram.
33476
33477@node Controlling the Elaboration Order,Controlling Elaboration in GNAT - Internal Calls,Checking the Elaboration Order,Elaboration Order Handling in GNAT
33478@anchor{gnat_ugn/elaboration_order_handling_in_gnat id4}@anchor{2c1}@anchor{gnat_ugn/elaboration_order_handling_in_gnat controlling-the-elaboration-order}@anchor{2c2}
33479@section Controlling the Elaboration Order
33480
33481
33482In the previous section we discussed the rules in Ada which ensure
33483that @cite{Program_Error} is raised if an incorrect elaboration order is
33484chosen. This prevents erroneous executions, but we need mechanisms to
33485specify a correct execution and avoid the exception altogether.
33486To achieve this, Ada provides a number of features for controlling
33487the order of elaboration. We discuss these features in this section.
33488
33489First, there are several ways of indicating to the compiler that a given
33490unit has no elaboration problems:
33491
33492
33493@itemize *
33494
33495@item
33496@emph{packages that do not require a body}
33497
33498A library package that does not require a body does not permit
33499a body (this rule was introduced in Ada 95).
33500Thus if we have a such a package, as in:
33501
33502@example
33503package Definitions is
33504   generic
33505      type m is new integer;
33506   package Subp is
33507      type a is array (1 .. 10) of m;
33508      type b is array (1 .. 20) of m;
33509   end Subp;
33510end Definitions;
33511@end example
33512
33513A package that @emph{with}s @cite{Definitions} may safely instantiate
33514@cite{Definitions.Subp} because the compiler can determine that there
33515definitely is no package body to worry about in this case
33516@end itemize
33517
33518@geindex pragma Pure
33519
33520
33521@itemize *
33522
33523@item
33524@emph{pragma Pure}
33525
33526This pragma places sufficient restrictions on a unit to guarantee that
33527no call to any subprogram in the unit can result in an
33528elaboration problem. This means that the compiler does not need
33529to worry about the point of elaboration of such units, and in
33530particular, does not need to check any calls to any subprograms
33531in this unit.
33532@end itemize
33533
33534@geindex pragma Preelaborate
33535
33536
33537@itemize *
33538
33539@item
33540@emph{pragma Preelaborate}
33541
33542This pragma places slightly less stringent restrictions on a unit than
33543does pragma Pure,
33544but these restrictions are still sufficient to ensure that there
33545are no elaboration problems with any calls to the unit.
33546@end itemize
33547
33548@geindex pragma Elaborate_Body
33549
33550
33551@itemize *
33552
33553@item
33554@emph{pragma Elaborate_Body}
33555
33556This pragma requires that the body of a unit be elaborated immediately
33557after its spec. Suppose a unit @cite{A} has such a pragma,
33558and unit @cite{B} does
33559a @emph{with} of unit @cite{A}. Recall that the standard rules require
33560the spec of unit @cite{A}
33561to be elaborated before the @emph{with}ing unit; given the pragma in
33562@cite{A}, we also know that the body of @cite{A}
33563will be elaborated before @cite{B}, so
33564that calls to @cite{A} are safe and do not need a check.
33565
33566Note that, unlike pragma @cite{Pure} and pragma @cite{Preelaborate},
33567the use of @cite{Elaborate_Body} does not guarantee that the program is
33568free of elaboration problems, because it may not be possible
33569to satisfy the requested elaboration order.
33570Let's go back to the example with @cite{Unit_1} and @cite{Unit_2}.
33571If a programmer marks @cite{Unit_1} as @cite{Elaborate_Body},
33572and not @cite{Unit_2@comma{}} then the order of
33573elaboration will be:
33574
33575@example
33576Spec of Unit_2
33577Spec of Unit_1
33578Body of Unit_1
33579Body of Unit_2
33580@end example
33581
33582Now that means that the call to @cite{Func_1} in @cite{Unit_2}
33583need not be checked,
33584it must be safe. But the call to @cite{Func_2} in
33585@cite{Unit_1} may still fail if
33586@cite{Expression_1} is equal to 1,
33587and the programmer must still take
33588responsibility for this not being the case.
33589
33590If all units carry a pragma @cite{Elaborate_Body}, then all problems are
33591eliminated, except for calls entirely within a body, which are
33592in any case fully under programmer control. However, using the pragma
33593everywhere is not always possible.
33594In particular, for our @cite{Unit_1}/@cite{Unit_2} example, if
33595we marked both of them as having pragma @cite{Elaborate_Body}, then
33596clearly there would be no possible elaboration order.
33597@end itemize
33598
33599The above pragmas allow a server to guarantee safe use by clients, and
33600clearly this is the preferable approach. Consequently a good rule
33601is to mark units as @cite{Pure} or @cite{Preelaborate} if possible,
33602and if this is not possible,
33603mark them as @cite{Elaborate_Body} if possible.
33604As we have seen, there are situations where neither of these
33605three pragmas can be used.
33606So we also provide methods for clients to control the
33607order of elaboration of the servers on which they depend:
33608
33609@geindex pragma Elaborate
33610
33611
33612@itemize *
33613
33614@item
33615@emph{pragma Elaborate (unit)}
33616
33617This pragma is placed in the context clause, after a @emph{with} clause,
33618and it requires that the body of the named unit be elaborated before
33619the unit in which the pragma occurs. The idea is to use this pragma
33620if the current unit calls at elaboration time, directly or indirectly,
33621some subprogram in the named unit.
33622@end itemize
33623
33624@geindex pragma Elaborate_All
33625
33626
33627@itemize *
33628
33629@item
33630@emph{pragma Elaborate_All (unit)}
33631
33632This is a stronger version of the Elaborate pragma. Consider the
33633following example:
33634
33635@example
33636Unit A |withs| unit B and calls B.Func in elab code
33637Unit B |withs| unit C, and B.Func calls C.Func
33638@end example
33639
33640Now if we put a pragma @cite{Elaborate (B)}
33641in unit @cite{A}, this ensures that the
33642body of @cite{B} is elaborated before the call, but not the
33643body of @cite{C}, so
33644the call to @cite{C.Func} could still cause @cite{Program_Error} to
33645be raised.
33646
33647The effect of a pragma @cite{Elaborate_All} is stronger, it requires
33648not only that the body of the named unit be elaborated before the
33649unit doing the @emph{with}, but also the bodies of all units that the
33650named unit uses, following @emph{with} links transitively. For example,
33651if we put a pragma @cite{Elaborate_All (B)} in unit @cite{A},
33652then it requires not only that the body of @cite{B} be elaborated before @cite{A},
33653but also the body of @cite{C}, because @cite{B} @emph{with}s @cite{C}.
33654@end itemize
33655
33656We are now in a position to give a usage rule in Ada for avoiding
33657elaboration problems, at least if dynamic dispatching and access to
33658subprogram values are not used. We will handle these cases separately
33659later.
33660
33661The rule is simple:
33662
33663@emph{If a unit has elaboration code that can directly or
33664indirectly make a call to a subprogram in a |withed| unit, or instantiate
33665a generic package in a |withed| unit,
33666then if the |withed| unit does not have
33667pragma `Pure` or `Preelaborate`, then the client should have
33668a pragma `Elaborate_All`for the |withed| unit.*}
33669
33670By following this rule a client is
33671assured that calls can be made without risk of an exception.
33672
33673For generic subprogram instantiations, the rule can be relaxed to
33674require only a pragma @cite{Elaborate} since elaborating the body
33675of a subprogram cannot cause any transitive elaboration (we are
33676not calling the subprogram in this case, just elaborating its
33677declaration).
33678
33679If this rule is not followed, then a program may be in one of four
33680states:
33681
33682
33683@itemize *
33684
33685@item
33686@emph{No order exists}
33687
33688No order of elaboration exists which follows the rules, taking into
33689account any @cite{Elaborate}, @cite{Elaborate_All},
33690or @cite{Elaborate_Body} pragmas. In
33691this case, an Ada compiler must diagnose the situation at bind
33692time, and refuse to build an executable program.
33693
33694@item
33695@emph{One or more orders exist, all incorrect}
33696
33697One or more acceptable elaboration orders exist, and all of them
33698generate an elaboration order problem. In this case, the binder
33699can build an executable program, but @cite{Program_Error} will be raised
33700when the program is run.
33701
33702@item
33703@emph{Several orders exist, some right, some incorrect}
33704
33705One or more acceptable elaboration orders exists, and some of them
33706work, and some do not. The programmer has not controlled
33707the order of elaboration, so the binder may or may not pick one of
33708the correct orders, and the program may or may not raise an
33709exception when it is run. This is the worst case, because it means
33710that the program may fail when moved to another compiler, or even
33711another version of the same compiler.
33712
33713@item
33714@emph{One or more orders exists, all correct}
33715
33716One ore more acceptable elaboration orders exist, and all of them
33717work. In this case the program runs successfully. This state of
33718affairs can be guaranteed by following the rule we gave above, but
33719may be true even if the rule is not followed.
33720@end itemize
33721
33722Note that one additional advantage of following our rules on the use
33723of @cite{Elaborate} and @cite{Elaborate_All}
33724is that the program continues to stay in the ideal (all orders OK) state
33725even if maintenance
33726changes some bodies of some units. Conversely, if a program that does
33727not follow this rule happens to be safe at some point, this state of affairs
33728may deteriorate silently as a result of maintenance changes.
33729
33730You may have noticed that the above discussion did not mention
33731the use of @cite{Elaborate_Body}. This was a deliberate omission. If you
33732@emph{with} an @cite{Elaborate_Body} unit, it still may be the case that
33733code in the body makes calls to some other unit, so it is still necessary
33734to use @cite{Elaborate_All} on such units.
33735
33736@node Controlling Elaboration in GNAT - Internal Calls,Controlling Elaboration in GNAT - External Calls,Controlling the Elaboration Order,Elaboration Order Handling in GNAT
33737@anchor{gnat_ugn/elaboration_order_handling_in_gnat id5}@anchor{2c3}@anchor{gnat_ugn/elaboration_order_handling_in_gnat controlling-elaboration-in-gnat-internal-calls}@anchor{2c4}
33738@section Controlling Elaboration in GNAT - Internal Calls
33739
33740
33741In the case of internal calls, i.e., calls within a single package, the
33742programmer has full control over the order of elaboration, and it is up
33743to the programmer to elaborate declarations in an appropriate order. For
33744example writing:
33745
33746@example
33747function One return Float;
33748
33749Q : Float := One;
33750
33751function One return Float is
33752begin
33753     return 1.0;
33754end One;
33755@end example
33756
33757will obviously raise @cite{Program_Error} at run time, because function
33758One will be called before its body is elaborated. In this case GNAT will
33759generate a warning that the call will raise @cite{Program_Error}:
33760
33761@example
33762 1. procedure y is
33763 2.    function One return Float;
33764 3.
33765 4.    Q : Float := One;
33766                    |
33767    >>> warning: cannot call "One" before body is elaborated
33768    >>> warning: Program_Error will be raised at run time
33769
33770 5.
33771 6.    function One return Float is
33772 7.    begin
33773 8.         return 1.0;
33774 9.    end One;
3377510.
3377611. begin
3377712.    null;
3377813. end;
33779@end example
33780
33781Note that in this particular case, it is likely that the call is safe, because
33782the function @cite{One} does not access any global variables.
33783Nevertheless in Ada, we do not want the validity of the check to depend on
33784the contents of the body (think about the separate compilation case), so this
33785is still wrong, as we discussed in the previous sections.
33786
33787The error is easily corrected by rearranging the declarations so that the
33788body of @cite{One} appears before the declaration containing the call
33789(note that in Ada 95 as well as later versions of the Ada standard,
33790declarations can appear in any order, so there is no restriction that
33791would prevent this reordering, and if we write:
33792
33793@example
33794function One return Float;
33795
33796function One return Float is
33797begin
33798     return 1.0;
33799end One;
33800
33801Q : Float := One;
33802@end example
33803
33804then all is well, no warning is generated, and no
33805@cite{Program_Error} exception
33806will be raised.
33807Things are more complicated when a chain of subprograms is executed:
33808
33809@example
33810function A return Integer;
33811function B return Integer;
33812function C return Integer;
33813
33814function B return Integer is begin return A; end;
33815function C return Integer is begin return B; end;
33816
33817X : Integer := C;
33818
33819function A return Integer is begin return 1; end;
33820@end example
33821
33822Now the call to @cite{C}
33823at elaboration time in the declaration of @cite{X} is correct, because
33824the body of @cite{C} is already elaborated,
33825and the call to @cite{B} within the body of
33826@cite{C} is correct, but the call
33827to @cite{A} within the body of @cite{B} is incorrect, because the body
33828of @cite{A} has not been elaborated, so @cite{Program_Error}
33829will be raised on the call to @cite{A}.
33830In this case GNAT will generate a
33831warning that @cite{Program_Error} may be
33832raised at the point of the call. Let's look at the warning:
33833
33834@example
33835 1. procedure x is
33836 2.    function A return Integer;
33837 3.    function B return Integer;
33838 4.    function C return Integer;
33839 5.
33840 6.    function B return Integer is begin return A; end;
33841                                                    |
33842    >>> warning: call to "A" before body is elaborated may
33843                 raise Program_Error
33844    >>> warning: "B" called at line 7
33845    >>> warning: "C" called at line 9
33846
33847 7.    function C return Integer is begin return B; end;
33848 8.
33849 9.    X : Integer := C;
3385010.
3385111.    function A return Integer is begin return 1; end;
3385212.
3385313. begin
3385414.    null;
3385515. end;
33856@end example
33857
33858Note that the message here says 'may raise', instead of the direct case,
33859where the message says 'will be raised'. That's because whether
33860@cite{A} is
33861actually called depends in general on run-time flow of control.
33862For example, if the body of @cite{B} said
33863
33864@example
33865function B return Integer is
33866begin
33867   if some-condition-depending-on-input-data then
33868      return A;
33869   else
33870      return 1;
33871   end if;
33872end B;
33873@end example
33874
33875then we could not know until run time whether the incorrect call to A would
33876actually occur, so @cite{Program_Error} might
33877or might not be raised. It is possible for a compiler to
33878do a better job of analyzing bodies, to
33879determine whether or not @cite{Program_Error}
33880might be raised, but it certainly
33881couldn't do a perfect job (that would require solving the halting problem
33882and is provably impossible), and because this is a warning anyway, it does
33883not seem worth the effort to do the analysis. Cases in which it
33884would be relevant are rare.
33885
33886In practice, warnings of either of the forms given
33887above will usually correspond to
33888real errors, and should be examined carefully and eliminated.
33889In the rare case where a warning is bogus, it can be suppressed by any of
33890the following methods:
33891
33892
33893@itemize *
33894
33895@item
33896Compile with the @emph{-gnatws} switch set
33897
33898@item
33899Suppress @cite{Elaboration_Check} for the called subprogram
33900
33901@item
33902Use pragma @cite{Warnings_Off} to turn warnings off for the call
33903@end itemize
33904
33905For the internal elaboration check case,
33906GNAT by default generates the
33907necessary run-time checks to ensure
33908that @cite{Program_Error} is raised if any
33909call fails an elaboration check. Of course this can only happen if a
33910warning has been issued as described above. The use of pragma
33911@cite{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
33912some of these checks, meaning that it may be possible (but is not
33913guaranteed) for a program to be able to call a subprogram whose body
33914is not yet elaborated, without raising a @cite{Program_Error} exception.
33915
33916@node Controlling Elaboration in GNAT - External Calls,Default Behavior in GNAT - Ensuring Safety,Controlling Elaboration in GNAT - Internal Calls,Elaboration Order Handling in GNAT
33917@anchor{gnat_ugn/elaboration_order_handling_in_gnat id6}@anchor{2c5}@anchor{gnat_ugn/elaboration_order_handling_in_gnat controlling-elaboration-in-gnat-external-calls}@anchor{2c6}
33918@section Controlling Elaboration in GNAT - External Calls
33919
33920
33921The previous section discussed the case in which the execution of a
33922particular thread of elaboration code occurred entirely within a
33923single unit. This is the easy case to handle, because a programmer
33924has direct and total control over the order of elaboration, and
33925furthermore, checks need only be generated in cases which are rare
33926and which the compiler can easily detect.
33927The situation is more complex when separate compilation is taken into account.
33928Consider the following:
33929
33930@example
33931package Math is
33932   function Sqrt (Arg : Float) return Float;
33933end Math;
33934
33935package body Math is
33936   function Sqrt (Arg : Float) return Float is
33937   begin
33938         ...
33939   end Sqrt;
33940end Math;
33941
33942with Math;
33943package Stuff is
33944   X : Float := Math.Sqrt (0.5);
33945end Stuff;
33946
33947with Stuff;
33948procedure Main is
33949begin
33950   ...
33951end Main;
33952@end example
33953
33954where @cite{Main} is the main program. When this program is executed, the
33955elaboration code must first be executed, and one of the jobs of the
33956binder is to determine the order in which the units of a program are
33957to be elaborated. In this case we have four units: the spec and body
33958of @cite{Math},
33959the spec of @cite{Stuff} and the body of @cite{Main}).
33960In what order should the four separate sections of elaboration code
33961be executed?
33962
33963There are some restrictions in the order of elaboration that the binder
33964can choose. In particular, if unit U has a @emph{with}
33965for a package @cite{X}, then you
33966are assured that the spec of @cite{X}
33967is elaborated before U , but you are
33968not assured that the body of @cite{X}
33969is elaborated before U.
33970This means that in the above case, the binder is allowed to choose the
33971order:
33972
33973@example
33974spec of Math
33975spec of Stuff
33976body of Math
33977body of Main
33978@end example
33979
33980but that's not good, because now the call to @cite{Math.Sqrt}
33981that happens during
33982the elaboration of the @cite{Stuff}
33983spec happens before the body of @cite{Math.Sqrt} is
33984elaborated, and hence causes @cite{Program_Error} exception to be raised.
33985At first glance, one might say that the binder is misbehaving, because
33986obviously you want to elaborate the body of something you @emph{with} first, but
33987that is not a general rule that can be followed in all cases. Consider
33988
33989@example
33990package X is ...
33991
33992package Y is ...
33993
33994with X;
33995package body Y is ...
33996
33997with Y;
33998package body X is ...
33999@end example
34000
34001This is a common arrangement, and, apart from the order of elaboration
34002problems that might arise in connection with elaboration code, this works fine.
34003A rule that says that you must first elaborate the body of anything you
34004@emph{with} cannot work in this case:
34005the body of @cite{X} @emph{with}s @cite{Y},
34006which means you would have to
34007elaborate the body of @cite{Y} first, but that @emph{with}s @cite{X},
34008which means
34009you have to elaborate the body of @cite{X} first, but ... and we have a
34010loop that cannot be broken.
34011
34012It is true that the binder can in many cases guess an order of elaboration
34013that is unlikely to cause a @cite{Program_Error}
34014exception to be raised, and it tries to do so (in the
34015above example of @cite{Math/Stuff/Spec}, the GNAT binder will
34016by default
34017elaborate the body of @cite{Math} right after its spec, so all will be well).
34018
34019However, a program that blindly relies on the binder to be helpful can
34020get into trouble, as we discussed in the previous sections, so GNAT
34021provides a number of facilities for assisting the programmer in
34022developing programs that are robust with respect to elaboration order.
34023
34024@node Default Behavior in GNAT - Ensuring Safety,Treatment of Pragma Elaborate,Controlling Elaboration in GNAT - External Calls,Elaboration Order Handling in GNAT
34025@anchor{gnat_ugn/elaboration_order_handling_in_gnat id7}@anchor{2c7}@anchor{gnat_ugn/elaboration_order_handling_in_gnat default-behavior-in-gnat-ensuring-safety}@anchor{2c8}
34026@section Default Behavior in GNAT - Ensuring Safety
34027
34028
34029The default behavior in GNAT ensures elaboration safety. In its
34030default mode GNAT implements the
34031rule we previously described as the right approach. Let's restate it:
34032
34033@emph{If a unit has elaboration code that can directly or indirectly make a
34034call to a subprogram in a |withed| unit, or instantiate a generic
34035package in a |withed| unit, then if the |withed| unit
34036does not have pragma `Pure` or `Preelaborate`, then the client should have an
34037`Elaborate_All` pragma for the |withed| unit.}
34038
34039@emph{In the case of instantiating a generic subprogram, it is always
34040sufficient to have only an `Elaborate` pragma for the
34041|withed| unit.}
34042
34043By following this rule a client is assured that calls and instantiations
34044can be made without risk of an exception.
34045
34046In this mode GNAT traces all calls that are potentially made from
34047elaboration code, and puts in any missing implicit @cite{Elaborate}
34048and @cite{Elaborate_All} pragmas.
34049The advantage of this approach is that no elaboration problems
34050are possible if the binder can find an elaboration order that is
34051consistent with these implicit @cite{Elaborate} and
34052@cite{Elaborate_All} pragmas. The
34053disadvantage of this approach is that no such order may exist.
34054
34055If the binder does not generate any diagnostics, then it means that it has
34056found an elaboration order that is guaranteed to be safe. However, the binder
34057may still be relying on implicitly generated @cite{Elaborate} and
34058@cite{Elaborate_All} pragmas so portability to other compilers than GNAT is not
34059guaranteed.
34060
34061If it is important to guarantee portability, then the compilations should
34062use the @emph{-gnatel}
34063(info messages for elaboration pragmas) switch. This will cause info messages
34064to be generated indicating the missing @cite{Elaborate} and
34065@cite{Elaborate_All} pragmas.
34066Consider the following source program:
34067
34068@example
34069with k;
34070package j is
34071  m : integer := k.r;
34072end;
34073@end example
34074
34075where it is clear that there
34076should be a pragma @cite{Elaborate_All}
34077for unit @cite{k}. An implicit pragma will be generated, and it is
34078likely that the binder will be able to honor it. However, if you want
34079to port this program to some other Ada compiler than GNAT.
34080it is safer to include the pragma explicitly in the source. If this
34081unit is compiled with the @emph{-gnatel}
34082switch, then the compiler outputs an information message:
34083
34084@example
340851. with k;
340862. package j is
340873.   m : integer := k.r;
34088                     |
34089   >>> info: call to "r" may raise Program_Error
34090   >>> info: missing pragma Elaborate_All for "k"
34091
340924. end;
34093@end example
34094
34095and these messages can be used as a guide for supplying manually
34096the missing pragmas. It is usually a bad idea to use this
34097option during development. That's because it will tell you when
34098you need to put in a pragma, but cannot tell you when it is time
34099to take it out. So the use of pragma @cite{Elaborate_All} may lead to
34100unnecessary dependencies and even false circularities.
34101
34102This default mode is more restrictive than the Ada Reference
34103Manual, and it is possible to construct programs which will compile
34104using the dynamic model described there, but will run into a
34105circularity using the safer static model we have described.
34106
34107Of course any Ada compiler must be able to operate in a mode
34108consistent with the requirements of the Ada Reference Manual,
34109and in particular must have the capability of implementing the
34110standard dynamic model of elaboration with run-time checks.
34111
34112In GNAT, this standard mode can be achieved either by the use of
34113the @emph{-gnatE} switch on the compiler (@emph{gcc} or
34114@emph{gnatmake}) command, or by the use of the configuration pragma:
34115
34116@example
34117pragma Elaboration_Checks (DYNAMIC);
34118@end example
34119
34120Either approach will cause the unit affected to be compiled using the
34121standard dynamic run-time elaboration checks described in the Ada
34122Reference Manual. The static model is generally preferable, since it
34123is clearly safer to rely on compile and link time checks rather than
34124run-time checks. However, in the case of legacy code, it may be
34125difficult to meet the requirements of the static model. This
34126issue is further discussed in
34127@ref{2c9,,What to Do If the Default Elaboration Behavior Fails}.
34128
34129Note that the static model provides a strict subset of the allowed
34130behavior and programs of the Ada Reference Manual, so if you do
34131adhere to the static model and no circularities exist,
34132then you are assured that your program will
34133work using the dynamic model, providing that you remove any
34134pragma Elaborate statements from the source.
34135
34136@node Treatment of Pragma Elaborate,Elaboration Issues for Library Tasks,Default Behavior in GNAT - Ensuring Safety,Elaboration Order Handling in GNAT
34137@anchor{gnat_ugn/elaboration_order_handling_in_gnat treatment-of-pragma-elaborate}@anchor{2ca}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id8}@anchor{2cb}
34138@section Treatment of Pragma Elaborate
34139
34140
34141@geindex Pragma Elaborate
34142
34143The use of @cite{pragma Elaborate}
34144should generally be avoided in Ada 95 and Ada 2005 programs,
34145since there is no guarantee that transitive calls
34146will be properly handled. Indeed at one point, this pragma was placed
34147in Annex J (Obsolescent Features), on the grounds that it is never useful.
34148
34149Now that's a bit restrictive. In practice, the case in which
34150@cite{pragma Elaborate} is useful is when the caller knows that there
34151are no transitive calls, or that the called unit contains all necessary
34152transitive @cite{pragma Elaborate} statements, and legacy code often
34153contains such uses.
34154
34155Strictly speaking the static mode in GNAT should ignore such pragmas,
34156since there is no assurance at compile time that the necessary safety
34157conditions are met. In practice, this would cause GNAT to be incompatible
34158with correctly written Ada 83 code that had all necessary
34159@cite{pragma Elaborate} statements in place. Consequently, we made the
34160decision that GNAT in its default mode will believe that if it encounters
34161a @cite{pragma Elaborate} then the programmer knows what they are doing,
34162and it will trust that no elaboration errors can occur.
34163
34164The result of this decision is two-fold. First to be safe using the
34165static mode, you should remove all @cite{pragma Elaborate} statements.
34166Second, when fixing circularities in existing code, you can selectively
34167use @cite{pragma Elaborate} statements to convince the static mode of
34168GNAT that it need not generate an implicit @cite{pragma Elaborate_All}
34169statement.
34170
34171When using the static mode with @emph{-gnatwl}, any use of
34172@cite{pragma Elaborate} will generate a warning about possible
34173problems.
34174
34175@node Elaboration Issues for Library Tasks,Mixing Elaboration Models,Treatment of Pragma Elaborate,Elaboration Order Handling in GNAT
34176@anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-issues-for-library-tasks}@anchor{2cc}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id9}@anchor{2cd}
34177@section Elaboration Issues for Library Tasks
34178
34179
34180@geindex Library tasks
34181@geindex elaboration issues
34182
34183@geindex Elaboration of library tasks
34184
34185In this section we examine special elaboration issues that arise for
34186programs that declare library level tasks.
34187
34188Generally the model of execution of an Ada program is that all units are
34189elaborated, and then execution of the program starts. However, the
34190declaration of library tasks definitely does not fit this model. The
34191reason for this is that library tasks start as soon as they are declared
34192(more precisely, as soon as the statement part of the enclosing package
34193body is reached), that is to say before elaboration
34194of the program is complete. This means that if such a task calls a
34195subprogram, or an entry in another task, the callee may or may not be
34196elaborated yet, and in the standard
34197Reference Manual model of dynamic elaboration checks, you can even
34198get timing dependent Program_Error exceptions, since there can be
34199a race between the elaboration code and the task code.
34200
34201The static model of elaboration in GNAT seeks to avoid all such
34202dynamic behavior, by being conservative, and the conservative
34203approach in this particular case is to assume that all the code
34204in a task body is potentially executed at elaboration time if
34205a task is declared at the library level.
34206
34207This can definitely result in unexpected circularities. Consider
34208the following example
34209
34210@example
34211package Decls is
34212  task Lib_Task is
34213     entry Start;
34214  end Lib_Task;
34215
34216  type My_Int is new Integer;
34217
34218  function Ident (M : My_Int) return My_Int;
34219end Decls;
34220
34221with Utils;
34222package body Decls is
34223  task body Lib_Task is
34224  begin
34225     accept Start;
34226     Utils.Put_Val (2);
34227  end Lib_Task;
34228
34229  function Ident (M : My_Int) return My_Int is
34230  begin
34231     return M;
34232  end Ident;
34233end Decls;
34234
34235with Decls;
34236package Utils is
34237  procedure Put_Val (Arg : Decls.My_Int);
34238end Utils;
34239
34240with Text_IO;
34241package body Utils is
34242  procedure Put_Val (Arg : Decls.My_Int) is
34243  begin
34244     Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
34245  end Put_Val;
34246end Utils;
34247
34248with Decls;
34249procedure Main is
34250begin
34251   Decls.Lib_Task.Start;
34252end;
34253@end example
34254
34255If the above example is compiled in the default static elaboration
34256mode, then a circularity occurs. The circularity comes from the call
34257@cite{Utils.Put_Val} in the task body of @cite{Decls.Lib_Task}. Since
34258this call occurs in elaboration code, we need an implicit pragma
34259@cite{Elaborate_All} for @cite{Utils}. This means that not only must
34260the spec and body of @cite{Utils} be elaborated before the body
34261of @cite{Decls}, but also the spec and body of any unit that is
34262@emph{with}ed by the body of @cite{Utils} must also be elaborated before
34263the body of @cite{Decls}. This is the transitive implication of
34264pragma @cite{Elaborate_All} and it makes sense, because in general
34265the body of @cite{Put_Val} might have a call to something in a
34266@emph{with}ed unit.
34267
34268In this case, the body of Utils (actually its spec) @emph{with}s
34269@cite{Decls}. Unfortunately this means that the body of @cite{Decls}
34270must be elaborated before itself, in case there is a call from the
34271body of @cite{Utils}.
34272
34273Here is the exact chain of events we are worrying about:
34274
34275
34276@itemize *
34277
34278@item
34279In the body of @cite{Decls} a call is made from within the body of a library
34280task to a subprogram in the package @cite{Utils}. Since this call may
34281occur at elaboration time (given that the task is activated at elaboration
34282time), we have to assume the worst, i.e., that the
34283call does happen at elaboration time.
34284
34285@item
34286This means that the body and spec of @cite{Util} must be elaborated before
34287the body of @cite{Decls} so that this call does not cause an access before
34288elaboration.
34289
34290@item
34291Within the body of @cite{Util}, specifically within the body of
34292@cite{Util.Put_Val} there may be calls to any unit @emph{with}ed
34293by this package.
34294
34295@item
34296One such @emph{with}ed package is package @cite{Decls}, so there
34297might be a call to a subprogram in @cite{Decls} in @cite{Put_Val}.
34298In fact there is such a call in this example, but we would have to
34299assume that there was such a call even if it were not there, since
34300we are not supposed to write the body of @cite{Decls} knowing what
34301is in the body of @cite{Utils}; certainly in the case of the
34302static elaboration model, the compiler does not know what is in
34303other bodies and must assume the worst.
34304
34305@item
34306This means that the spec and body of @cite{Decls} must also be
34307elaborated before we elaborate the unit containing the call, but
34308that unit is @cite{Decls}! This means that the body of @cite{Decls}
34309must be elaborated before itself, and that's a circularity.
34310@end itemize
34311
34312Indeed, if you add an explicit pragma @cite{Elaborate_All} for @cite{Utils} in
34313the body of @cite{Decls} you will get a true Ada Reference Manual
34314circularity that makes the program illegal.
34315
34316In practice, we have found that problems with the static model of
34317elaboration in existing code often arise from library tasks, so
34318we must address this particular situation.
34319
34320Note that if we compile and run the program above, using the dynamic model of
34321elaboration (that is to say use the @emph{-gnatE} switch),
34322then it compiles, binds,
34323links, and runs, printing the expected result of 2. Therefore in some sense
34324the circularity here is only apparent, and we need to capture
34325the properties of this program that  distinguish it from other library-level
34326tasks that have real elaboration problems.
34327
34328We have four possible answers to this question:
34329
34330
34331@itemize *
34332
34333@item
34334Use the dynamic model of elaboration.
34335
34336If we use the @emph{-gnatE} switch, then as noted above, the program works.
34337Why is this? If we examine the task body, it is apparent that the task cannot
34338proceed past the
34339@cite{accept} statement until after elaboration has been completed, because
34340the corresponding entry call comes from the main program, not earlier.
34341This is why the dynamic model works here. But that's really giving
34342up on a precise analysis, and we prefer to take this approach only if we cannot
34343solve the
34344problem in any other manner. So let us examine two ways to reorganize
34345the program to avoid the potential elaboration problem.
34346
34347@item
34348Split library tasks into separate packages.
34349
34350Write separate packages, so that library tasks are isolated from
34351other declarations as much as possible. Let us look at a variation on
34352the above program.
34353
34354@example
34355package Decls1 is
34356  task Lib_Task is
34357     entry Start;
34358  end Lib_Task;
34359end Decls1;
34360
34361with Utils;
34362package body Decls1 is
34363  task body Lib_Task is
34364  begin
34365     accept Start;
34366     Utils.Put_Val (2);
34367  end Lib_Task;
34368end Decls1;
34369
34370package Decls2 is
34371  type My_Int is new Integer;
34372  function Ident (M : My_Int) return My_Int;
34373end Decls2;
34374
34375with Utils;
34376package body Decls2 is
34377  function Ident (M : My_Int) return My_Int is
34378  begin
34379     return M;
34380  end Ident;
34381end Decls2;
34382
34383with Decls2;
34384package Utils is
34385  procedure Put_Val (Arg : Decls2.My_Int);
34386end Utils;
34387
34388with Text_IO;
34389package body Utils is
34390  procedure Put_Val (Arg : Decls2.My_Int) is
34391  begin
34392     Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
34393  end Put_Val;
34394end Utils;
34395
34396with Decls1;
34397procedure Main is
34398begin
34399   Decls1.Lib_Task.Start;
34400end;
34401@end example
34402
34403All we have done is to split @cite{Decls} into two packages, one
34404containing the library task, and one containing everything else. Now
34405there is no cycle, and the program compiles, binds, links and executes
34406using the default static model of elaboration.
34407
34408@item
34409Declare separate task types.
34410
34411A significant part of the problem arises because of the use of the
34412single task declaration form. This means that the elaboration of
34413the task type, and the elaboration of the task itself (i.e., the
34414creation of the task) happen at the same time. A good rule
34415of style in Ada is to always create explicit task types. By
34416following the additional step of placing task objects in separate
34417packages from the task type declaration, many elaboration problems
34418are avoided. Here is another modified example of the example program:
34419
34420@example
34421package Decls is
34422  task type Lib_Task_Type is
34423     entry Start;
34424  end Lib_Task_Type;
34425
34426  type My_Int is new Integer;
34427
34428  function Ident (M : My_Int) return My_Int;
34429end Decls;
34430
34431with Utils;
34432package body Decls is
34433  task body Lib_Task_Type is
34434  begin
34435     accept Start;
34436     Utils.Put_Val (2);
34437  end Lib_Task_Type;
34438
34439  function Ident (M : My_Int) return My_Int is
34440  begin
34441     return M;
34442  end Ident;
34443end Decls;
34444
34445with Decls;
34446package Utils is
34447  procedure Put_Val (Arg : Decls.My_Int);
34448end Utils;
34449
34450with Text_IO;
34451package body Utils is
34452  procedure Put_Val (Arg : Decls.My_Int) is
34453  begin
34454     Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
34455  end Put_Val;
34456end Utils;
34457
34458with Decls;
34459package Declst is
34460   Lib_Task : Decls.Lib_Task_Type;
34461end Declst;
34462
34463with Declst;
34464procedure Main is
34465begin
34466   Declst.Lib_Task.Start;
34467end;
34468@end example
34469
34470What we have done here is to replace the @cite{task} declaration in
34471package @cite{Decls} with a @cite{task type} declaration. Then we
34472introduce a separate package @cite{Declst} to contain the actual
34473task object. This separates the elaboration issues for
34474the @cite{task type}
34475declaration, which causes no trouble, from the elaboration issues
34476of the task object, which is also unproblematic, since it is now independent
34477of the elaboration of  @cite{Utils}.
34478This separation of concerns also corresponds to
34479a generally sound engineering principle of separating declarations
34480from instances. This version of the program also compiles, binds, links,
34481and executes, generating the expected output.
34482@end itemize
34483
34484@geindex No_Entry_Calls_In_Elaboration_Code restriction
34485
34486
34487@itemize *
34488
34489@item
34490Use No_Entry_Calls_In_Elaboration_Code restriction.
34491
34492The previous two approaches described how a program can be restructured
34493to avoid the special problems caused by library task bodies. in practice,
34494however, such restructuring may be difficult to apply to existing legacy code,
34495so we must consider solutions that do not require massive rewriting.
34496
34497Let us consider more carefully why our original sample program works
34498under the dynamic model of elaboration. The reason is that the code
34499in the task body blocks immediately on the @cite{accept}
34500statement. Now of course there is nothing to prohibit elaboration
34501code from making entry calls (for example from another library level task),
34502so we cannot tell in isolation that
34503the task will not execute the accept statement  during elaboration.
34504
34505However, in practice it is very unusual to see elaboration code
34506make any entry calls, and the pattern of tasks starting
34507at elaboration time and then immediately blocking on @cite{accept} or
34508@cite{select} statements is very common. What this means is that
34509the compiler is being too pessimistic when it analyzes the
34510whole package body as though it might be executed at elaboration
34511time.
34512
34513If we know that the elaboration code contains no entry calls, (a very safe
34514assumption most of the time, that could almost be made the default
34515behavior), then we can compile all units of the program under control
34516of the following configuration pragma:
34517
34518@example
34519pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
34520@end example
34521
34522This pragma can be placed in the @code{gnat.adc} file in the usual
34523manner. If we take our original unmodified program and compile it
34524in the presence of a @code{gnat.adc} containing the above pragma,
34525then once again, we can compile, bind, link, and execute, obtaining
34526the expected result. In the presence of this pragma, the compiler does
34527not trace calls in a task body, that appear after the first @cite{accept}
34528or @cite{select} statement, and therefore does not report a potential
34529circularity in the original program.
34530
34531The compiler will check to the extent it can that the above
34532restriction is not violated, but it is not always possible to do a
34533complete check at compile time, so it is important to use this
34534pragma only if the stated restriction is in fact met, that is to say
34535no task receives an entry call before elaboration of all units is completed.
34536@end itemize
34537
34538@node Mixing Elaboration Models,What to Do If the Default Elaboration Behavior Fails,Elaboration Issues for Library Tasks,Elaboration Order Handling in GNAT
34539@anchor{gnat_ugn/elaboration_order_handling_in_gnat id10}@anchor{2ce}@anchor{gnat_ugn/elaboration_order_handling_in_gnat mixing-elaboration-models}@anchor{2cf}
34540@section Mixing Elaboration Models
34541
34542
34543So far, we have assumed that the entire program is either compiled
34544using the dynamic model or static model, ensuring consistency. It
34545is possible to mix the two models, but rules have to be followed
34546if this mixing is done to ensure that elaboration checks are not
34547omitted.
34548
34549The basic rule is that
34550@strong{a unit compiled with the static model cannot
34551be |withed| by a unit compiled with the dynamic model}.
34552The reason for this is that in the static model, a unit assumes that
34553its clients guarantee to use (the equivalent of) pragma
34554@cite{Elaborate_All} so that no elaboration checks are required
34555in inner subprograms, and this assumption is violated if the
34556client is compiled with dynamic checks.
34557
34558The precise rule is as follows. A unit that is compiled with dynamic
34559checks can only @emph{with} a unit that meets at least one of the
34560following criteria:
34561
34562
34563@itemize *
34564
34565@item
34566The @emph{with}ed unit is itself compiled with dynamic elaboration
34567checks (that is with the @emph{-gnatE} switch.
34568
34569@item
34570The @emph{with}ed unit is an internal GNAT implementation unit from
34571the System, Interfaces, Ada, or GNAT hierarchies.
34572
34573@item
34574The @emph{with}ed unit has pragma Preelaborate or pragma Pure.
34575
34576@item
34577The @emph{with}ing unit (that is the client) has an explicit pragma
34578@cite{Elaborate_All} for the @emph{with}ed unit.
34579@end itemize
34580
34581If this rule is violated, that is if a unit with dynamic elaboration
34582checks @emph{with}s a unit that does not meet one of the above four
34583criteria, then the binder (@cite{gnatbind}) will issue a warning
34584similar to that in the following example:
34585
34586@example
34587warning: "x.ads" has dynamic elaboration checks and with's
34588warning:   "y.ads" which has static elaboration checks
34589@end example
34590
34591These warnings indicate that the rule has been violated, and that as a result
34592elaboration checks may be missed in the resulting executable file.
34593This warning may be suppressed using the @emph{-ws} binder switch
34594in the usual manner.
34595
34596One useful application of this mixing rule is in the case of a subsystem
34597which does not itself @emph{with} units from the remainder of the
34598application. In this case, the entire subsystem can be compiled with
34599dynamic checks to resolve a circularity in the subsystem, while
34600allowing the main application that uses this subsystem to be compiled
34601using the more reliable default static model.
34602
34603@node What to Do If the Default Elaboration Behavior Fails,Elaboration for Indirect Calls,Mixing Elaboration Models,Elaboration Order Handling in GNAT
34604@anchor{gnat_ugn/elaboration_order_handling_in_gnat id11}@anchor{2d0}@anchor{gnat_ugn/elaboration_order_handling_in_gnat what-to-do-if-the-default-elaboration-behavior-fails}@anchor{2c9}
34605@section What to Do If the Default Elaboration Behavior Fails
34606
34607
34608If the binder cannot find an acceptable order, it outputs detailed
34609diagnostics. For example:
34610
34611@example
34612error: elaboration circularity detected
34613info:   "proc (body)" must be elaborated before "pack (body)"
34614info:     reason: Elaborate_All probably needed in unit "pack (body)"
34615info:     recompile "pack (body)" with -gnatel
34616info:                             for full details
34617info:       "proc (body)"
34618info:         is needed by its spec:
34619info:       "proc (spec)"
34620info:         which is withed by:
34621info:       "pack (body)"
34622info:  "pack (body)" must be elaborated before "proc (body)"
34623info:     reason: pragma Elaborate in unit "proc (body)"
34624@end example
34625
34626In this case we have a cycle that the binder cannot break. On the one
34627hand, there is an explicit pragma Elaborate in @cite{proc} for
34628@cite{pack}. This means that the body of @cite{pack} must be elaborated
34629before the body of @cite{proc}. On the other hand, there is elaboration
34630code in @cite{pack} that calls a subprogram in @cite{proc}. This means
34631that for maximum safety, there should really be a pragma
34632Elaborate_All in @cite{pack} for @cite{proc} which would require that
34633the body of @cite{proc} be elaborated before the body of
34634@cite{pack}. Clearly both requirements cannot be satisfied.
34635Faced with a circularity of this kind, you have three different options.
34636
34637
34638@itemize *
34639
34640@item
34641@emph{Fix the program}
34642
34643The most desirable option from the point of view of long-term maintenance
34644is to rearrange the program so that the elaboration problems are avoided.
34645One useful technique is to place the elaboration code into separate
34646child packages. Another is to move some of the initialization code to
34647explicitly called subprograms, where the program controls the order
34648of initialization explicitly. Although this is the most desirable option,
34649it may be impractical and involve too much modification, especially in
34650the case of complex legacy code.
34651
34652@item
34653@emph{Perform dynamic checks}
34654
34655If the compilations are done using the @emph{-gnatE}
34656(dynamic elaboration check) switch, then GNAT behaves in a quite different
34657manner. Dynamic checks are generated for all calls that could possibly result
34658in raising an exception. With this switch, the compiler does not generate
34659implicit @cite{Elaborate} or @cite{Elaborate_All} pragmas. The behavior then is
34660exactly as specified in the @cite{Ada Reference Manual}.
34661The binder will generate
34662an executable program that may or may not raise @cite{Program_Error}, and then
34663it is the programmer's job to ensure that it does not raise an exception. Note
34664that it is important to compile all units with the switch, it cannot be used
34665selectively.
34666
34667@item
34668@emph{Suppress checks}
34669
34670The drawback of dynamic checks is that they generate a
34671significant overhead at run time, both in space and time. If you
34672are absolutely sure that your program cannot raise any elaboration
34673exceptions, and you still want to use the dynamic elaboration model,
34674then you can use the configuration pragma
34675@cite{Suppress (Elaboration_Check)} to suppress all such checks. For
34676example this pragma could be placed in the @code{gnat.adc} file.
34677
34678@item
34679@emph{Suppress checks selectively}
34680
34681When you know that certain calls or instantiations in elaboration code cannot
34682possibly lead to an elaboration error, and the binder nevertheless complains
34683about implicit @cite{Elaborate} and @cite{Elaborate_All} pragmas that lead to
34684elaboration circularities, it is possible to remove those warnings locally and
34685obtain a program that will bind. Clearly this can be unsafe, and it is the
34686responsibility of the programmer to make sure that the resulting program has no
34687elaboration anomalies. The pragma @cite{Suppress (Elaboration_Check)} can be
34688used with different granularity to suppress warnings and break elaboration
34689circularities:
34690
34691
34692@itemize *
34693
34694@item
34695Place the pragma that names the called subprogram in the declarative part
34696that contains the call.
34697
34698@item
34699Place the pragma in the declarative part, without naming an entity. This
34700disables warnings on all calls in the corresponding  declarative region.
34701
34702@item
34703Place the pragma in the package spec that declares the called subprogram,
34704and name the subprogram. This disables warnings on all elaboration calls to
34705that subprogram.
34706
34707@item
34708Place the pragma in the package spec that declares the called subprogram,
34709without naming any entity. This disables warnings on all elaboration calls to
34710all subprograms declared in this spec.
34711
34712@item
34713Use Pragma Elaborate.
34714
34715As previously described in section @ref{2ca,,Treatment of Pragma Elaborate},
34716GNAT in static mode assumes that a @cite{pragma} Elaborate indicates correctly
34717that no elaboration checks are required on calls to the designated unit.
34718There may be cases in which the caller knows that no transitive calls
34719can occur, so that a @cite{pragma Elaborate} will be sufficient in a
34720case where @cite{pragma Elaborate_All} would cause a circularity.
34721@end itemize
34722
34723These five cases are listed in order of decreasing safety, and therefore
34724require increasing programmer care in their application. Consider the
34725following program:
34726
34727@example
34728package Pack1 is
34729  function F1 return Integer;
34730  X1 : Integer;
34731end Pack1;
34732
34733package Pack2 is
34734  function F2 return Integer;
34735  function Pure (x : integer) return integer;
34736  --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
34737  --  pragma Suppress (Elaboration_Check);              -- (4)
34738end Pack2;
34739
34740with Pack2;
34741package body Pack1 is
34742  function F1 return Integer is
34743  begin
34744    return 100;
34745  end F1;
34746  Val : integer := Pack2.Pure (11);    --  Elab. call (1)
34747begin
34748  declare
34749    --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
34750    --  pragma Suppress(Elaboration_Check);             -- (2)
34751  begin
34752    X1 := Pack2.F2 + 1;                --  Elab. call (2)
34753  end;
34754end Pack1;
34755
34756with Pack1;
34757package body Pack2 is
34758  function F2 return Integer is
34759  begin
34760     return Pack1.F1;
34761  end F2;
34762  function Pure (x : integer) return integer is
34763  begin
34764     return x ** 3 - 3 * x;
34765  end;
34766end Pack2;
34767
34768with Pack1, Ada.Text_IO;
34769procedure Proc3 is
34770begin
34771  Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
34772end Proc3;
34773@end example
34774
34775In the absence of any pragmas, an attempt to bind this program produces
34776the following diagnostics:
34777
34778@example
34779error: elaboration circularity detected
34780info:    "pack1 (body)" must be elaborated before "pack1 (body)"
34781info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
34782info:       recompile "pack1 (body)" with -gnatel for full details
34783info:          "pack1 (body)"
34784info:             must be elaborated along with its spec:
34785info:          "pack1 (spec)"
34786info:             which is withed by:
34787info:          "pack2 (body)"
34788info:             which must be elaborated along with its spec:
34789info:          "pack2 (spec)"
34790info:             which is withed by:
34791info:          "pack1 (body)"
34792@end example
34793
34794The sources of the circularity are the two calls to @cite{Pack2.Pure} and
34795@cite{Pack2.F2} in the body of @cite{Pack1}. We can see that the call to
34796F2 is safe, even though F2 calls F1, because the call appears after the
34797elaboration of the body of F1. Therefore the pragma (1) is safe, and will
34798remove the warning on the call. It is also possible to use pragma (2)
34799because there are no other potentially unsafe calls in the block.
34800
34801The call to @cite{Pure} is safe because this function does not depend on the
34802state of @cite{Pack2}. Therefore any call to this function is safe, and it
34803is correct to place pragma (3) in the corresponding package spec.
34804
34805Finally, we could place pragma (4) in the spec of @cite{Pack2} to disable
34806warnings on all calls to functions declared therein. Note that this is not
34807necessarily safe, and requires more detailed examination of the subprogram
34808bodies involved. In particular, a call to @cite{F2} requires that @cite{F1}
34809be already elaborated.
34810@end itemize
34811
34812It is hard to generalize on which of these four approaches should be
34813taken. Obviously if it is possible to fix the program so that the default
34814treatment works, this is preferable, but this may not always be practical.
34815It is certainly simple enough to use @emph{-gnatE}
34816but the danger in this case is that, even if the GNAT binder
34817finds a correct elaboration order, it may not always do so,
34818and certainly a binder from another Ada compiler might not. A
34819combination of testing and analysis (for which the
34820information messages generated with the @emph{-gnatel}
34821switch can be useful) must be used to ensure that the program is free
34822of errors. One switch that is useful in this testing is the
34823@emph{-p (pessimistic elaboration order)} switch for @cite{gnatbind}.
34824Normally the binder tries to find an order that has the best chance
34825of avoiding elaboration problems. However, if this switch is used, the binder
34826plays a devil's advocate role, and tries to choose the order that
34827has the best chance of failing. If your program works even with this
34828switch, then it has a better chance of being error free, but this is still
34829not a guarantee.
34830
34831For an example of this approach in action, consider the C-tests (executable
34832tests) from the ACATS suite. If these are compiled and run with the default
34833treatment, then all but one of them succeed without generating any error
34834diagnostics from the binder. However, there is one test that fails, and
34835this is not surprising, because the whole point of this test is to ensure
34836that the compiler can handle cases where it is impossible to determine
34837a correct order statically, and it checks that an exception is indeed
34838raised at run time.
34839
34840This one test must be compiled and run using the @emph{-gnatE}
34841switch, and then it passes. Alternatively, the entire suite can
34842be run using this switch. It is never wrong to run with the dynamic
34843elaboration switch if your code is correct, and we assume that the
34844C-tests are indeed correct (it is less efficient, but efficiency is
34845not a factor in running the ACATS tests.)
34846
34847@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
34848@anchor{gnat_ugn/elaboration_order_handling_in_gnat id12}@anchor{2d1}@anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-for-indirect-calls}@anchor{2d2}
34849@section Elaboration for Indirect Calls
34850
34851
34852@geindex Dispatching calls
34853
34854@geindex Indirect calls
34855
34856In rare cases, the static elaboration model fails to prevent
34857dispatching calls to not-yet-elaborated subprograms. In such cases, we
34858fall back to run-time checks; premature calls to any primitive
34859operation of a tagged type before the body of the operation has been
34860elaborated will raise @cite{Program_Error}.
34861
34862Access-to-subprogram types, however, are handled conservatively, and
34863do not require run-time checks. This was not true in earlier versions
34864of the compiler; you can use the @emph{-gnatd.U} debug switch to
34865revert to the old behavior if the new conservative behavior causes
34866elaboration cycles. Here, 'conservative' means that if you do
34867@cite{P'Access} during elaboration, the compiler will assume that you
34868might call @cite{P} indirectly during elaboration, so it adds an
34869implicit @cite{pragma Elaborate_All} on the library unit containing
34870@cite{P}. The @emph{-gnatd.U} switch is safe if you know there are
34871no such calls. If the program worked before, it will continue to work
34872with @emph{-gnatd.U}. But beware that code modifications such as
34873adding an indirect call can cause erroneous behavior in the presence
34874of @emph{-gnatd.U}.
34875
34876@node Summary of Procedures for Elaboration Control,Other Elaboration Order Considerations,Elaboration for Indirect Calls,Elaboration Order Handling in GNAT
34877@anchor{gnat_ugn/elaboration_order_handling_in_gnat id13}@anchor{2d3}@anchor{gnat_ugn/elaboration_order_handling_in_gnat summary-of-procedures-for-elaboration-control}@anchor{2d4}
34878@section Summary of Procedures for Elaboration Control
34879
34880
34881@geindex Elaboration control
34882
34883First, compile your program with the default options, using none of
34884the special elaboration control switches. If the binder successfully
34885binds your program, then you can be confident that, apart from issues
34886raised by the use of access-to-subprogram types and dynamic dispatching,
34887the program is free of elaboration errors. If it is important that the
34888program be portable to other compilers than GNAT, then use the
34889@emph{-gnatel}
34890switch to generate messages about missing @cite{Elaborate} or
34891@cite{Elaborate_All} pragmas, and supply the missing pragmas.
34892
34893If the program fails to bind using the default static elaboration
34894handling, then you can fix the program to eliminate the binder
34895message, or recompile the entire program with the
34896@emph{-gnatE} switch to generate dynamic elaboration checks,
34897and, if you are sure there really are no elaboration problems,
34898use a global pragma @cite{Suppress (Elaboration_Check)}.
34899
34900@node Other Elaboration Order Considerations,Determining the Chosen Elaboration Order,Summary of Procedures for Elaboration Control,Elaboration Order Handling in GNAT
34901@anchor{gnat_ugn/elaboration_order_handling_in_gnat id14}@anchor{2d5}@anchor{gnat_ugn/elaboration_order_handling_in_gnat other-elaboration-order-considerations}@anchor{2d6}
34902@section Other Elaboration Order Considerations
34903
34904
34905This section has been entirely concerned with the issue of finding a valid
34906elaboration order, as defined by the Ada Reference Manual. In a case
34907where several elaboration orders are valid, the task is to find one
34908of the possible valid elaboration orders (and the static model in GNAT
34909will ensure that this is achieved).
34910
34911The purpose of the elaboration rules in the Ada Reference Manual is to
34912make sure that no entity is accessed before it has been elaborated. For
34913a subprogram, this means that the spec and body must have been elaborated
34914before the subprogram is called. For an object, this means that the object
34915must have been elaborated before its value is read or written. A violation
34916of either of these two requirements is an access before elaboration order,
34917and this section has been all about avoiding such errors.
34918
34919In the case where more than one order of elaboration is possible, in the
34920sense that access before elaboration errors are avoided, then any one of
34921the orders is 'correct' in the sense that it meets the requirements of
34922the Ada Reference Manual, and no such error occurs.
34923
34924However, it may be the case for a given program, that there are
34925constraints on the order of elaboration that come not from consideration
34926of avoiding elaboration errors, but rather from extra-lingual logic
34927requirements. Consider this example:
34928
34929@example
34930with Init_Constants;
34931package Constants is
34932   X : Integer := 0;
34933   Y : Integer := 0;
34934end Constants;
34935
34936package Init_Constants is
34937   procedure P; --* require a body*
34938end Init_Constants;
34939
34940with Constants;
34941package body Init_Constants is
34942   procedure P is begin null; end;
34943begin
34944   Constants.X := 3;
34945   Constants.Y := 4;
34946end Init_Constants;
34947
34948with Constants;
34949package Calc is
34950   Z : Integer := Constants.X + Constants.Y;
34951end Calc;
34952
34953with Calc;
34954with Text_IO; use Text_IO;
34955procedure Main is
34956begin
34957   Put_Line (Calc.Z'Img);
34958end Main;
34959@end example
34960
34961In this example, there is more than one valid order of elaboration. For
34962example both the following are correct orders:
34963
34964@example
34965Init_Constants spec
34966Constants spec
34967Calc spec
34968Init_Constants body
34969Main body
34970@end example
34971
34972and
34973
34974@example
34975Init_Constants spec
34976Init_Constants body
34977Constants spec
34978Calc spec
34979Main body
34980@end example
34981
34982There is no language rule to prefer one or the other, both are correct
34983from an order of elaboration point of view. But the programmatic effects
34984of the two orders are very different. In the first, the elaboration routine
34985of @cite{Calc} initializes @cite{Z} to zero, and then the main program
34986runs with this value of zero. But in the second order, the elaboration
34987routine of @cite{Calc} runs after the body of Init_Constants has set
34988@cite{X} and @cite{Y} and thus @cite{Z} is set to 7 before @cite{Main} runs.
34989
34990One could perhaps by applying pretty clever non-artificial intelligence
34991to the situation guess that it is more likely that the second order of
34992elaboration is the one desired, but there is no formal linguistic reason
34993to prefer one over the other. In fact in this particular case, GNAT will
34994prefer the second order, because of the rule that bodies are elaborated
34995as soon as possible, but it's just luck that this is what was wanted
34996(if indeed the second order was preferred).
34997
34998If the program cares about the order of elaboration routines in a case like
34999this, it is important to specify the order required. In this particular
35000case, that could have been achieved by adding to the spec of Calc:
35001
35002@example
35003pragma Elaborate_All (Constants);
35004@end example
35005
35006which requires that the body (if any) and spec of @cite{Constants},
35007as well as the body and spec of any unit @emph{with}ed by
35008@cite{Constants} be elaborated before @cite{Calc} is elaborated.
35009
35010Clearly no automatic method can always guess which alternative you require,
35011and if you are working with legacy code that had constraints of this kind
35012which were not properly specified by adding @cite{Elaborate} or
35013@cite{Elaborate_All} pragmas, then indeed it is possible that two different
35014compilers can choose different orders.
35015
35016However, GNAT does attempt to diagnose the common situation where there
35017are uninitialized variables in the visible part of a package spec, and the
35018corresponding package body has an elaboration block that directly or
35019indirectly initialized one or more of these variables. This is the situation
35020in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
35021a warning that suggests this addition if it detects this situation.
35022
35023The @cite{gnatbind} @emph{-p} switch may be useful in smoking
35024out problems. This switch causes bodies to be elaborated as late as possible
35025instead of as early as possible. In the example above, it would have forced
35026the choice of the first elaboration order. If you get different results
35027when using this switch, and particularly if one set of results is right,
35028and one is wrong as far as you are concerned, it shows that you have some
35029missing @cite{Elaborate} pragmas. For the example above, we have the
35030following output:
35031
35032@example
35033$ gnatmake -f -q main
35034$ main
35035 7
35036$ gnatmake -f -q main -bargs -p
35037$ main
35038 0
35039@end example
35040
35041It is of course quite unlikely that both these results are correct, so
35042it is up to you in a case like this to investigate the source of the
35043difference, by looking at the two elaboration orders that are chosen,
35044and figuring out which is correct, and then adding the necessary
35045@cite{Elaborate} or @cite{Elaborate_All} pragmas to ensure the desired order.
35046
35047@node Determining the Chosen Elaboration Order,,Other Elaboration Order Considerations,Elaboration Order Handling in GNAT
35048@anchor{gnat_ugn/elaboration_order_handling_in_gnat determining-the-chosen-elaboration-order}@anchor{2d7}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id15}@anchor{2d8}
35049@section Determining the Chosen Elaboration Order
35050
35051
35052To see the elaboration order that the binder chooses, you can look at
35053the last part of the file:@cite{b~xxx.adb} binder output file. Here is an example:
35054
35055@example
35056System.Soft_Links'Elab_Body;
35057E14 := True;
35058System.Secondary_Stack'Elab_Body;
35059E18 := True;
35060System.Exception_Table'Elab_Body;
35061E24 := True;
35062Ada.Io_Exceptions'Elab_Spec;
35063E67 := True;
35064Ada.Tags'Elab_Spec;
35065Ada.Streams'Elab_Spec;
35066E43 := True;
35067Interfaces.C'Elab_Spec;
35068E69 := True;
35069System.Finalization_Root'Elab_Spec;
35070E60 := True;
35071System.Os_Lib'Elab_Body;
35072E71 := True;
35073System.Finalization_Implementation'Elab_Spec;
35074System.Finalization_Implementation'Elab_Body;
35075E62 := True;
35076Ada.Finalization'Elab_Spec;
35077E58 := True;
35078Ada.Finalization.List_Controller'Elab_Spec;
35079E76 := True;
35080System.File_Control_Block'Elab_Spec;
35081E74 := True;
35082System.File_Io'Elab_Body;
35083E56 := True;
35084Ada.Tags'Elab_Body;
35085E45 := True;
35086Ada.Text_Io'Elab_Spec;
35087Ada.Text_Io'Elab_Body;
35088E07 := True;
35089@end example
35090
35091Here Elab_Spec elaborates the spec
35092and Elab_Body elaborates the body. The assignments to the @code{E@emph{xx}} flags
35093flag that the corresponding body is now elaborated.
35094
35095You can also ask the binder to generate a more
35096readable list of the elaboration order using the
35097@cite{-l} switch when invoking the binder. Here is
35098an example of the output generated by this switch:
35099
35100@example
35101ada (spec)
35102interfaces (spec)
35103system (spec)
35104system.case_util (spec)
35105system.case_util (body)
35106system.concat_2 (spec)
35107system.concat_2 (body)
35108system.concat_3 (spec)
35109system.concat_3 (body)
35110system.htable (spec)
35111system.parameters (spec)
35112system.parameters (body)
35113system.crtl (spec)
35114interfaces.c_streams (spec)
35115interfaces.c_streams (body)
35116system.restrictions (spec)
35117system.restrictions (body)
35118system.standard_library (spec)
35119system.exceptions (spec)
35120system.exceptions (body)
35121system.storage_elements (spec)
35122system.storage_elements (body)
35123system.secondary_stack (spec)
35124system.stack_checking (spec)
35125system.stack_checking (body)
35126system.string_hash (spec)
35127system.string_hash (body)
35128system.htable (body)
35129system.strings (spec)
35130system.strings (body)
35131system.traceback (spec)
35132system.traceback (body)
35133system.traceback_entries (spec)
35134system.traceback_entries (body)
35135ada.exceptions (spec)
35136ada.exceptions.last_chance_handler (spec)
35137system.soft_links (spec)
35138system.soft_links (body)
35139ada.exceptions.last_chance_handler (body)
35140system.secondary_stack (body)
35141system.exception_table (spec)
35142system.exception_table (body)
35143ada.io_exceptions (spec)
35144ada.tags (spec)
35145ada.streams (spec)
35146interfaces.c (spec)
35147interfaces.c (body)
35148system.finalization_root (spec)
35149system.finalization_root (body)
35150system.memory (spec)
35151system.memory (body)
35152system.standard_library (body)
35153system.os_lib (spec)
35154system.os_lib (body)
35155system.unsigned_types (spec)
35156system.stream_attributes (spec)
35157system.stream_attributes (body)
35158system.finalization_implementation (spec)
35159system.finalization_implementation (body)
35160ada.finalization (spec)
35161ada.finalization (body)
35162ada.finalization.list_controller (spec)
35163ada.finalization.list_controller (body)
35164system.file_control_block (spec)
35165system.file_io (spec)
35166system.file_io (body)
35167system.val_uns (spec)
35168system.val_util (spec)
35169system.val_util (body)
35170system.val_uns (body)
35171system.wch_con (spec)
35172system.wch_con (body)
35173system.wch_cnv (spec)
35174system.wch_jis (spec)
35175system.wch_jis (body)
35176system.wch_cnv (body)
35177system.wch_stw (spec)
35178system.wch_stw (body)
35179ada.tags (body)
35180ada.exceptions (body)
35181ada.text_io (spec)
35182ada.text_io (body)
35183text_io (spec)
35184gdbstr (body)
35185@end example
35186
35187@node Inline Assembler,GNU Free Documentation License,Elaboration Order Handling in GNAT,Top
35188@anchor{gnat_ugn/inline_assembler inline-assembler}@anchor{12}@anchor{gnat_ugn/inline_assembler doc}@anchor{2d9}@anchor{gnat_ugn/inline_assembler id1}@anchor{2da}
35189@chapter Inline Assembler
35190
35191
35192@geindex Inline Assembler
35193
35194If you need to write low-level software that interacts directly
35195with the hardware, Ada provides two ways to incorporate assembly
35196language code into your program.  First, you can import and invoke
35197external routines written in assembly language, an Ada feature fully
35198supported by GNAT.  However, for small sections of code it may be simpler
35199or more efficient to include assembly language statements directly
35200in your Ada source program, using the facilities of the implementation-defined
35201package @cite{System.Machine_Code}, which incorporates the gcc
35202Inline Assembler.  The Inline Assembler approach offers a number of advantages,
35203including the following:
35204
35205
35206@itemize *
35207
35208@item
35209No need to use non-Ada tools
35210
35211@item
35212Consistent interface over different targets
35213
35214@item
35215Automatic usage of the proper calling conventions
35216
35217@item
35218Access to Ada constants and variables
35219
35220@item
35221Definition of intrinsic routines
35222
35223@item
35224Possibility of inlining a subprogram comprising assembler code
35225
35226@item
35227Code optimizer can take Inline Assembler code into account
35228@end itemize
35229
35230This appendix presents a series of examples to show you how to use
35231the Inline Assembler.  Although it focuses on the Intel x86,
35232the general approach applies also to other processors.
35233It is assumed that you are familiar with Ada
35234and with assembly language programming.
35235
35236@menu
35237* Basic Assembler Syntax::
35238* A Simple Example of Inline Assembler::
35239* Output Variables in Inline Assembler::
35240* Input Variables in Inline Assembler::
35241* Inlining Inline Assembler Code::
35242* Other Asm Functionality::
35243
35244@end menu
35245
35246@node Basic Assembler Syntax,A Simple Example of Inline Assembler,,Inline Assembler
35247@anchor{gnat_ugn/inline_assembler id2}@anchor{2db}@anchor{gnat_ugn/inline_assembler basic-assembler-syntax}@anchor{2dc}
35248@section Basic Assembler Syntax
35249
35250
35251The assembler used by GNAT and gcc is based not on the Intel assembly
35252language, but rather on a language that descends from the AT&T Unix
35253assembler @emph{as} (and which is often referred to as 'AT&T syntax').
35254The following table summarizes the main features of @emph{as} syntax
35255and points out the differences from the Intel conventions.
35256See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
35257pre-processor) documentation for further information.
35258
35259
35260@display
35261@emph{Register names}@w{ }
35262@display
35263gcc / @emph{as}: Prefix with '%'; for example @cite{%eax}@w{ }
35264Intel: No extra punctuation; for example @cite{eax}@w{ }
35265@end display
35266@end display
35267
35268
35269
35270
35271@display
35272@emph{Immediate operand}@w{ }
35273@display
35274gcc / @emph{as}: Prefix with '$'; for example @cite{$4}@w{ }
35275Intel: No extra punctuation; for example @cite{4}@w{ }
35276@end display
35277@end display
35278
35279
35280
35281
35282@display
35283@emph{Address}@w{ }
35284@display
35285gcc / @emph{as}: Prefix with '$'; for example @cite{$loc}@w{ }
35286Intel: No extra punctuation; for example @cite{loc}@w{ }
35287@end display
35288@end display
35289
35290
35291
35292
35293@display
35294@emph{Memory contents}@w{ }
35295@display
35296gcc / @emph{as}: No extra punctuation; for example @cite{loc}@w{ }
35297Intel: Square brackets; for example @cite{[loc]}@w{ }
35298@end display
35299@end display
35300
35301
35302
35303
35304@display
35305@emph{Register contents}@w{ }
35306@display
35307gcc / @emph{as}: Parentheses; for example @cite{(%eax)}@w{ }
35308Intel: Square brackets; for example @cite{[eax]}@w{ }
35309@end display
35310@end display
35311
35312
35313
35314
35315@display
35316@emph{Hexadecimal numbers}@w{ }
35317@display
35318gcc / @emph{as}: Leading '0x' (C language syntax); for example @cite{0xA0}@w{ }
35319Intel: Trailing 'h'; for example @cite{A0h}@w{ }
35320@end display
35321@end display
35322
35323
35324
35325
35326@display
35327@emph{Operand size}@w{ }
35328@display
35329gcc / @emph{as}: Explicit in op code; for example @cite{movw} to move a 16-bit word@w{ }
35330Intel: Implicit, deduced by assembler; for example @cite{mov}@w{ }
35331@end display
35332@end display
35333
35334
35335
35336
35337@display
35338@emph{Instruction repetition}@w{ }
35339@display
35340gcc / @emph{as}: Split into two lines; for example@w{ }
35341@display
35342@cite{rep}@w{ }
35343@cite{stosl}@w{ }
35344@end display
35345Intel: Keep on one line; for example @cite{rep stosl}@w{ }
35346@end display
35347@end display
35348
35349
35350
35351
35352@display
35353@emph{Order of operands}@w{ }
35354@display
35355gcc / @emph{as}: Source first; for example @cite{movw $4@comma{} %eax}@w{ }
35356Intel: Destination first; for example @cite{mov eax@comma{} 4}@w{ }
35357@end display
35358@end display
35359
35360
35361
35362@node A Simple Example of Inline Assembler,Output Variables in Inline Assembler,Basic Assembler Syntax,Inline Assembler
35363@anchor{gnat_ugn/inline_assembler a-simple-example-of-inline-assembler}@anchor{2dd}@anchor{gnat_ugn/inline_assembler id3}@anchor{2de}
35364@section A Simple Example of Inline Assembler
35365
35366
35367The following example will generate a single assembly language statement,
35368@cite{nop}, which does nothing.  Despite its lack of run-time effect,
35369the example will be useful in illustrating the basics of
35370the Inline Assembler facility.
35371
35372@quotation
35373
35374@example
35375with System.Machine_Code; use System.Machine_Code;
35376procedure Nothing is
35377begin
35378   Asm ("nop");
35379end Nothing;
35380@end example
35381@end quotation
35382
35383@cite{Asm} is a procedure declared in package @cite{System.Machine_Code};
35384here it takes one parameter, a @emph{template string} that must be a static
35385expression and that will form the generated instruction.
35386@cite{Asm} may be regarded as a compile-time procedure that parses
35387the template string and additional parameters (none here),
35388from which it generates a sequence of assembly language instructions.
35389
35390The examples in this chapter will illustrate several of the forms
35391for invoking @cite{Asm}; a complete specification of the syntax
35392is found in the @cite{Machine_Code_Insertions} section of the
35393@cite{GNAT Reference Manual}.
35394
35395Under the standard GNAT conventions, the @cite{Nothing} procedure
35396should be in a file named @code{nothing.adb}.
35397You can build the executable in the usual way:
35398
35399@quotation
35400
35401@example
35402$ gnatmake nothing
35403@end example
35404@end quotation
35405
35406However, the interesting aspect of this example is not its run-time behavior
35407but rather the generated assembly code.
35408To see this output, invoke the compiler as follows:
35409
35410@quotation
35411
35412@example
35413$  gcc -c -S -fomit-frame-pointer -gnatp nothing.adb
35414@end example
35415@end quotation
35416
35417where the options are:
35418
35419
35420@itemize *
35421
35422@item
35423
35424@table @asis
35425
35426@item @code{-c}
35427
35428compile only (no bind or link)
35429@end table
35430
35431@item
35432
35433@table @asis
35434
35435@item @code{-S}
35436
35437generate assembler listing
35438@end table
35439
35440@item
35441
35442@table @asis
35443
35444@item @code{-fomit-frame-pointer}
35445
35446do not set up separate stack frames
35447@end table
35448
35449@item
35450
35451@table @asis
35452
35453@item @code{-gnatp}
35454
35455do not add runtime checks
35456@end table
35457@end itemize
35458
35459This gives a human-readable assembler version of the code. The resulting
35460file will have the same name as the Ada source file, but with a @cite{.s}
35461extension. In our example, the file @code{nothing.s} has the following
35462contents:
35463
35464@quotation
35465
35466@example
35467.file "nothing.adb"
35468gcc2_compiled.:
35469___gnu_compiled_ada:
35470.text
35471   .align 4
35472.globl __ada_nothing
35473__ada_nothing:
35474#APP
35475   nop
35476#NO_APP
35477   jmp L1
35478   .align 2,0x90
35479L1:
35480   ret
35481@end example
35482@end quotation
35483
35484The assembly code you included is clearly indicated by
35485the compiler, between the @cite{#APP} and @cite{#NO_APP}
35486delimiters. The character before the 'APP' and 'NOAPP'
35487can differ on different targets. For example, GNU/Linux uses '#APP' while
35488on NT you will see '/APP'.
35489
35490If you make a mistake in your assembler code (such as using the
35491wrong size modifier, or using a wrong operand for the instruction) GNAT
35492will report this error in a temporary file, which will be deleted when
35493the compilation is finished.  Generating an assembler file will help
35494in such cases, since you can assemble this file separately using the
35495@emph{as} assembler that comes with gcc.
35496
35497Assembling the file using the command
35498
35499@quotation
35500
35501@example
35502$ as nothing.s
35503@end example
35504@end quotation
35505
35506will give you error messages whose lines correspond to the assembler
35507input file, so you can easily find and correct any mistakes you made.
35508If there are no errors, @emph{as} will generate an object file
35509@code{nothing.out}.
35510
35511@node Output Variables in Inline Assembler,Input Variables in Inline Assembler,A Simple Example of Inline Assembler,Inline Assembler
35512@anchor{gnat_ugn/inline_assembler id4}@anchor{2df}@anchor{gnat_ugn/inline_assembler output-variables-in-inline-assembler}@anchor{2e0}
35513@section Output Variables in Inline Assembler
35514
35515
35516The examples in this section, showing how to access the processor flags,
35517illustrate how to specify the destination operands for assembly language
35518statements.
35519
35520@quotation
35521
35522@example
35523with Interfaces; use Interfaces;
35524with Ada.Text_IO; use Ada.Text_IO;
35525with System.Machine_Code; use System.Machine_Code;
35526procedure Get_Flags is
35527   Flags : Unsigned_32;
35528   use ASCII;
35529begin
35530   Asm ("pushfl"          & LF & HT & -- push flags on stack
35531        "popl %%eax"      & LF & HT & -- load eax with flags
35532        "movl %%eax, %0",             -- store flags in variable
35533        Outputs => Unsigned_32'Asm_Output ("=g", Flags));
35534   Put_Line ("Flags register:" & Flags'Img);
35535end Get_Flags;
35536@end example
35537@end quotation
35538
35539In order to have a nicely aligned assembly listing, we have separated
35540multiple assembler statements in the Asm template string with linefeed
35541(ASCII.LF) and horizontal tab (ASCII.HT) characters.
35542The resulting section of the assembly output file is:
35543
35544@quotation
35545
35546@example
35547#APP
35548   pushfl
35549   popl %eax
35550   movl %eax, -40(%ebp)
35551#NO_APP
35552@end example
35553@end quotation
35554
35555It would have been legal to write the Asm invocation as:
35556
35557@quotation
35558
35559@example
35560Asm ("pushfl popl %%eax movl %%eax, %0")
35561@end example
35562@end quotation
35563
35564but in the generated assembler file, this would come out as:
35565
35566@quotation
35567
35568@example
35569#APP
35570   pushfl popl %eax movl %eax, -40(%ebp)
35571#NO_APP
35572@end example
35573@end quotation
35574
35575which is not so convenient for the human reader.
35576
35577We use Ada comments
35578at the end of each line to explain what the assembler instructions
35579actually do.  This is a useful convention.
35580
35581When writing Inline Assembler instructions, you need to precede each register
35582and variable name with a percent sign.  Since the assembler already requires
35583a percent sign at the beginning of a register name, you need two consecutive
35584percent signs for such names in the Asm template string, thus @cite{%%eax}.
35585In the generated assembly code, one of the percent signs will be stripped off.
35586
35587Names such as @cite{%0}, @cite{%1}, @cite{%2}, etc., denote input or output
35588variables: operands you later define using @cite{Input} or @cite{Output}
35589parameters to @cite{Asm}.
35590An output variable is illustrated in
35591the third statement in the Asm template string:
35592
35593@quotation
35594
35595@example
35596movl %%eax, %0
35597@end example
35598@end quotation
35599
35600The intent is to store the contents of the eax register in a variable that can
35601be accessed in Ada.  Simply writing @cite{movl %%eax@comma{} Flags} would not
35602necessarily work, since the compiler might optimize by using a register
35603to hold Flags, and the expansion of the @cite{movl} instruction would not be
35604aware of this optimization.  The solution is not to store the result directly
35605but rather to advise the compiler to choose the correct operand form;
35606that is the purpose of the @cite{%0} output variable.
35607
35608Information about the output variable is supplied in the @cite{Outputs}
35609parameter to @cite{Asm}:
35610
35611@quotation
35612
35613@example
35614Outputs => Unsigned_32'Asm_Output ("=g", Flags));
35615@end example
35616@end quotation
35617
35618The output is defined by the @cite{Asm_Output} attribute of the target type;
35619the general format is
35620
35621@quotation
35622
35623@example
35624Type'Asm_Output (constraint_string, variable_name)
35625@end example
35626@end quotation
35627
35628The constraint string directs the compiler how
35629to store/access the associated variable.  In the example
35630
35631@quotation
35632
35633@example
35634Unsigned_32'Asm_Output ("=m", Flags);
35635@end example
35636@end quotation
35637
35638the @cite{"m"} (memory) constraint tells the compiler that the variable
35639@cite{Flags} should be stored in a memory variable, thus preventing
35640the optimizer from keeping it in a register.  In contrast,
35641
35642@quotation
35643
35644@example
35645Unsigned_32'Asm_Output ("=r", Flags);
35646@end example
35647@end quotation
35648
35649uses the @cite{"r"} (register) constraint, telling the compiler to
35650store the variable in a register.
35651
35652If the constraint is preceded by the equal character '=', it tells
35653the compiler that the variable will be used to store data into it.
35654
35655In the @cite{Get_Flags} example, we used the @cite{"g"} (global) constraint,
35656allowing the optimizer to choose whatever it deems best.
35657
35658There are a fairly large number of constraints, but the ones that are
35659most useful (for the Intel x86 processor) are the following:
35660
35661@quotation
35662
35663
35664@multitable {xxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
35665@item
35666
35667@emph{=}
35668
35669@tab
35670
35671output constraint
35672
35673@item
35674
35675@emph{g}
35676
35677@tab
35678
35679global (i.e., can be stored anywhere)
35680
35681@item
35682
35683@emph{m}
35684
35685@tab
35686
35687in memory
35688
35689@item
35690
35691@emph{I}
35692
35693@tab
35694
35695a constant
35696
35697@item
35698
35699@emph{a}
35700
35701@tab
35702
35703use eax
35704
35705@item
35706
35707@emph{b}
35708
35709@tab
35710
35711use ebx
35712
35713@item
35714
35715@emph{c}
35716
35717@tab
35718
35719use ecx
35720
35721@item
35722
35723@emph{d}
35724
35725@tab
35726
35727use edx
35728
35729@item
35730
35731@emph{S}
35732
35733@tab
35734
35735use esi
35736
35737@item
35738
35739@emph{D}
35740
35741@tab
35742
35743use edi
35744
35745@item
35746
35747@emph{r}
35748
35749@tab
35750
35751use one of eax, ebx, ecx or edx
35752
35753@item
35754
35755@emph{q}
35756
35757@tab
35758
35759use one of eax, ebx, ecx, edx, esi or edi
35760
35761@end multitable
35762
35763@end quotation
35764
35765The full set of constraints is described in the gcc and @emph{as}
35766documentation; note that it is possible to combine certain constraints
35767in one constraint string.
35768
35769You specify the association of an output variable with an assembler operand
35770through the @code{%@emph{n}} notation, where @emph{n} is a non-negative
35771integer.  Thus in
35772
35773@quotation
35774
35775@example
35776Asm ("pushfl"          & LF & HT & -- push flags on stack
35777     "popl %%eax"      & LF & HT & -- load eax with flags
35778     "movl %%eax, %0",             -- store flags in variable
35779     Outputs => Unsigned_32'Asm_Output ("=g", Flags));
35780@end example
35781@end quotation
35782
35783@cite{%0} will be replaced in the expanded code by the appropriate operand,
35784whatever
35785the compiler decided for the @cite{Flags} variable.
35786
35787In general, you may have any number of output variables:
35788
35789
35790@itemize *
35791
35792@item
35793Count the operands starting at 0; thus @cite{%0}, @cite{%1}, etc.
35794
35795@item
35796Specify the @cite{Outputs} parameter as a parenthesized comma-separated list
35797of @cite{Asm_Output} attributes
35798@end itemize
35799
35800For example:
35801
35802@quotation
35803
35804@example
35805Asm ("movl %%eax, %0" & LF & HT &
35806     "movl %%ebx, %1" & LF & HT &
35807     "movl %%ecx, %2",
35808     Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
35809                 Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
35810                 Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
35811@end example
35812@end quotation
35813
35814where @cite{Var_A}, @cite{Var_B}, and @cite{Var_C} are variables
35815in the Ada program.
35816
35817As a variation on the @cite{Get_Flags} example, we can use the constraints
35818string to direct the compiler to store the eax register into the @cite{Flags}
35819variable, instead of including the store instruction explicitly in the
35820@cite{Asm} template string:
35821
35822@quotation
35823
35824@example
35825with Interfaces; use Interfaces;
35826with Ada.Text_IO; use Ada.Text_IO;
35827with System.Machine_Code; use System.Machine_Code;
35828procedure Get_Flags_2 is
35829   Flags : Unsigned_32;
35830   use ASCII;
35831begin
35832   Asm ("pushfl"      & LF & HT & -- push flags on stack
35833        "popl %%eax",             -- save flags in eax
35834        Outputs => Unsigned_32'Asm_Output ("=a", Flags));
35835   Put_Line ("Flags register:" & Flags'Img);
35836end Get_Flags_2;
35837@end example
35838@end quotation
35839
35840The @cite{"a"} constraint tells the compiler that the @cite{Flags}
35841variable will come from the eax register. Here is the resulting code:
35842
35843@quotation
35844
35845@example
35846#APP
35847   pushfl
35848   popl %eax
35849#NO_APP
35850   movl %eax,-40(%ebp)
35851@end example
35852@end quotation
35853
35854The compiler generated the store of eax into Flags after
35855expanding the assembler code.
35856
35857Actually, there was no need to pop the flags into the eax register;
35858more simply, we could just pop the flags directly into the program variable:
35859
35860@quotation
35861
35862@example
35863with Interfaces; use Interfaces;
35864with Ada.Text_IO; use Ada.Text_IO;
35865with System.Machine_Code; use System.Machine_Code;
35866procedure Get_Flags_3 is
35867   Flags : Unsigned_32;
35868   use ASCII;
35869begin
35870   Asm ("pushfl"  & LF & HT & -- push flags on stack
35871        "pop %0",             -- save flags in Flags
35872        Outputs => Unsigned_32'Asm_Output ("=g", Flags));
35873   Put_Line ("Flags register:" & Flags'Img);
35874end Get_Flags_3;
35875@end example
35876@end quotation
35877
35878@node Input Variables in Inline Assembler,Inlining Inline Assembler Code,Output Variables in Inline Assembler,Inline Assembler
35879@anchor{gnat_ugn/inline_assembler id5}@anchor{2e1}@anchor{gnat_ugn/inline_assembler input-variables-in-inline-assembler}@anchor{2e2}
35880@section Input Variables in Inline Assembler
35881
35882
35883The example in this section illustrates how to specify the source operands
35884for assembly language statements.
35885The program simply increments its input value by 1:
35886
35887@quotation
35888
35889@example
35890with Interfaces; use Interfaces;
35891with Ada.Text_IO; use Ada.Text_IO;
35892with System.Machine_Code; use System.Machine_Code;
35893procedure Increment is
35894
35895   function Incr (Value : Unsigned_32) return Unsigned_32 is
35896      Result : Unsigned_32;
35897   begin
35898      Asm ("incl %0",
35899           Outputs => Unsigned_32'Asm_Output ("=a", Result),
35900           Inputs  => Unsigned_32'Asm_Input ("a", Value));
35901      return Result;
35902   end Incr;
35903
35904   Value : Unsigned_32;
35905
35906begin
35907   Value := 5;
35908   Put_Line ("Value before is" & Value'Img);
35909   Value := Incr (Value);
35910  Put_Line ("Value after is" & Value'Img);
35911end Increment;
35912@end example
35913@end quotation
35914
35915The @cite{Outputs} parameter to @cite{Asm} specifies
35916that the result will be in the eax register and that it is to be stored
35917in the @cite{Result} variable.
35918
35919The @cite{Inputs} parameter looks much like the @cite{Outputs} parameter,
35920but with an @cite{Asm_Input} attribute.
35921The @cite{"="} constraint, indicating an output value, is not present.
35922
35923You can have multiple input variables, in the same way that you can have more
35924than one output variable.
35925
35926The parameter count (%0, %1) etc, still starts at the first output statement,
35927and continues with the input statements.
35928
35929Just as the @cite{Outputs} parameter causes the register to be stored into the
35930target variable after execution of the assembler statements, so does the
35931@cite{Inputs} parameter cause its variable to be loaded into the register
35932before execution of the assembler statements.
35933
35934Thus the effect of the @cite{Asm} invocation is:
35935
35936
35937@itemize *
35938
35939@item
35940load the 32-bit value of @cite{Value} into eax
35941
35942@item
35943execute the @cite{incl %eax} instruction
35944
35945@item
35946store the contents of eax into the @cite{Result} variable
35947@end itemize
35948
35949The resulting assembler file (with @emph{-O2} optimization) contains:
35950
35951@quotation
35952
35953@example
35954_increment__incr.1:
35955   subl $4,%esp
35956   movl 8(%esp),%eax
35957#APP
35958   incl %eax
35959#NO_APP
35960   movl %eax,%edx
35961   movl %ecx,(%esp)
35962   addl $4,%esp
35963   ret
35964@end example
35965@end quotation
35966
35967@node Inlining Inline Assembler Code,Other Asm Functionality,Input Variables in Inline Assembler,Inline Assembler
35968@anchor{gnat_ugn/inline_assembler id6}@anchor{2e3}@anchor{gnat_ugn/inline_assembler inlining-inline-assembler-code}@anchor{2e4}
35969@section Inlining Inline Assembler Code
35970
35971
35972For a short subprogram such as the @cite{Incr} function in the previous
35973section, the overhead of the call and return (creating / deleting the stack
35974frame) can be significant, compared to the amount of code in the subprogram
35975body.  A solution is to apply Ada's @cite{Inline} pragma to the subprogram,
35976which directs the compiler to expand invocations of the subprogram at the
35977point(s) of call, instead of setting up a stack frame for out-of-line calls.
35978Here is the resulting program:
35979
35980@quotation
35981
35982@example
35983with Interfaces; use Interfaces;
35984with Ada.Text_IO; use Ada.Text_IO;
35985with System.Machine_Code; use System.Machine_Code;
35986procedure Increment_2 is
35987
35988   function Incr (Value : Unsigned_32) return Unsigned_32 is
35989      Result : Unsigned_32;
35990   begin
35991      Asm ("incl %0",
35992           Outputs => Unsigned_32'Asm_Output ("=a", Result),
35993           Inputs  => Unsigned_32'Asm_Input ("a", Value));
35994      return Result;
35995   end Incr;
35996   pragma Inline (Increment);
35997
35998   Value : Unsigned_32;
35999
36000begin
36001   Value := 5;
36002   Put_Line ("Value before is" & Value'Img);
36003   Value := Increment (Value);
36004   Put_Line ("Value after is" & Value'Img);
36005end Increment_2;
36006@end example
36007@end quotation
36008
36009Compile the program with both optimization (@emph{-O2}) and inlining
36010(@emph{-gnatn}) enabled.
36011
36012The @cite{Incr} function is still compiled as usual, but at the
36013point in @cite{Increment} where our function used to be called:
36014
36015@quotation
36016
36017@example
36018pushl %edi
36019call _increment__incr.1
36020@end example
36021@end quotation
36022
36023the code for the function body directly appears:
36024
36025@quotation
36026
36027@example
36028movl %esi,%eax
36029#APP
36030   incl %eax
36031#NO_APP
36032   movl %eax,%edx
36033@end example
36034@end quotation
36035
36036thus saving the overhead of stack frame setup and an out-of-line call.
36037
36038@node Other Asm Functionality,,Inlining Inline Assembler Code,Inline Assembler
36039@anchor{gnat_ugn/inline_assembler other-asm-functionality}@anchor{2e5}@anchor{gnat_ugn/inline_assembler id7}@anchor{2e6}
36040@section Other @cite{Asm} Functionality
36041
36042
36043This section describes two important parameters to the @cite{Asm}
36044procedure: @cite{Clobber}, which identifies register usage;
36045and @cite{Volatile}, which inhibits unwanted optimizations.
36046
36047@menu
36048* The Clobber Parameter::
36049* The Volatile Parameter::
36050
36051@end menu
36052
36053@node The Clobber Parameter,The Volatile Parameter,,Other Asm Functionality
36054@anchor{gnat_ugn/inline_assembler the-clobber-parameter}@anchor{2e7}@anchor{gnat_ugn/inline_assembler id8}@anchor{2e8}
36055@subsection The @cite{Clobber} Parameter
36056
36057
36058One of the dangers of intermixing assembly language and a compiled language
36059such as Ada is that the compiler needs to be aware of which registers are
36060being used by the assembly code.  In some cases, such as the earlier examples,
36061the constraint string is sufficient to indicate register usage (e.g.,
36062@cite{"a"} for
36063the eax register).  But more generally, the compiler needs an explicit
36064identification of the registers that are used by the Inline Assembly
36065statements.
36066
36067Using a register that the compiler doesn't know about
36068could be a side effect of an instruction (like @cite{mull}
36069storing its result in both eax and edx).
36070It can also arise from explicit register usage in your
36071assembly code; for example:
36072
36073@quotation
36074
36075@example
36076Asm ("movl %0, %%ebx" & LF & HT &
36077     "movl %%ebx, %1",
36078     Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
36079     Inputs  => Unsigned_32'Asm_Input  ("g", Var_In));
36080@end example
36081@end quotation
36082
36083where the compiler (since it does not analyze the @cite{Asm} template string)
36084does not know you are using the ebx register.
36085
36086In such cases you need to supply the @cite{Clobber} parameter to @cite{Asm},
36087to identify the registers that will be used by your assembly code:
36088
36089@quotation
36090
36091@example
36092Asm ("movl %0, %%ebx" & LF & HT &
36093     "movl %%ebx, %1",
36094     Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
36095     Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
36096     Clobber => "ebx");
36097@end example
36098@end quotation
36099
36100The Clobber parameter is a static string expression specifying the
36101register(s) you are using.  Note that register names are @emph{not} prefixed
36102by a percent sign. Also, if more than one register is used then their names
36103are separated by commas; e.g., @cite{"eax@comma{} ebx"}
36104
36105The @cite{Clobber} parameter has several additional uses:
36106
36107
36108@itemize *
36109
36110@item
36111Use 'register' name @cite{cc} to indicate that flags might have changed
36112
36113@item
36114Use 'register' name @cite{memory} if you changed a memory location
36115@end itemize
36116
36117@node The Volatile Parameter,,The Clobber Parameter,Other Asm Functionality
36118@anchor{gnat_ugn/inline_assembler the-volatile-parameter}@anchor{2e9}@anchor{gnat_ugn/inline_assembler id9}@anchor{2ea}
36119@subsection The @cite{Volatile} Parameter
36120
36121
36122@geindex Volatile parameter
36123
36124Compiler optimizations in the presence of Inline Assembler may sometimes have
36125unwanted effects.  For example, when an @cite{Asm} invocation with an input
36126variable is inside a loop, the compiler might move the loading of the input
36127variable outside the loop, regarding it as a one-time initialization.
36128
36129If this effect is not desired, you can disable such optimizations by setting
36130the @cite{Volatile} parameter to @cite{True}; for example:
36131
36132@quotation
36133
36134@example
36135Asm ("movl %0, %%ebx" & LF & HT &
36136     "movl %%ebx, %1",
36137     Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
36138     Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
36139     Clobber  => "ebx",
36140     Volatile => True);
36141@end example
36142@end quotation
36143
36144By default, @cite{Volatile} is set to @cite{False} unless there is no
36145@cite{Outputs} parameter.
36146
36147Although setting @cite{Volatile} to @cite{True} prevents unwanted
36148optimizations, it will also disable other optimizations that might be
36149important for efficiency. In general, you should set @cite{Volatile}
36150to @cite{True} only if the compiler's optimizations have created
36151problems.
36152
36153@node GNU Free Documentation License,Index,Inline Assembler,Top
36154@anchor{share/gnu_free_documentation_license gnu-fdl}@anchor{1}@anchor{share/gnu_free_documentation_license doc}@anchor{2eb}@anchor{share/gnu_free_documentation_license gnu-free-documentation-license}@anchor{2ec}
36155@chapter GNU Free Documentation License
36156
36157
36158Version 1.3, 3 November 2008
36159
36160Copyright  2000, 2001, 2002, 2007, 2008  Free Software Foundation, Inc
36161@indicateurl{http://fsf.org/}
36162
36163Everyone is permitted to copy and distribute verbatim copies of this
36164license document, but changing it is not allowed.
36165
36166@strong{Preamble}
36167
36168The purpose of this License is to make a manual, textbook, or other
36169functional and useful document "free" in the sense of freedom: to
36170assure everyone the effective freedom to copy and redistribute it,
36171with or without modifying it, either commercially or noncommercially.
36172Secondarily, this License preserves for the author and publisher a way
36173to get credit for their work, while not being considered responsible
36174for modifications made by others.
36175
36176This License is a kind of "copyleft", which means that derivative
36177works of the document must themselves be free in the same sense.  It
36178complements the GNU General Public License, which is a copyleft
36179license designed for free software.
36180
36181We have designed this License in order to use it for manuals for free
36182software, because free software needs free documentation: a free
36183program should come with manuals providing the same freedoms that the
36184software does.  But this License is not limited to software manuals;
36185it can be used for any textual work, regardless of subject matter or
36186whether it is published as a printed book.  We recommend this License
36187principally for works whose purpose is instruction or reference.
36188
36189@strong{1. APPLICABILITY AND DEFINITIONS}
36190
36191This License applies to any manual or other work, in any medium, that
36192contains a notice placed by the copyright holder saying it can be
36193distributed under the terms of this License.  Such a notice grants a
36194world-wide, royalty-free license, unlimited in duration, to use that
36195work under the conditions stated herein.  The @strong{Document}, below,
36196refers to any such manual or work.  Any member of the public is a
36197licensee, and is addressed as "@strong{you}".  You accept the license if you
36198copy, modify or distribute the work in a way requiring permission
36199under copyright law.
36200
36201A "@strong{Modified Version}" of the Document means any work containing the
36202Document or a portion of it, either copied verbatim, or with
36203modifications and/or translated into another language.
36204
36205A "@strong{Secondary Section}" is a named appendix or a front-matter section of
36206the Document that deals exclusively with the relationship of the
36207publishers or authors of the Document to the Document's overall subject
36208(or to related matters) and contains nothing that could fall directly
36209within that overall subject.  (Thus, if the Document is in part a
36210textbook of mathematics, a Secondary Section may not explain any
36211mathematics.)  The relationship could be a matter of historical
36212connection with the subject or with related matters, or of legal,
36213commercial, philosophical, ethical or political position regarding
36214them.
36215
36216The "@strong{Invariant Sections}" are certain Secondary Sections whose titles
36217are designated, as being those of Invariant Sections, in the notice
36218that says that the Document is released under this License.  If a
36219section does not fit the above definition of Secondary then it is not
36220allowed to be designated as Invariant.  The Document may contain zero
36221Invariant Sections.  If the Document does not identify any Invariant
36222Sections then there are none.
36223
36224The "@strong{Cover Texts}" are certain short passages of text that are listed,
36225as Front-Cover Texts or Back-Cover Texts, in the notice that says that
36226the Document is released under this License.  A Front-Cover Text may
36227be at most 5 words, and a Back-Cover Text may be at most 25 words.
36228
36229A "@strong{Transparent}" copy of the Document means a machine-readable copy,
36230represented in a format whose specification is available to the
36231general public, that is suitable for revising the document
36232straightforwardly with generic text editors or (for images composed of
36233pixels) generic paint programs or (for drawings) some widely available
36234drawing editor, and that is suitable for input to text formatters or
36235for automatic translation to a variety of formats suitable for input
36236to text formatters.  A copy made in an otherwise Transparent file
36237format whose markup, or absence of markup, has been arranged to thwart
36238or discourage subsequent modification by readers is not Transparent.
36239An image format is not Transparent if used for any substantial amount
36240of text.  A copy that is not "Transparent" is called @strong{Opaque}.
36241
36242Examples of suitable formats for Transparent copies include plain
36243ASCII without markup, Texinfo input format, LaTeX input format, SGML
36244or XML using a publicly available DTD, and standard-conforming simple
36245HTML, PostScript or PDF designed for human modification.  Examples of
36246transparent image formats include PNG, XCF and JPG.  Opaque formats
36247include proprietary formats that can be read and edited only by
36248proprietary word processors, SGML or XML for which the DTD and/or
36249processing tools are not generally available, and the
36250machine-generated HTML, PostScript or PDF produced by some word
36251processors for output purposes only.
36252
36253The "@strong{Title Page}" means, for a printed book, the title page itself,
36254plus such following pages as are needed to hold, legibly, the material
36255this License requires to appear in the title page.  For works in
36256formats which do not have any title page as such, "Title Page" means
36257the text near the most prominent appearance of the work's title,
36258preceding the beginning of the body of the text.
36259
36260The "@strong{publisher}" means any person or entity that distributes
36261copies of the Document to the public.
36262
36263A section "@strong{Entitled XYZ}" means a named subunit of the Document whose
36264title either is precisely XYZ or contains XYZ in parentheses following
36265text that translates XYZ in another language.  (Here XYZ stands for a
36266specific section name mentioned below, such as "@strong{Acknowledgements}",
36267"@strong{Dedications}", "@strong{Endorsements}", or "@strong{History}".)
36268To "@strong{Preserve the Title}"
36269of such a section when you modify the Document means that it remains a
36270section "Entitled XYZ" according to this definition.
36271
36272The Document may include Warranty Disclaimers next to the notice which
36273states that this License applies to the Document.  These Warranty
36274Disclaimers are considered to be included by reference in this
36275License, but only as regards disclaiming warranties: any other
36276implication that these Warranty Disclaimers may have is void and has
36277no effect on the meaning of this License.
36278
36279@strong{2. VERBATIM COPYING}
36280
36281You may copy and distribute the Document in any medium, either
36282commercially or noncommercially, provided that this License, the
36283copyright notices, and the license notice saying this License applies
36284to the Document are reproduced in all copies, and that you add no other
36285conditions whatsoever to those of this License.  You may not use
36286technical measures to obstruct or control the reading or further
36287copying of the copies you make or distribute.  However, you may accept
36288compensation in exchange for copies.  If you distribute a large enough
36289number of copies you must also follow the conditions in section 3.
36290
36291You may also lend copies, under the same conditions stated above, and
36292you may publicly display copies.
36293
36294@strong{3. COPYING IN QUANTITY}
36295
36296If you publish printed copies (or copies in media that commonly have
36297printed covers) of the Document, numbering more than 100, and the
36298Document's license notice requires Cover Texts, you must enclose the
36299copies in covers that carry, clearly and legibly, all these Cover
36300Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on
36301the back cover.  Both covers must also clearly and legibly identify
36302you as the publisher of these copies.  The front cover must present
36303the full title with all words of the title equally prominent and
36304visible.  You may add other material on the covers in addition.
36305Copying with changes limited to the covers, as long as they preserve
36306the title of the Document and satisfy these conditions, can be treated
36307as verbatim copying in other respects.
36308
36309If the required texts for either cover are too voluminous to fit
36310legibly, you should put the first ones listed (as many as fit
36311reasonably) on the actual cover, and continue the rest onto adjacent
36312pages.
36313
36314If you publish or distribute Opaque copies of the Document numbering
36315more than 100, you must either include a machine-readable Transparent
36316copy along with each Opaque copy, or state in or with each Opaque copy
36317a computer-network location from which the general network-using
36318public has access to download using public-standard network protocols
36319a complete Transparent copy of the Document, free of added material.
36320If you use the latter option, you must take reasonably prudent steps,
36321when you begin distribution of Opaque copies in quantity, to ensure
36322that this Transparent copy will remain thus accessible at the stated
36323location until at least one year after the last time you distribute an
36324Opaque copy (directly or through your agents or retailers) of that
36325edition to the public.
36326
36327It is requested, but not required, that you contact the authors of the
36328Document well before redistributing any large number of copies, to give
36329them a chance to provide you with an updated version of the Document.
36330
36331@strong{4. MODIFICATIONS}
36332
36333You may copy and distribute a Modified Version of the Document under
36334the conditions of sections 2 and 3 above, provided that you release
36335the Modified Version under precisely this License, with the Modified
36336Version filling the role of the Document, thus licensing distribution
36337and modification of the Modified Version to whoever possesses a copy
36338of it.  In addition, you must do these things in the Modified Version:
36339
36340
36341@enumerate A
36342
36343@item
36344Use in the Title Page (and on the covers, if any) a title distinct
36345from that of the Document, and from those of previous versions
36346(which should, if there were any, be listed in the History section
36347of the Document).  You may use the same title as a previous version
36348if the original publisher of that version gives permission.
36349
36350@item
36351List on the Title Page, as authors, one or more persons or entities
36352responsible for authorship of the modifications in the Modified
36353Version, together with at least five of the principal authors of the
36354Document (all of its principal authors, if it has fewer than five),
36355unless they release you from this requirement.
36356
36357@item
36358State on the Title page the name of the publisher of the
36359Modified Version, as the publisher.
36360
36361@item
36362Preserve all the copyright notices of the Document.
36363
36364@item
36365Add an appropriate copyright notice for your modifications
36366adjacent to the other copyright notices.
36367
36368@item
36369Include, immediately after the copyright notices, a license notice
36370giving the public permission to use the Modified Version under the
36371terms of this License, in the form shown in the Addendum below.
36372
36373@item
36374Preserve in that license notice the full lists of Invariant Sections
36375and required Cover Texts given in the Document's license notice.
36376
36377@item
36378Include an unaltered copy of this License.
36379
36380@item
36381Preserve the section Entitled "History", Preserve its Title, and add
36382to it an item stating at least the title, year, new authors, and
36383publisher of the Modified Version as given on the Title Page.  If
36384there is no section Entitled "History" in the Document, create one
36385stating the title, year, authors, and publisher of the Document as
36386given on its Title Page, then add an item describing the Modified
36387Version as stated in the previous sentence.
36388
36389@item
36390Preserve the network location, if any, given in the Document for
36391public access to a Transparent copy of the Document, and likewise
36392the network locations given in the Document for previous versions
36393it was based on.  These may be placed in the "History" section.
36394You may omit a network location for a work that was published at
36395least four years before the Document itself, or if the original
36396publisher of the version it refers to gives permission.
36397
36398@item
36399For any section Entitled "Acknowledgements" or "Dedications",
36400Preserve the Title of the section, and preserve in the section all
36401the substance and tone of each of the contributor acknowledgements
36402and/or dedications given therein.
36403
36404@item
36405Preserve all the Invariant Sections of the Document,
36406unaltered in their text and in their titles.  Section numbers
36407or the equivalent are not considered part of the section titles.
36408
36409@item
36410Delete any section Entitled "Endorsements".  Such a section
36411may not be included in the Modified Version.
36412
36413@item
36414Do not retitle any existing section to be Entitled "Endorsements"
36415or to conflict in title with any Invariant Section.
36416
36417@item
36418Preserve any Warranty Disclaimers.
36419@end enumerate
36420
36421If the Modified Version includes new front-matter sections or
36422appendices that qualify as Secondary Sections and contain no material
36423copied from the Document, you may at your option designate some or all
36424of these sections as invariant.  To do this, add their titles to the
36425list of Invariant Sections in the Modified Version's license notice.
36426These titles must be distinct from any other section titles.
36427
36428You may add a section Entitled "Endorsements", provided it contains
36429nothing but endorsements of your Modified Version by various
36430parties---for example, statements of peer review or that the text has
36431been approved by an organization as the authoritative definition of a
36432standard.
36433
36434You may add a passage of up to five words as a Front-Cover Text, and a
36435passage of up to 25 words as a Back-Cover Text, to the end of the list
36436of Cover Texts in the Modified Version.  Only one passage of
36437Front-Cover Text and one of Back-Cover Text may be added by (or
36438through arrangements made by) any one entity.  If the Document already
36439includes a cover text for the same cover, previously added by you or
36440by arrangement made by the same entity you are acting on behalf of,
36441you may not add another; but you may replace the old one, on explicit
36442permission from the previous publisher that added the old one.
36443
36444The author(s) and publisher(s) of the Document do not by this License
36445give permission to use their names for publicity for or to assert or
36446imply endorsement of any Modified Version.
36447
36448@strong{5. COMBINING DOCUMENTS}
36449
36450You may combine the Document with other documents released under this
36451License, under the terms defined in section 4 above for modified
36452versions, provided that you include in the combination all of the
36453Invariant Sections of all of the original documents, unmodified, and
36454list them all as Invariant Sections of your combined work in its
36455license notice, and that you preserve all their Warranty Disclaimers.
36456
36457The combined work need only contain one copy of this License, and
36458multiple identical Invariant Sections may be replaced with a single
36459copy.  If there are multiple Invariant Sections with the same name but
36460different contents, make the title of each such section unique by
36461adding at the end of it, in parentheses, the name of the original
36462author or publisher of that section if known, or else a unique number.
36463Make the same adjustment to the section titles in the list of
36464Invariant Sections in the license notice of the combined work.
36465
36466In the combination, you must combine any sections Entitled "History"
36467in the various original documents, forming one section Entitled
36468"History"; likewise combine any sections Entitled "Acknowledgements",
36469and any sections Entitled "Dedications".  You must delete all sections
36470Entitled "Endorsements".
36471
36472@strong{6. COLLECTIONS OF DOCUMENTS}
36473
36474You may make a collection consisting of the Document and other documents
36475released under this License, and replace the individual copies of this
36476License in the various documents with a single copy that is included in
36477the collection, provided that you follow the rules of this License for
36478verbatim copying of each of the documents in all other respects.
36479
36480You may extract a single document from such a collection, and distribute
36481it individually under this License, provided you insert a copy of this
36482License into the extracted document, and follow this License in all
36483other respects regarding verbatim copying of that document.
36484
36485@strong{7. AGGREGATION WITH INDEPENDENT WORKS}
36486
36487A compilation of the Document or its derivatives with other separate
36488and independent documents or works, in or on a volume of a storage or
36489distribution medium, is called an "aggregate" if the copyright
36490resulting from the compilation is not used to limit the legal rights
36491of the compilation's users beyond what the individual works permit.
36492When the Document is included in an aggregate, this License does not
36493apply to the other works in the aggregate which are not themselves
36494derivative works of the Document.
36495
36496If the Cover Text requirement of section 3 is applicable to these
36497copies of the Document, then if the Document is less than one half of
36498the entire aggregate, the Document's Cover Texts may be placed on
36499covers that bracket the Document within the aggregate, or the
36500electronic equivalent of covers if the Document is in electronic form.
36501Otherwise they must appear on printed covers that bracket the whole
36502aggregate.
36503
36504@strong{8. TRANSLATION}
36505
36506Translation is considered a kind of modification, so you may
36507distribute translations of the Document under the terms of section 4.
36508Replacing Invariant Sections with translations requires special
36509permission from their copyright holders, but you may include
36510translations of some or all Invariant Sections in addition to the
36511original versions of these Invariant Sections.  You may include a
36512translation of this License, and all the license notices in the
36513Document, and any Warranty Disclaimers, provided that you also include
36514the original English version of this License and the original versions
36515of those notices and disclaimers.  In case of a disagreement between
36516the translation and the original version of this License or a notice
36517or disclaimer, the original version will prevail.
36518
36519If a section in the Document is Entitled "Acknowledgements",
36520"Dedications", or "History", the requirement (section 4) to Preserve
36521its Title (section 1) will typically require changing the actual
36522title.
36523
36524@strong{9. TERMINATION}
36525
36526You may not copy, modify, sublicense, or distribute the Document
36527except as expressly provided under this License.  Any attempt
36528otherwise to copy, modify, sublicense, or distribute it is void, and
36529will automatically terminate your rights under this License.
36530
36531However, if you cease all violation of this License, then your license
36532from a particular copyright holder is reinstated (a) provisionally,
36533unless and until the copyright holder explicitly and finally
36534terminates your license, and (b) permanently, if the copyright holder
36535fails to notify you of the violation by some reasonable means prior to
3653660 days after the cessation.
36537
36538Moreover, your license from a particular copyright holder is
36539reinstated permanently if the copyright holder notifies you of the
36540violation by some reasonable means, this is the first time you have
36541received notice of violation of this License (for any work) from that
36542copyright holder, and you cure the violation prior to 30 days after
36543your receipt of the notice.
36544
36545Termination of your rights under this section does not terminate the
36546licenses of parties who have received copies or rights from you under
36547this License.  If your rights have been terminated and not permanently
36548reinstated, receipt of a copy of some or all of the same material does
36549not give you any rights to use it.
36550
36551@strong{10. FUTURE REVISIONS OF THIS LICENSE}
36552
36553The Free Software Foundation may publish new, revised versions
36554of the GNU Free Documentation License from time to time.  Such new
36555versions will be similar in spirit to the present version, but may
36556differ in detail to address new problems or concerns.  See
36557@indicateurl{http://www.gnu.org/copyleft/}.
36558
36559Each version of the License is given a distinguishing version number.
36560If the Document specifies that a particular numbered version of this
36561License "or any later version" applies to it, you have the option of
36562following the terms and conditions either of that specified version or
36563of any later version that has been published (not as a draft) by the
36564Free Software Foundation.  If the Document does not specify a version
36565number of this License, you may choose any version ever published (not
36566as a draft) by the Free Software Foundation.  If the Document
36567specifies that a proxy can decide which future versions of this
36568License can be used, that proxy's public statement of acceptance of a
36569version permanently authorizes you to choose that version for the
36570Document.
36571
36572@strong{11. RELICENSING}
36573
36574"Massive Multiauthor Collaboration Site" (or "MMC Site") means any
36575World Wide Web server that publishes copyrightable works and also
36576provides prominent facilities for anybody to edit those works.  A
36577public wiki that anybody can edit is an example of such a server.  A
36578"Massive Multiauthor Collaboration" (or "MMC") contained in the
36579site means any set of copyrightable works thus published on the MMC
36580site.
36581
36582"CC-BY-SA" means the Creative Commons Attribution-Share Alike 3.0
36583license published by Creative Commons Corporation, a not-for-profit
36584corporation with a principal place of business in San Francisco,
36585California, as well as future copyleft versions of that license
36586published by that same organization.
36587
36588"Incorporate" means to publish or republish a Document, in whole or
36589in part, as part of another Document.
36590
36591An MMC is "eligible for relicensing" if it is licensed under this
36592License, and if all works that were first published under this License
36593somewhere other than this MMC, and subsequently incorporated in whole
36594or in part into the MMC, (1) had no cover texts or invariant sections,
36595and (2) were thus incorporated prior to November 1, 2008.
36596
36597The operator of an MMC Site may republish an MMC contained in the site
36598under CC-BY-SA on the same site at any time before August 1, 2009,
36599provided the MMC is eligible for relicensing.
36600
36601@strong{ADDENDUM: How to use this License for your documents}
36602
36603To use this License in a document you have written, include a copy of
36604the License in the document and put the following copyright and
36605license notices just after the title page:
36606
36607@quotation
36608
36609Copyright © YEAR  YOUR NAME.
36610Permission is granted to copy, distribute and/or modify this document
36611under the terms of the GNU Free Documentation License, Version 1.3
36612or any later version published by the Free Software Foundation;
36613with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
36614A copy of the license is included in the section entitled "GNU
36615Free Documentation License".
36616@end quotation
36617
36618If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts,
36619replace the "with ... Texts." line with this:
36620
36621@quotation
36622
36623with the Invariant Sections being LIST THEIR TITLES, with the
36624Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST.
36625@end quotation
36626
36627If you have Invariant Sections without Cover Texts, or some other
36628combination of the three, merge those two alternatives to suit the
36629situation.
36630
36631If your document contains nontrivial examples of program code, we
36632recommend releasing these examples in parallel under your choice of
36633free software license, such as the GNU General Public License,
36634to permit their use in free software.
36635
36636@node Index,,GNU Free Documentation License,Top
36637@unnumbered Index
36638
36639
36640@printindex ge
36641
36642
36643@c %**end of body
36644@bye
36645