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 , March 24, 2015
25
26AdaCore
27
28Copyright @copyright{} 2008-2015, 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
208Building Mixed Ada and C++ Programs
209
210* Interfacing to C++:: 
211* Linking a Mixed C++ & Ada Program:: 
212* A Simple Example:: 
213* Interfacing with C++ constructors:: 
214* Interfacing with C++ at the Class Level:: 
215
216Generating Ada Bindings for C and C++ headers
217
218* Running the binding generator:: 
219* Generating bindings for C++ headers:: 
220* Switches:: 
221
222GNAT and Other Compilation Models
223
224* Comparison between GNAT and C/C++ Compilation Models:: 
225* Comparison between GNAT and Conventional Ada Library Models:: 
226
227Using GNAT Files with External Tools
228
229* Using Other Utility Programs with GNAT:: 
230* The External Symbol Naming Scheme of GNAT:: 
231
232Building Executable Programs with GNAT
233
234* Building with gnatmake:: 
235* Compiling with gcc:: 
236* Compiler Switches:: 
237* Binding with gnatbind:: 
238* Linking with gnatlink:: 
239* Using the GNU make Utility:: 
240
241Building with gnatmake
242
243* Running gnatmake:: 
244* Switches for gnatmake:: 
245* Mode Switches for gnatmake:: 
246* Notes on the Command Line:: 
247* How gnatmake Works:: 
248* Examples of gnatmake Usage:: 
249
250Compiling with gcc
251
252* Compiling Programs:: 
253* Search Paths and the Run-Time Library (RTL): Search Paths and the Run-Time Library RTL. 
254* Order of Compilation Issues:: 
255* Examples:: 
256
257Compiler Switches
258
259* Alphabetical List of All Switches:: 
260* Output and Error Message Control:: 
261* Warning Message Control:: 
262* Debugging and Assertion Control:: 
263* Validity Checking:: 
264* Style Checking:: 
265* Run-Time Checks:: 
266* Using gcc for Syntax Checking:: 
267* Using gcc for Semantic Checking:: 
268* Compiling Different Versions of Ada:: 
269* Character Set Control:: 
270* File Naming Control:: 
271* Subprogram Inlining Control:: 
272* Auxiliary Output Control:: 
273* Debugging Control:: 
274* Exception Handling Control:: 
275* Units to Sources Mapping Files:: 
276* Code Generation Control:: 
277
278Binding with gnatbind
279
280* Running gnatbind:: 
281* Switches for gnatbind:: 
282* Command-Line Access:: 
283* Search Paths for gnatbind:: 
284* Examples of gnatbind Usage:: 
285
286Switches for gnatbind
287
288* Consistency-Checking Modes:: 
289* Binder Error Message Control:: 
290* Elaboration Control:: 
291* Output Control:: 
292* Dynamic Allocation Control:: 
293* Binding with Non-Ada Main Programs:: 
294* Binding Programs with No Main Subprogram:: 
295
296Linking with gnatlink
297
298* Running gnatlink:: 
299* Switches for gnatlink:: 
300
301Using the GNU make Utility
302
303* Using gnatmake in a Makefile:: 
304* Automatically Creating a List of Directories:: 
305* Generating the Command Line Switches:: 
306* Overcoming Command Line Length Limits:: 
307
308GNAT Project Manager
309
310* Introduction:: 
311* Building With Projects:: 
312* Organizing Projects into Subsystems:: 
313* Scenarios in Projects:: 
314* Library Projects:: 
315* Project Extension:: 
316* Aggregate Projects:: 
317* Aggregate Library Projects:: 
318* Project File Reference:: 
319
320Building With Projects
321
322* Source Files and Directories:: 
323* Duplicate Sources in Projects:: 
324* Object and Exec Directory:: 
325* Main Subprograms:: 
326* Tools Options in Project Files:: 
327* Compiling with Project Files:: 
328* Executable File Names:: 
329* Avoid Duplication With Variables:: 
330* Naming Schemes:: 
331* Installation:: 
332* Distributed support:: 
333
334Organizing Projects into Subsystems
335
336* Project Dependencies:: 
337* Cyclic Project Dependencies:: 
338* Sharing Between Projects:: 
339* Global Attributes:: 
340
341Library Projects
342
343* Building Libraries:: 
344* Using Library Projects:: 
345* Stand-alone Library Projects:: 
346* Installing a library with project files:: 
347
348Project Extension
349
350* Project Hierarchy Extension:: 
351
352Aggregate Projects
353
354* Building all main programs from a single project tree:: 
355* Building a set of projects with a single command:: 
356* Define a build environment:: 
357* Performance improvements in builder:: 
358* Syntax of aggregate projects:: 
359* package Builder in aggregate projects:: 
360
361Aggregate Library Projects
362
363* Building aggregate library projects:: 
364* Syntax of aggregate library projects:: 
365
366Project File Reference
367
368* Project Declaration:: 
369* Qualified Projects:: 
370* Declarations:: 
371* Packages:: 
372* Expressions:: 
373* External Values:: 
374* Typed String Declaration:: 
375* Variables:: 
376* Case Constructions:: 
377* Attributes:: 
378
379Attributes
380
381* Project Level Attributes:: 
382* Package Binder Attributes:: 
383* Package Builder Attributes:: 
384* Package Clean Attributes:: 
385* Package Compiler Attributes:: 
386* Package Cross_Reference Attributes:: 
387* Package Finder Attributes:: 
388* Package gnatls Attributes:: 
389* Package IDE Attributes:: 
390* Package Install Attributes:: 
391* Package Linker Attributes:: 
392* Package Naming Attributes:: 
393* Package Remote Attributes:: 
394* Package Stack Attributes:: 
395* Package Synchronize Attributes:: 
396
397Tools Supporting Project Files
398
399* gnatmake and Project Files:: 
400* The GNAT Driver and Project Files:: 
401
402gnatmake and Project Files
403
404* Switches Related to Project Files:: 
405* Switches and Project Files:: 
406* Specifying Configuration Pragmas:: 
407* Project Files and Main Subprograms:: 
408* Library Project Files:: 
409
410GNAT Utility Programs
411
412* The File Cleanup Utility gnatclean:: 
413* The GNAT Library Browser gnatls:: 
414* The Cross-Referencing Tools gnatxref and gnatfind:: 
415* The Ada to HTML Converter gnathtml:: 
416
417The File Cleanup Utility gnatclean
418
419* Running gnatclean:: 
420* Switches for gnatclean:: 
421
422The GNAT Library Browser gnatls
423
424* Running gnatls:: 
425* Switches for gnatls:: 
426* Example of gnatls Usage:: 
427
428The Cross-Referencing Tools gnatxref and gnatfind
429
430* gnatxref Switches:: 
431* gnatfind Switches:: 
432* Project Files for gnatxref and gnatfind:: 
433* Regular Expressions in gnatfind and gnatxref:: 
434* Examples of gnatxref Usage:: 
435* Examples of gnatfind Usage:: 
436
437Examples of gnatxref Usage
438
439* General Usage:: 
440* Using gnatxref with vi:: 
441
442The Ada to HTML Converter gnathtml
443
444* Invoking gnathtml:: 
445* Installing gnathtml:: 
446
447GNAT and Program Execution
448
449* Running and Debugging Ada Programs:: 
450* Code Coverage and Profiling:: 
451* Improving Performance:: 
452* Overflow Check Handling in GNAT:: 
453* Performing Dimensionality Analysis in GNAT:: 
454* Stack Related Facilities:: 
455* Memory Management Issues:: 
456
457Running and Debugging Ada Programs
458
459* The GNAT Debugger GDB:: 
460* Running GDB:: 
461* Introduction to GDB Commands:: 
462* Using Ada Expressions:: 
463* Calling User-Defined Subprograms:: 
464* Using the next Command in a Function:: 
465* Stopping When Ada Exceptions Are Raised:: 
466* Ada Tasks:: 
467* Debugging Generic Units:: 
468* Remote Debugging with gdbserver:: 
469* GNAT Abnormal Termination or Failure to Terminate:: 
470* Naming Conventions for GNAT Source Files:: 
471* Getting Internal Debugging Information:: 
472* Stack Traceback:: 
473
474Stack Traceback
475
476* Non-Symbolic Traceback:: 
477* Symbolic Traceback:: 
478
479Code Coverage and Profiling
480
481* Code Coverage of Ada Programs with gcov:: 
482* Profiling an Ada Program with gprof:: 
483
484Code Coverage of Ada Programs with gcov
485
486* Quick startup guide:: 
487* GNAT specifics:: 
488
489Profiling an Ada Program with gprof
490
491* Compilation for profiling:: 
492* Program execution:: 
493* Running gprof:: 
494* Interpretation of profiling results:: 
495
496Improving Performance
497
498* Performance Considerations:: 
499* Text_IO Suggestions:: 
500* Reducing Size of Executables with Unused Subprogram/Data Elimination:: 
501
502Performance Considerations
503
504* Controlling Run-Time Checks:: 
505* Use of Restrictions:: 
506* Optimization Levels:: 
507* Debugging Optimized Code:: 
508* Inlining of Subprograms:: 
509* Floating_Point_Operations:: 
510* Vectorization of loops:: 
511* Other Optimization Switches:: 
512* Optimization and Strict Aliasing:: 
513* Aliased Variables and Optimization:: 
514* Atomic Variables and Optimization:: 
515* Passive Task Optimization:: 
516
517Reducing Size of Executables with Unused Subprogram/Data Elimination
518
519* About unused subprogram/data elimination:: 
520* Compilation options:: 
521* Example of unused subprogram/data elimination:: 
522
523Overflow Check Handling in GNAT
524
525* Background:: 
526* Overflow Checking Modes in GNAT:: 
527* Specifying the Desired Mode:: 
528* Default Settings:: 
529* Implementation Notes:: 
530
531Stack Related Facilities
532
533* Stack Overflow Checking:: 
534* Static Stack Usage Analysis:: 
535* Dynamic Stack Usage Analysis:: 
536
537Memory Management Issues
538
539* Some Useful Memory Pools:: 
540* The GNAT Debug Pool Facility:: 
541
542Platform-Specific Information
543
544* Run-Time Libraries:: 
545* Specifying a Run-Time Library:: 
546* Microsoft Windows Topics:: 
547* Mac OS Topics:: 
548
549Run-Time Libraries
550
551* Summary of Run-Time Configurations:: 
552
553Specifying a Run-Time Library
554
555* Choosing the Scheduling Policy:: 
556* Solaris-Specific Considerations:: 
557* Solaris Threads Issues:: 
558* AIX-Specific Considerations:: 
559
560Microsoft Windows Topics
561
562* Using GNAT on Windows:: 
563* Using a network installation of GNAT:: 
564* CONSOLE and WINDOWS subsystems:: 
565* Temporary Files:: 
566* Mixed-Language Programming on Windows:: 
567
568Mixed-Language Programming on Windows
569
570* Windows Calling Conventions:: 
571* Introduction to Dynamic Link Libraries (DLLs): Introduction to Dynamic Link Libraries DLLs. 
572* Using DLLs with GNAT:: 
573* Building DLLs with GNAT Project files:: 
574* Building DLLs with GNAT:: 
575* Building DLLs with gnatdll:: 
576* Ada DLLs and Finalization:: 
577* Creating a Spec for Ada DLLs:: 
578* GNAT and Windows Resources:: 
579* Debugging a DLL:: 
580* Setting Stack Size from gnatlink:: 
581* Setting Heap Size from gnatlink:: 
582
583Windows Calling Conventions
584
585* C Calling Convention:: 
586* Stdcall Calling Convention:: 
587* Win32 Calling Convention:: 
588* DLL Calling Convention:: 
589
590Using DLLs with GNAT
591
592* Creating an Ada Spec for the DLL Services:: 
593* Creating an Import Library:: 
594
595Building DLLs with gnatdll
596
597* Limitations When Using Ada DLLs from Ada:: 
598* Exporting Ada Entities:: 
599* Ada DLLs and Elaboration:: 
600
601Creating a Spec for Ada DLLs
602
603* Creating the Definition File:: 
604* Using gnatdll:: 
605
606GNAT and Windows Resources
607
608* Building Resources:: 
609* Compiling Resources:: 
610* Using Resources:: 
611
612Debugging a DLL
613
614* Program and DLL Both Built with GCC/GNAT:: 
615* Program Built with Foreign Tools and DLL Built with GCC/GNAT:: 
616
617Mac OS Topics
618
619* Codesigning the Debugger:: 
620
621Elaboration Order Handling in GNAT
622
623* Elaboration Code:: 
624* Checking the Elaboration Order:: 
625* Controlling the Elaboration Order:: 
626* Controlling Elaboration in GNAT - Internal Calls:: 
627* Controlling Elaboration in GNAT - External Calls:: 
628* Default Behavior in GNAT - Ensuring Safety:: 
629* Treatment of Pragma Elaborate:: 
630* Elaboration Issues for Library Tasks:: 
631* Mixing Elaboration Models:: 
632* What to Do If the Default Elaboration Behavior Fails:: 
633* Elaboration for Indirect Calls:: 
634* Summary of Procedures for Elaboration Control:: 
635* Other Elaboration Order Considerations:: 
636* Determining the Chosen Elaboration Order:: 
637
638Inline Assembler
639
640* Basic Assembler Syntax:: 
641* A Simple Example of Inline Assembler:: 
642* Output Variables in Inline Assembler:: 
643* Input Variables in Inline Assembler:: 
644* Inlining Inline Assembler Code:: 
645* Other Asm Functionality:: 
646
647Other Asm Functionality
648
649* The Clobber Parameter:: 
650* The Volatile Parameter:: 
651
652@end detailmenu
653@end menu
654
655@node About This Guide,Getting Started with GNAT,Top,Top
656@anchor{gnat_ugn/about_this_guide about-this-guide}@anchor{2}@anchor{gnat_ugn/about_this_guide doc}@anchor{3}@anchor{gnat_ugn/about_this_guide gnat-user-s-guide-for-native-platforms}@anchor{4}@anchor{gnat_ugn/about_this_guide id1}@anchor{5}
657@chapter About This Guide
658
659
660
661This guide describes the use of GNAT,
662a compiler and software development
663toolset for the full Ada programming language.
664It documents the features of the compiler and tools, and explains
665how to use them to build Ada applications.
666
667GNAT implements Ada 95, Ada 2005 and Ada 2012, and it may also be
668invoked in Ada 83 compatibility mode.
669By default, GNAT assumes Ada 2012, but you can override with a
670compiler switch (@ref{6,,Compiling Different Versions of Ada})
671to explicitly specify the language version.
672Throughout this manual, references to 'Ada' without a year suffix
673apply to all Ada 95/2005/2012 versions of the language.
674
675@menu
676* What This Guide Contains:: 
677* What You Should Know before Reading This Guide:: 
678* Related Information:: 
679* A Note to Readers of Previous Versions of the Manual:: 
680* Conventions:: 
681
682@end menu
683
684@node What This Guide Contains,What You Should Know before Reading This Guide,,About This Guide
685@anchor{gnat_ugn/about_this_guide what-this-guide-contains}@anchor{7}
686@section What This Guide Contains
687
688
689This guide contains the following chapters:
690
691
692@itemize *
693
694@item 
695@ref{8,,Getting Started with GNAT} describes how to get started compiling
696and running Ada programs with the GNAT Ada programming environment.
697
698@item 
699@ref{9,,The GNAT Compilation Model} describes the compilation model used
700by GNAT.
701
702@item 
703@ref{a,,Building Executable Programs with GNAT} describes how to use the
704main GNAT tools to build executable programs, and it also gives examples of
705using the GNU make utility with GNAT.
706
707@item 
708@ref{b,,GNAT Project Manager} describes how to use project files
709to organize large projects.
710
711@item 
712@ref{c,,Tools Supporting Project Files} described how to use the project
713facility in conjunction with various GNAT tools.
714
715@item 
716@ref{d,,GNAT Utility Programs} explains the various utility programs that
717are included in the GNAT environment
718
719@item 
720@ref{e,,GNAT and Program Execution} covers a number of topics related to
721running, debugging, and tuning the performace of programs developed
722with GNAT
723@end itemize
724
725Appendices cover several additional topics:
726
727
728@itemize *
729
730@item 
731@ref{f,,Platform-Specific Information} describes the different run-time
732library implementations and also presents information on how to use
733GNAT on several specific platforms
734
735@item 
736@ref{10,,Example of Binder Output File} shows the source code for the binder
737output file for a sample program.
738
739@item 
740@ref{11,,Elaboration Order Handling in GNAT} describes how GNAT helps
741you deal with elaboration order issues.
742
743@item 
744@ref{12,,Inline Assembler} shows how to use the inline assembly facility
745in an Ada program.
746@end itemize
747
748@node What You Should Know before Reading This Guide,Related Information,What This Guide Contains,About This Guide
749@anchor{gnat_ugn/about_this_guide what-you-should-know-before-reading-this-guide}@anchor{13}
750@section What You Should Know before Reading This Guide
751
752
753@geindex Ada 95 Language Reference Manual
754
755@geindex Ada 2005 Language Reference Manual
756
757This guide assumes a basic familiarity with the Ada 95 language, as
758described in the International Standard ANSI/ISO/IEC-8652:1995, January
7591995.
760It does not require knowledge of the features introduced by Ada 2005
761or Ada 2012.
762Reference manuals for Ada 95, Ada 2005, and Ada 2012 are included in
763the GNAT documentation package.
764
765@node Related Information,A Note to Readers of Previous Versions of the Manual,What You Should Know before Reading This Guide,About This Guide
766@anchor{gnat_ugn/about_this_guide related-information}@anchor{14}
767@section Related Information
768
769
770For further information about Ada and related tools, please refer to the
771following documents:
772
773
774@itemize *
775
776@item 
777@cite{Ada 95 Reference Manual}, @cite{Ada 2005 Reference Manual}, and
778@cite{Ada 2012 Reference Manual}, which contain reference
779material for the several revisions of the Ada language standard.
780
781@item 
782@cite{GNAT Reference_Manual}, which contains all reference material for the GNAT
783implementation of Ada.
784
785@item 
786@cite{Using the GNAT Programming Studio}, which describes the GPS
787Integrated Development Environment.
788
789@item 
790@cite{GNAT Programming Studio Tutorial}, which introduces the
791main GPS features through examples.
792
793@item 
794@cite{Debugging with GDB},
795for all details on the use of the GNU source-level debugger.
796
797@item 
798@cite{GNU Emacs Manual},
799for full information on the extensible editor and programming
800environment Emacs.
801@end itemize
802
803@node A Note to Readers of Previous Versions of the Manual,Conventions,Related Information,About This Guide
804@anchor{gnat_ugn/about_this_guide a-note-to-readers-of-previous-versions-of-the-manual}@anchor{15}
805@section A Note to Readers of Previous Versions of the Manual
806
807
808In early 2015 the GNAT manuals were transitioned to the
809reStructuredText (rst) / Sphinx documentation generator technology.
810During that process the @cite{GNAT User's Guide} was reorganized
811so that related topics would be described together in the same chapter
812or appendix.  Here's a summary of the major changes realized in
813the new document structure.
814
815
816@itemize *
817
818@item 
819@ref{9,,The GNAT Compilation Model} has been extended so that it now covers
820the following material:
821
822
823@itemize -
824
825@item 
826The @cite{gnatname}, @cite{gnatkr}, and @cite{gnatchop} tools
827
828@item 
829@ref{16,,Configuration Pragmas}
830
831@item 
832@ref{17,,GNAT and Libraries}
833
834@item 
835@ref{18,,Conditional Compilation} including @ref{19,,Preprocessing with gnatprep}
836and @ref{1a,,Integrated Preprocessing}
837
838@item 
839@ref{1b,,Generating Ada Bindings for C and C++ headers}
840
841@item 
842@ref{1c,,Using GNAT Files with External Tools}
843@end itemize
844
845@item 
846@ref{a,,Building Executable Programs with GNAT} is a new chapter consolidating
847the following content:
848
849
850@itemize -
851
852@item 
853@ref{1d,,Building with gnatmake}
854
855@item 
856@ref{1e,,Compiling with gcc}
857
858@item 
859@ref{1f,,Binding with gnatbind}
860
861@item 
862@ref{20,,Linking with gnatlink}
863
864@item 
865@ref{21,,Using the GNU make Utility}
866@end itemize
867
868@item 
869@ref{d,,GNAT Utility Programs} is a new chapter consolidating the information about several
870GNAT tools:
871
872
873
874@itemize -
875
876@item 
877@ref{22,,The File Cleanup Utility gnatclean}
878
879@item 
880@ref{23,,The GNAT Library Browser gnatls}
881
882@item 
883@ref{24,,The Cross-Referencing Tools gnatxref and gnatfind}
884
885@item 
886@ref{25,,The Ada to HTML Converter gnathtml}
887@end itemize
888
889@item 
890@ref{e,,GNAT and Program Execution} is a new chapter consolidating the following:
891
892
893@itemize -
894
895@item 
896@ref{26,,Running and Debugging Ada Programs}
897
898@item 
899@ref{27,,Code Coverage and Profiling}
900
901@item 
902@ref{28,,Improving Performance}
903
904@item 
905@ref{29,,Overflow Check Handling in GNAT}
906
907@item 
908@ref{2a,,Performing Dimensionality Analysis in GNAT}
909
910@item 
911@ref{2b,,Stack Related Facilities}
912
913@item 
914@ref{2c,,Memory Management Issues}
915@end itemize
916
917@item 
918@ref{f,,Platform-Specific Information} is a new appendix consolidating the following:
919
920
921@itemize -
922
923@item 
924@ref{2d,,Run-Time Libraries}
925
926@item 
927@ref{2e,,Microsoft Windows Topics}
928
929@item 
930@ref{2f,,Mac OS Topics}
931@end itemize
932
933@item 
934The @cite{Compatibility and Porting Guide} appendix has been moved to the
935@cite{GNAT Reference Manual}. It now includes a section
936@cite{Writing Portable Fixed-Point Declarations} which was previously
937a separate chapter in the @cite{GNAT User's Guide}.
938@end itemize
939
940@node Conventions,,A Note to Readers of Previous Versions of the Manual,About This Guide
941@anchor{gnat_ugn/about_this_guide conventions}@anchor{30}
942@section Conventions
943
944
945@geindex Conventions
946@geindex typographical
947
948@geindex Typographical conventions
949
950Following are examples of the typographical and graphic conventions used
951in this guide:
952
953
954@itemize *
955
956@item 
957@cite{Functions}, @cite{utility program names}, @cite{standard names},
958and @cite{classes}.
959
960@item 
961@cite{Option flags}
962
963@item 
964@code{File names}
965
966@item 
967@cite{Variables}
968
969@item 
970@emph{Emphasis}
971
972@item 
973[optional information or parameters]
974
975@item 
976Examples are described by text
977
978@example
979and then shown this way.
980@end example
981
982@item 
983Commands that are entered by the user are shown as preceded by a prompt string
984comprising the @code{$} character followed by a space.
985
986@item 
987Full file names are shown with the '/' character
988as the directory separator; e.g., @code{parent-dir/subdir/myfile.adb}.
989If you are using GNAT on a Windows platform, please note that
990the '\' character should be used instead.
991@end itemize
992
993@node Getting Started with GNAT,The GNAT Compilation Model,About This Guide,Top
994@anchor{gnat_ugn/getting_started_with_gnat getting-started-with-gnat}@anchor{8}@anchor{gnat_ugn/getting_started_with_gnat doc}@anchor{31}@anchor{gnat_ugn/getting_started_with_gnat id1}@anchor{32}
995@chapter Getting Started with GNAT
996
997
998This chapter describes how to use GNAT's command line interface to build
999executable Ada programs.
1000On most platforms a visually oriented Integrated Development Environment
1001is also available, the GNAT Programming Studio (GPS).
1002GPS offers a graphical "look and feel", support for development in
1003other programming languages, comprehensive browsing features, and
1004many other capabilities.
1005For information on GPS please refer to
1006@cite{Using the GNAT Programming Studio}.
1007
1008@menu
1009* Running GNAT:: 
1010* Running a Simple Ada Program:: 
1011* Running a Program with Multiple Units:: 
1012* Using the gnatmake Utility:: 
1013
1014@end menu
1015
1016@node Running GNAT,Running a Simple Ada Program,,Getting Started with GNAT
1017@anchor{gnat_ugn/getting_started_with_gnat running-gnat}@anchor{33}@anchor{gnat_ugn/getting_started_with_gnat id2}@anchor{34}
1018@section Running GNAT
1019
1020
1021Three steps are needed to create an executable file from an Ada source
1022file:
1023
1024
1025@itemize *
1026
1027@item 
1028The source file(s) must be compiled.
1029
1030@item 
1031The file(s) must be bound using the GNAT binder.
1032
1033@item 
1034All appropriate object files must be linked to produce an executable.
1035@end itemize
1036
1037All three steps are most commonly handled by using the @emph{gnatmake}
1038utility program that, given the name of the main program, automatically
1039performs the necessary compilation, binding and linking steps.
1040
1041@node Running a Simple Ada Program,Running a Program with Multiple Units,Running GNAT,Getting Started with GNAT
1042@anchor{gnat_ugn/getting_started_with_gnat running-a-simple-ada-program}@anchor{35}@anchor{gnat_ugn/getting_started_with_gnat id3}@anchor{36}
1043@section Running a Simple Ada Program
1044
1045
1046Any text editor may be used to prepare an Ada program.
1047(If Emacs is used, the optional Ada mode may be helpful in laying out the
1048program.)
1049The program text is a normal text file. We will assume in our initial
1050example that you have used your editor to prepare the following
1051standard format text file:
1052
1053@example
1054with Ada.Text_IO; use Ada.Text_IO;
1055procedure Hello is
1056begin
1057   Put_Line ("Hello WORLD!");
1058end Hello;
1059@end example
1060
1061This file should be named @code{hello.adb}.
1062With the normal default file naming conventions, GNAT requires
1063that each file
1064contain a single compilation unit whose file name is the
1065unit name,
1066with periods replaced by hyphens; the
1067extension is @code{ads} for a
1068spec and @code{adb} for a body.
1069You can override this default file naming convention by use of the
1070special pragma @cite{Source_File_Name} (for further information please
1071see @ref{37,,Using Other File Names}).
1072Alternatively, if you want to rename your files according to this default
1073convention, which is probably more convenient if you will be using GNAT
1074for all your compilations, then the @cite{gnatchop} utility
1075can be used to generate correctly-named source files
1076(see @ref{38,,Renaming Files with gnatchop}).
1077
1078You can compile the program using the following command (@cite{$} is used
1079as the command prompt in the examples in this document):
1080
1081@example
1082$ gcc -c hello.adb
1083@end example
1084
1085@emph{gcc} is the command used to run the compiler. This compiler is
1086capable of compiling programs in several languages, including Ada and
1087C. It assumes that you have given it an Ada program if the file extension is
1088either @code{.ads} or @code{.adb}, and it will then call
1089the GNAT compiler to compile the specified file.
1090
1091The @code{-c} switch is required. It tells @emph{gcc} to only do a
1092compilation. (For C programs, @emph{gcc} can also do linking, but this
1093capability is not used directly for Ada programs, so the @code{-c}
1094switch must always be present.)
1095
1096This compile command generates a file
1097@code{hello.o}, which is the object
1098file corresponding to your Ada program. It also generates
1099an 'Ada Library Information' file @code{hello.ali},
1100which contains additional information used to check
1101that an Ada program is consistent.
1102To build an executable file,
1103use @cite{gnatbind} to bind the program
1104and @emph{gnatlink} to link it. The
1105argument to both @cite{gnatbind} and @emph{gnatlink} is the name of the
1106@code{ALI} file, but the default extension of @code{.ali} can
1107be omitted. This means that in the most common case, the argument
1108is simply the name of the main program:
1109
1110@example
1111$ gnatbind hello
1112$ gnatlink hello
1113@end example
1114
1115A simpler method of carrying out these steps is to use @emph{gnatmake},
1116a master program that invokes all the required
1117compilation, binding and linking tools in the correct order. In particular,
1118@emph{gnatmake} automatically recompiles any sources that have been
1119modified since they were last compiled, or sources that depend
1120on such modified sources, so that 'version skew' is avoided.
1121
1122@geindex Version skew (avoided by *gnatmake*)
1123
1124@example
1125$ gnatmake hello.adb
1126@end example
1127
1128The result is an executable program called @code{hello}, which can be
1129run by entering:
1130
1131@example
1132$ hello
1133@end example
1134
1135assuming that the current directory is on the search path
1136for executable programs.
1137
1138and, if all has gone well, you will see:
1139
1140@example
1141Hello WORLD!
1142@end example
1143
1144appear in response to this command.
1145
1146@node Running a Program with Multiple Units,Using the gnatmake Utility,Running a Simple Ada Program,Getting Started with GNAT
1147@anchor{gnat_ugn/getting_started_with_gnat id4}@anchor{39}@anchor{gnat_ugn/getting_started_with_gnat running-a-program-with-multiple-units}@anchor{3a}
1148@section Running a Program with Multiple Units
1149
1150
1151Consider a slightly more complicated example that has three files: a
1152main program, and the spec and body of a package:
1153
1154@example
1155package Greetings is
1156   procedure Hello;
1157   procedure Goodbye;
1158end Greetings;
1159
1160with Ada.Text_IO; use Ada.Text_IO;
1161package body Greetings is
1162   procedure Hello is
1163   begin
1164      Put_Line ("Hello WORLD!");
1165   end Hello;
1166
1167   procedure Goodbye is
1168   begin
1169      Put_Line ("Goodbye WORLD!");
1170   end Goodbye;
1171end Greetings;
1172
1173with Greetings;
1174procedure Gmain is
1175begin
1176   Greetings.Hello;
1177   Greetings.Goodbye;
1178end Gmain;
1179@end example
1180
1181Following the one-unit-per-file rule, place this program in the
1182following three separate files:
1183
1184
1185@table @asis
1186
1187@item @emph{greetings.ads}
1188
1189spec of package @cite{Greetings}
1190
1191@item @emph{greetings.adb}
1192
1193body of package @cite{Greetings}
1194
1195@item @emph{gmain.adb}
1196
1197body of main program
1198@end table
1199
1200To build an executable version of
1201this program, we could use four separate steps to compile, bind, and link
1202the program, as follows:
1203
1204@example
1205$ gcc -c gmain.adb
1206$ gcc -c greetings.adb
1207$ gnatbind gmain
1208$ gnatlink gmain
1209@end example
1210
1211Note that there is no required order of compilation when using GNAT.
1212In particular it is perfectly fine to compile the main program first.
1213Also, it is not necessary to compile package specs in the case where
1214there is an accompanying body; you only need to compile the body. If you want
1215to submit these files to the compiler for semantic checking and not code
1216generation, then use the @code{-gnatc} switch:
1217
1218@example
1219$ gcc -c greetings.ads -gnatc
1220@end example
1221
1222Although the compilation can be done in separate steps as in the
1223above example, in practice it is almost always more convenient
1224to use the @emph{gnatmake} tool. All you need to know in this case
1225is the name of the main program's source file. The effect of the above four
1226commands can be achieved with a single one:
1227
1228@example
1229$ gnatmake gmain.adb
1230@end example
1231
1232In the next section we discuss the advantages of using @emph{gnatmake} in
1233more detail.
1234
1235@node Using the gnatmake Utility,,Running a Program with Multiple Units,Getting Started with GNAT
1236@anchor{gnat_ugn/getting_started_with_gnat using-the-gnatmake-utility}@anchor{3b}@anchor{gnat_ugn/getting_started_with_gnat id5}@anchor{3c}
1237@section Using the @emph{gnatmake} Utility
1238
1239
1240If you work on a program by compiling single components at a time using
1241@emph{gcc}, you typically keep track of the units you modify. In order to
1242build a consistent system, you compile not only these units, but also any
1243units that depend on the units you have modified.
1244For example, in the preceding case,
1245if you edit @code{gmain.adb}, you only need to recompile that file. But if
1246you edit @code{greetings.ads}, you must recompile both
1247@code{greetings.adb} and @code{gmain.adb}, because both files contain
1248units that depend on @code{greetings.ads}.
1249
1250@emph{gnatbind} will warn you if you forget one of these compilation
1251steps, so that it is impossible to generate an inconsistent program as a
1252result of forgetting to do a compilation. Nevertheless it is tedious and
1253error-prone to keep track of dependencies among units.
1254One approach to handle the dependency-bookkeeping is to use a
1255makefile. However, makefiles present maintenance problems of their own:
1256if the dependencies change as you change the program, you must make
1257sure that the makefile is kept up-to-date manually, which is also an
1258error-prone process.
1259
1260The @emph{gnatmake} utility takes care of these details automatically.
1261Invoke it using either one of the following forms:
1262
1263@example
1264$ gnatmake gmain.adb
1265$ gnatmake gmain
1266@end example
1267
1268The argument is the name of the file containing the main program;
1269you may omit the extension. @emph{gnatmake}
1270examines the environment, automatically recompiles any files that need
1271recompiling, and binds and links the resulting set of object files,
1272generating the executable file, @code{gmain}.
1273In a large program, it
1274can be extremely helpful to use @emph{gnatmake}, because working out by hand
1275what needs to be recompiled can be difficult.
1276
1277Note that @emph{gnatmake} takes into account all the Ada rules that
1278establish dependencies among units. These include dependencies that result
1279from inlining subprogram bodies, and from
1280generic instantiation. Unlike some other
1281Ada make tools, @emph{gnatmake} does not rely on the dependencies that were
1282found by the compiler on a previous compilation, which may possibly
1283be wrong when sources change. @emph{gnatmake} determines the exact set of
1284dependencies from scratch each time it is run.
1285
1286@c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
1287
1288@node The GNAT Compilation Model,Building Executable Programs with GNAT,Getting Started with GNAT,Top
1289@anchor{gnat_ugn/the_gnat_compilation_model doc}@anchor{3d}@anchor{gnat_ugn/the_gnat_compilation_model the-gnat-compilation-model}@anchor{9}@anchor{gnat_ugn/the_gnat_compilation_model id1}@anchor{3e}
1290@chapter The GNAT Compilation Model
1291
1292
1293@geindex GNAT compilation model
1294
1295@geindex Compilation model
1296
1297This chapter describes the compilation model used by GNAT. Although
1298similar to that used by other languages such as C and C++, this model
1299is substantially different from the traditional Ada compilation models,
1300which are based on a centralized program library. The chapter covers
1301the following material:
1302
1303
1304@itemize *
1305
1306@item 
1307Topics related to source file makeup and naming
1308
1309
1310@itemize *
1311
1312@item 
1313@ref{3f,,Source Representation}
1314
1315@item 
1316@ref{40,,Foreign Language Representation}
1317
1318@item 
1319@ref{41,,File Naming Topics and Utilities}
1320@end itemize
1321
1322@item 
1323@ref{16,,Configuration Pragmas}
1324
1325@item 
1326@ref{42,,Generating Object Files}
1327
1328@item 
1329@ref{43,,Source Dependencies}
1330
1331@item 
1332@ref{44,,The Ada Library Information Files}
1333
1334@item 
1335@ref{45,,Binding an Ada Program}
1336
1337@item 
1338@ref{17,,GNAT and Libraries}
1339
1340@item 
1341@ref{18,,Conditional Compilation}
1342
1343@item 
1344@ref{46,,Mixed Language Programming}
1345
1346@item 
1347@ref{47,,GNAT and Other Compilation Models}
1348
1349@item 
1350@ref{1c,,Using GNAT Files with External Tools}
1351@end itemize
1352
1353@menu
1354* Source Representation:: 
1355* Foreign Language Representation:: 
1356* File Naming Topics and Utilities:: 
1357* Configuration Pragmas:: 
1358* Generating Object Files:: 
1359* Source Dependencies:: 
1360* The Ada Library Information Files:: 
1361* Binding an Ada Program:: 
1362* GNAT and Libraries:: 
1363* Conditional Compilation:: 
1364* Mixed Language Programming:: 
1365* GNAT and Other Compilation Models:: 
1366* Using GNAT Files with External Tools:: 
1367
1368@end menu
1369
1370@node Source Representation,Foreign Language Representation,,The GNAT Compilation Model
1371@anchor{gnat_ugn/the_gnat_compilation_model source-representation}@anchor{3f}@anchor{gnat_ugn/the_gnat_compilation_model id2}@anchor{48}
1372@section Source Representation
1373
1374
1375@geindex Latin-1
1376
1377@geindex VT
1378@geindex HT
1379@geindex CR
1380@geindex LF
1381@geindex FF
1382
1383Ada source programs are represented in standard text files, using
1384Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
13857-bit ASCII set, plus additional characters used for
1386representing foreign languages (see @ref{40,,Foreign Language Representation}
1387for support of non-USA character sets). The format effector characters
1388are represented using their standard ASCII encodings, as follows:
1389
1390@quotation
1391
1392
1393@multitable {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxx} 
1394@item
1395
1396Character
1397
1398@tab
1399
1400Effect
1401
1402@tab
1403
1404Code
1405
1406@item
1407
1408@code{VT}
1409
1410@tab
1411
1412Vertical tab
1413
1414@tab
1415
1416@cite{16#0B#}
1417
1418@item
1419
1420@code{HT}
1421
1422@tab
1423
1424Horizontal tab
1425
1426@tab
1427
1428@cite{16#09#}
1429
1430@item
1431
1432@code{CR}
1433
1434@tab
1435
1436Carriage return
1437
1438@tab
1439
1440@cite{16#0D#}
1441
1442@item
1443
1444@code{LF}
1445
1446@tab
1447
1448Line feed
1449
1450@tab
1451
1452@cite{16#0A#}
1453
1454@item
1455
1456@code{FF}
1457
1458@tab
1459
1460Form feed
1461
1462@tab
1463
1464@cite{16#0C#}
1465
1466@end multitable
1467
1468@end quotation
1469
1470Source files are in standard text file format. In addition, GNAT will
1471recognize a wide variety of stream formats, in which the end of
1472physical lines is marked by any of the following sequences:
1473@cite{LF}, @cite{CR}, @cite{CR-LF}, or @cite{LF-CR}. This is useful
1474in accommodating files that are imported from other operating systems.
1475
1476@geindex End of source file; Source file@comma{} end
1477
1478@geindex SUB (control character)
1479
1480The end of a source file is normally represented by the physical end of
1481file. However, the control character @cite{16#1A#} (@code{SUB}) is also
1482recognized as signalling the end of the source file. Again, this is
1483provided for compatibility with other operating systems where this
1484code is used to represent the end of file.
1485
1486@geindex spec (definition)
1487@geindex compilation (definition)
1488
1489Each file contains a single Ada compilation unit, including any pragmas
1490associated with the unit. For example, this means you must place a
1491package declaration (a package @cite{spec}) and the corresponding body in
1492separate files. An Ada @cite{compilation} (which is a sequence of
1493compilation units) is represented using a sequence of files. Similarly,
1494you will place each subunit or child unit in a separate file.
1495
1496@node Foreign Language Representation,File Naming Topics and Utilities,Source Representation,The GNAT Compilation Model
1497@anchor{gnat_ugn/the_gnat_compilation_model foreign-language-representation}@anchor{40}@anchor{gnat_ugn/the_gnat_compilation_model id3}@anchor{49}
1498@section Foreign Language Representation
1499
1500
1501GNAT supports the standard character sets defined in Ada as well as
1502several other non-standard character sets for use in localized versions
1503of the compiler (@ref{4a,,Character Set Control}).
1504
1505@menu
1506* Latin-1:: 
1507* Other 8-Bit Codes:: 
1508* Wide_Character Encodings:: 
1509* Wide_Wide_Character Encodings:: 
1510
1511@end menu
1512
1513@node Latin-1,Other 8-Bit Codes,,Foreign Language Representation
1514@anchor{gnat_ugn/the_gnat_compilation_model id4}@anchor{4b}@anchor{gnat_ugn/the_gnat_compilation_model latin-1}@anchor{4c}
1515@subsection Latin-1
1516
1517
1518@geindex Latin-1
1519
1520The basic character set is Latin-1. This character set is defined by ISO
1521standard 8859, part 1. The lower half (character codes @cite{16#00#}
1522... @cite{16#7F#)} is identical to standard ASCII coding, but the upper
1523half is used to represent additional characters. These include extended letters
1524used by European languages, such as French accents, the vowels with umlauts
1525used in German, and the extra letter A-ring used in Swedish.
1526
1527@geindex Ada.Characters.Latin_1
1528
1529For a complete list of Latin-1 codes and their encodings, see the source
1530file of library unit @cite{Ada.Characters.Latin_1} in file
1531@code{a-chlat1.ads}.
1532You may use any of these extended characters freely in character or
1533string literals. In addition, the extended characters that represent
1534letters can be used in identifiers.
1535
1536@node Other 8-Bit Codes,Wide_Character Encodings,Latin-1,Foreign Language Representation
1537@anchor{gnat_ugn/the_gnat_compilation_model other-8-bit-codes}@anchor{4d}@anchor{gnat_ugn/the_gnat_compilation_model id5}@anchor{4e}
1538@subsection Other 8-Bit Codes
1539
1540
1541GNAT also supports several other 8-bit coding schemes:
1542
1543@geindex Latin-2
1544
1545@geindex ISO 8859-2
1546
1547
1548@table @asis
1549
1550@item @emph{ISO 8859-2 (Latin-2)}
1551
1552Latin-2 letters allowed in identifiers, with uppercase and lowercase
1553equivalence.
1554@end table
1555
1556@geindex Latin-3
1557
1558@geindex ISO 8859-3
1559
1560
1561@table @asis
1562
1563@item @emph{ISO 8859-3 (Latin-3)}
1564
1565Latin-3 letters allowed in identifiers, with uppercase and lowercase
1566equivalence.
1567@end table
1568
1569@geindex Latin-4
1570
1571@geindex ISO 8859-4
1572
1573
1574@table @asis
1575
1576@item @emph{ISO 8859-4 (Latin-4)}
1577
1578Latin-4 letters allowed in identifiers, with uppercase and lowercase
1579equivalence.
1580@end table
1581
1582@geindex ISO 8859-5
1583
1584@geindex Cyrillic
1585
1586
1587@table @asis
1588
1589@item @emph{ISO 8859-5 (Cyrillic)}
1590
1591ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1592lowercase equivalence.
1593@end table
1594
1595@geindex ISO 8859-15
1596
1597@geindex Latin-9
1598
1599
1600@table @asis
1601
1602@item @emph{ISO 8859-15 (Latin-9)}
1603
1604ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1605lowercase equivalence
1606@end table
1607
1608@geindex code page 437 (IBM PC)
1609
1610
1611@table @asis
1612
1613@item @emph{IBM PC (code page 437)}
1614
1615This code page is the normal default for PCs in the U.S. It corresponds
1616to the original IBM PC character set. This set has some, but not all, of
1617the extended Latin-1 letters, but these letters do not have the same
1618encoding as Latin-1. In this mode, these letters are allowed in
1619identifiers with uppercase and lowercase equivalence.
1620@end table
1621
1622@geindex code page 850 (IBM PC)
1623
1624
1625@table @asis
1626
1627@item @emph{IBM PC (code page 850)}
1628
1629This code page is a modification of 437 extended to include all the
1630Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1631mode, all these letters are allowed in identifiers with uppercase and
1632lowercase equivalence.
1633
1634@item @emph{Full Upper 8-bit}
1635
1636Any character in the range 80-FF allowed in identifiers, and all are
1637considered distinct. In other words, there are no uppercase and lowercase
1638equivalences in this range. This is useful in conjunction with
1639certain encoding schemes used for some foreign character sets (e.g.,
1640the typical method of representing Chinese characters on the PC).
1641
1642@item @emph{No Upper-Half}
1643
1644No upper-half characters in the range 80-FF are allowed in identifiers.
1645This gives Ada 83 compatibility for identifier names.
1646@end table
1647
1648For precise data on the encodings permitted, and the uppercase and lowercase
1649equivalences that are recognized, see the file @code{csets.adb} in
1650the GNAT compiler sources. You will need to obtain a full source release
1651of GNAT to obtain this file.
1652
1653@node Wide_Character Encodings,Wide_Wide_Character Encodings,Other 8-Bit Codes,Foreign Language Representation
1654@anchor{gnat_ugn/the_gnat_compilation_model id6}@anchor{4f}@anchor{gnat_ugn/the_gnat_compilation_model wide-character-encodings}@anchor{50}
1655@subsection Wide_Character Encodings
1656
1657
1658GNAT allows wide character codes to appear in character and string
1659literals, and also optionally in identifiers, by means of the following
1660possible encoding schemes:
1661
1662
1663@table @asis
1664
1665@item @emph{Hex Coding}
1666
1667In this encoding, a wide character is represented by the following five
1668character sequence:
1669
1670@example
1671ESC a b c d
1672@end example
1673
1674where @cite{a}, @cite{b}, @cite{c}, @cite{d} are the four hexadecimal
1675characters (using uppercase letters) of the wide character code. For
1676example, ESC A345 is used to represent the wide character with code
1677@cite{16#A345#}.
1678This scheme is compatible with use of the full Wide_Character set.
1679
1680@item @emph{Upper-Half Coding}
1681
1682@geindex Upper-Half Coding
1683
1684The wide character with encoding @cite{16#abcd#} where the upper bit is on
1685(in other words, 'a' is in the range 8-F) is represented as two bytes,
1686@cite{16#ab#} and @cite{16#cd#}. The second byte cannot be a format control
1687character, but is not required to be in the upper half. This method can
1688be also used for shift-JIS or EUC, where the internal coding matches the
1689external coding.
1690
1691@item @emph{Shift JIS Coding}
1692
1693@geindex Shift JIS Coding
1694
1695A wide character is represented by a two-character sequence,
1696@cite{16#ab#} and
1697@cite{16#cd#}, with the restrictions described for upper-half encoding as
1698described above. The internal character code is the corresponding JIS
1699character according to the standard algorithm for Shift-JIS
1700conversion. Only characters defined in the JIS code set table can be
1701used with this encoding method.
1702
1703@item @emph{EUC Coding}
1704
1705@geindex EUC Coding
1706
1707A wide character is represented by a two-character sequence
1708@cite{16#ab#} and
1709@cite{16#cd#}, with both characters being in the upper half. The internal
1710character code is the corresponding JIS character according to the EUC
1711encoding algorithm. Only characters defined in the JIS code set table
1712can be used with this encoding method.
1713
1714@item @emph{UTF-8 Coding}
1715
1716A wide character is represented using
1717UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
171810646-1/Am.2. Depending on the character value, the representation
1719is a one, two, or three byte sequence:
1720
1721@example
172216#0000#-16#007f#: 2#0`xxxxxxx`#
172316#0080#-16#07ff#: 2#110`xxxxx`# 2#10`xxxxxx`#
172416#0800#-16#ffff#: 2#1110`xxxx`# 2#10`xxxxxx`# 2#10`xxxxxx`#
1725@end example
1726
1727where the @cite{xxx} bits correspond to the left-padded bits of the
172816-bit character value. Note that all lower half ASCII characters
1729are represented as ASCII bytes and all upper half characters and
1730other wide characters are represented as sequences of upper-half
1731(The full UTF-8 scheme allows for encoding 31-bit characters as
17326-byte sequences, and in the following section on wide wide
1733characters, the use of these sequences is documented).
1734
1735@item @emph{Brackets Coding}
1736
1737In this encoding, a wide character is represented by the following eight
1738character sequence:
1739
1740@example
1741[ " a b c d " ]
1742@end example
1743
1744where @cite{a}, @cite{b}, @cite{c}, @cite{d} are the four hexadecimal
1745characters (using uppercase letters) of the wide character code. For
1746example, ['A345'] is used to represent the wide character with code
1747@cite{16#A345#}. It is also possible (though not required) to use the
1748Brackets coding for upper half characters. For example, the code
1749@cite{16#A3#} can be represented as @cite{['A3']}.
1750
1751This scheme is compatible with use of the full Wide_Character set,
1752and is also the method used for wide character encoding in some standard
1753ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
1754@end table
1755
1756@cartouche
1757@quotation Note 
1758Some of these coding schemes do not permit the full use of the
1759Ada character set. For example, neither Shift JIS nor EUC allow the
1760use of the upper half of the Latin-1 set.
1761@end quotation
1762@end cartouche
1763
1764@node Wide_Wide_Character Encodings,,Wide_Character Encodings,Foreign Language Representation
1765@anchor{gnat_ugn/the_gnat_compilation_model id7}@anchor{51}@anchor{gnat_ugn/the_gnat_compilation_model wide-wide-character-encodings}@anchor{52}
1766@subsection Wide_Wide_Character Encodings
1767
1768
1769GNAT allows wide wide character codes to appear in character and string
1770literals, and also optionally in identifiers, by means of the following
1771possible encoding schemes:
1772
1773
1774@table @asis
1775
1776@item @emph{UTF-8 Coding}
1777
1778A wide character is represented using
1779UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
178010646-1/Am.2. Depending on the character value, the representation
1781of character codes with values greater than 16#FFFF# is a
1782is a four, five, or six byte sequence:
1783
1784@example
178516#01_0000#-16#10_FFFF#:     11110xxx 10xxxxxx 10xxxxxx
1786                             10xxxxxx
178716#0020_0000#-16#03FF_FFFF#: 111110xx 10xxxxxx 10xxxxxx
1788                             10xxxxxx 10xxxxxx
178916#0400_0000#-16#7FFF_FFFF#: 1111110x 10xxxxxx 10xxxxxx
1790                             10xxxxxx 10xxxxxx 10xxxxxx
1791@end example
1792
1793where the @cite{xxx} bits correspond to the left-padded bits of the
179432-bit character value.
1795
1796@item @emph{Brackets Coding}
1797
1798In this encoding, a wide wide character is represented by the following ten or
1799twelve byte character sequence:
1800
1801@example
1802[ " a b c d e f " ]
1803[ " a b c d e f g h " ]
1804@end example
1805
1806where @cite{a-h} are the six or eight hexadecimal
1807characters (using uppercase letters) of the wide wide character code. For
1808example, ["1F4567"] is used to represent the wide wide character with code
1809@cite{16#001F_4567#}.
1810
1811This scheme is compatible with use of the full Wide_Wide_Character set,
1812and is also the method used for wide wide character encoding in some standard
1813ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
1814@end table
1815
1816@node File Naming Topics and Utilities,Configuration Pragmas,Foreign Language Representation,The GNAT Compilation Model
1817@anchor{gnat_ugn/the_gnat_compilation_model id8}@anchor{53}@anchor{gnat_ugn/the_gnat_compilation_model file-naming-topics-and-utilities}@anchor{41}
1818@section File Naming Topics and Utilities
1819
1820
1821GNAT has a default file naming scheme and also provides the user with
1822a high degree of control over how the names and extensions of the
1823source files correspond to the Ada compilation units that they contain.
1824
1825@menu
1826* File Naming Rules:: 
1827* Using Other File Names:: 
1828* Alternative File Naming Schemes:: 
1829* Handling Arbitrary File Naming Conventions with gnatname:: 
1830* File Name Krunching with gnatkr:: 
1831* Renaming Files with gnatchop:: 
1832
1833@end menu
1834
1835@node File Naming Rules,Using Other File Names,,File Naming Topics and Utilities
1836@anchor{gnat_ugn/the_gnat_compilation_model file-naming-rules}@anchor{54}@anchor{gnat_ugn/the_gnat_compilation_model id9}@anchor{55}
1837@subsection File Naming Rules
1838
1839
1840The default file name is determined by the name of the unit that the
1841file contains. The name is formed by taking the full expanded name of
1842the unit and replacing the separating dots with hyphens and using
1843lowercase for all letters.
1844
1845An exception arises if the file name generated by the above rules starts
1846with one of the characters
1847@cite{a}, @cite{g}, @cite{i}, or @cite{s}, and the second character is a
1848minus. In this case, the character tilde is used in place
1849of the minus. The reason for this special rule is to avoid clashes with
1850the standard names for child units of the packages System, Ada,
1851Interfaces, and GNAT, which use the prefixes
1852@cite{s-}, @cite{a-}, @cite{i-}, and @cite{g-},
1853respectively.
1854
1855The file extension is @code{.ads} for a spec and
1856@code{.adb} for a body. The following table shows some
1857examples of these rules.
1858
1859@quotation
1860
1861
1862@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
1863@item
1864
1865Source File
1866
1867@tab
1868
1869Ada Compilation Unit
1870
1871@item
1872
1873@code{main.ads}
1874
1875@tab
1876
1877Main (spec)
1878
1879@item
1880
1881@code{main.adb}
1882
1883@tab
1884
1885Main (body)
1886
1887@item
1888
1889@code{arith_functions.ads}
1890
1891@tab
1892
1893Arith_Functions (package spec)
1894
1895@item
1896
1897@code{arith_functions.adb}
1898
1899@tab
1900
1901Arith_Functions (package body)
1902
1903@item
1904
1905@code{func-spec.ads}
1906
1907@tab
1908
1909Func.Spec (child package spec)
1910
1911@item
1912
1913@code{func-spec.adb}
1914
1915@tab
1916
1917Func.Spec (child package body)
1918
1919@item
1920
1921@code{main-sub.adb}
1922
1923@tab
1924
1925Sub (subunit of Main)
1926
1927@item
1928
1929@code{a~bad.adb}
1930
1931@tab
1932
1933A.Bad (child package body)
1934
1935@end multitable
1936
1937@end quotation
1938
1939Following these rules can result in excessively long
1940file names if corresponding
1941unit names are long (for example, if child units or subunits are
1942heavily nested). An option is available to shorten such long file names
1943(called file name 'krunching'). This may be particularly useful when
1944programs being developed with GNAT are to be used on operating systems
1945with limited file name lengths. @ref{56,,Using gnatkr}.
1946
1947Of course, no file shortening algorithm can guarantee uniqueness over
1948all possible unit names; if file name krunching is used, it is your
1949responsibility to ensure no name clashes occur. Alternatively you
1950can specify the exact file names that you want used, as described
1951in the next section. Finally, if your Ada programs are migrating from a
1952compiler with a different naming convention, you can use the gnatchop
1953utility to produce source files that follow the GNAT naming conventions.
1954(For details see @ref{38,,Renaming Files with gnatchop}.)
1955
1956Note: in the case of Windows or Mac OS operating systems, case is not
1957significant. So for example on @cite{Windows} if the canonical name is
1958@cite{main-sub.adb}, you can use the file name @code{Main-Sub.adb} instead.
1959However, case is significant for other operating systems, so for example,
1960if you want to use other than canonically cased file names on a Unix system,
1961you need to follow the procedures described in the next section.
1962
1963@node Using Other File Names,Alternative File Naming Schemes,File Naming Rules,File Naming Topics and Utilities
1964@anchor{gnat_ugn/the_gnat_compilation_model id10}@anchor{57}@anchor{gnat_ugn/the_gnat_compilation_model using-other-file-names}@anchor{37}
1965@subsection Using Other File Names
1966
1967
1968@geindex File names
1969
1970In the previous section, we have described the default rules used by
1971GNAT to determine the file name in which a given unit resides. It is
1972often convenient to follow these default rules, and if you follow them,
1973the compiler knows without being explicitly told where to find all
1974the files it needs.
1975
1976@geindex Source_File_Name pragma
1977
1978However, in some cases, particularly when a program is imported from
1979another Ada compiler environment, it may be more convenient for the
1980programmer to specify which file names contain which units. GNAT allows
1981arbitrary file names to be used by means of the Source_File_Name pragma.
1982The form of this pragma is as shown in the following examples:
1983
1984@example
1985pragma Source_File_Name (My_Utilities.Stacks,
1986  Spec_File_Name => "myutilst_a.ada");
1987pragma Source_File_name (My_Utilities.Stacks,
1988  Body_File_Name => "myutilst.ada");
1989@end example
1990
1991As shown in this example, the first argument for the pragma is the unit
1992name (in this example a child unit). The second argument has the form
1993of a named association. The identifier
1994indicates whether the file name is for a spec or a body;
1995the file name itself is given by a string literal.
1996
1997The source file name pragma is a configuration pragma, which means that
1998normally it will be placed in the @code{gnat.adc}
1999file used to hold configuration
2000pragmas that apply to a complete compilation environment.
2001For more details on how the @code{gnat.adc} file is created and used
2002see @ref{58,,Handling of Configuration Pragmas}.
2003
2004@geindex gnat.adc
2005
2006GNAT allows completely arbitrary file names to be specified using the
2007source file name pragma. However, if the file name specified has an
2008extension other than @code{.ads} or @code{.adb} it is necessary to use
2009a special syntax when compiling the file. The name in this case must be
2010preceded by the special sequence @emph{-x} followed by a space and the name
2011of the language, here @cite{ada}, as in:
2012
2013@example
2014$ gcc -c -x ada peculiar_file_name.sim
2015@end example
2016
2017@cite{gnatmake} handles non-standard file names in the usual manner (the
2018non-standard file name for the main program is simply used as the
2019argument to gnatmake). Note that if the extension is also non-standard,
2020then it must be included in the @cite{gnatmake} command, it may not
2021be omitted.
2022
2023@node Alternative File Naming Schemes,Handling Arbitrary File Naming Conventions with gnatname,Using Other File Names,File Naming Topics and Utilities
2024@anchor{gnat_ugn/the_gnat_compilation_model id11}@anchor{59}@anchor{gnat_ugn/the_gnat_compilation_model alternative-file-naming-schemes}@anchor{5a}
2025@subsection Alternative File Naming Schemes
2026
2027
2028@geindex File naming schemes
2029@geindex alternative
2030
2031@geindex File names
2032
2033The previous section described the use of the @cite{Source_File_Name}
2034pragma to allow arbitrary names to be assigned to individual source files.
2035However, this approach requires one pragma for each file, and especially in
2036large systems can result in very long @code{gnat.adc} files, and also create
2037a maintenance problem.
2038
2039@geindex Source_File_Name pragma
2040
2041GNAT also provides a facility for specifying systematic file naming schemes
2042other than the standard default naming scheme previously described. An
2043alternative scheme for naming is specified by the use of
2044@cite{Source_File_Name} pragmas having the following format:
2045
2046@example
2047pragma Source_File_Name (
2048   Spec_File_Name  => FILE_NAME_PATTERN
2049 [ , Casing          => CASING_SPEC]
2050 [ , Dot_Replacement => STRING_LITERAL ] );
2051
2052pragma Source_File_Name (
2053   Body_File_Name  => FILE_NAME_PATTERN
2054 [ , Casing          => CASING_SPEC ]
2055 [ , Dot_Replacement => STRING_LITERAL ] ) ;
2056
2057pragma Source_File_Name (
2058   Subunit_File_Name  => FILE_NAME_PATTERN
2059 [ , Casing          => CASING_SPEC ]
2060 [ , Dot_Replacement => STRING_LITERAL ] ) ;
2061
2062FILE_NAME_PATTERN ::= STRING_LITERAL
2063CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2064@end example
2065
2066The @cite{FILE_NAME_PATTERN} string shows how the file name is constructed.
2067It contains a single asterisk character, and the unit name is substituted
2068systematically for this asterisk. The optional parameter
2069@cite{Casing} indicates
2070whether the unit name is to be all upper-case letters, all lower-case letters,
2071or mixed-case. If no
2072@cite{Casing} parameter is used, then the default is all
2073lower-case.
2074
2075The optional @cite{Dot_Replacement} string is used to replace any periods
2076that occur in subunit or child unit names. If no @cite{Dot_Replacement}
2077argument is used then separating dots appear unchanged in the resulting
2078file name.
2079Although the above syntax indicates that the
2080@cite{Casing} argument must appear
2081before the @cite{Dot_Replacement} argument, but it
2082is also permissible to write these arguments in the opposite order.
2083
2084As indicated, it is possible to specify different naming schemes for
2085bodies, specs, and subunits. Quite often the rule for subunits is the
2086same as the rule for bodies, in which case, there is no need to give
2087a separate @cite{Subunit_File_Name} rule, and in this case the
2088@cite{Body_File_name} rule is used for subunits as well.
2089
2090The separate rule for subunits can also be used to implement the rather
2091unusual case of a compilation environment (e.g., a single directory) which
2092contains a subunit and a child unit with the same unit name. Although
2093both units cannot appear in the same partition, the Ada Reference Manual
2094allows (but does not require) the possibility of the two units coexisting
2095in the same environment.
2096
2097The file name translation works in the following steps:
2098
2099
2100@itemize *
2101
2102@item 
2103If there is a specific @cite{Source_File_Name} pragma for the given unit,
2104then this is always used, and any general pattern rules are ignored.
2105
2106@item 
2107If there is a pattern type @cite{Source_File_Name} pragma that applies to
2108the unit, then the resulting file name will be used if the file exists. If
2109more than one pattern matches, the latest one will be tried first, and the
2110first attempt resulting in a reference to a file that exists will be used.
2111
2112@item 
2113If no pattern type @cite{Source_File_Name} pragma that applies to the unit
2114for which the corresponding file exists, then the standard GNAT default
2115naming rules are used.
2116@end itemize
2117
2118As an example of the use of this mechanism, consider a commonly used scheme
2119in which file names are all lower case, with separating periods copied
2120unchanged to the resulting file name, and specs end with @code{.1.ada}, and
2121bodies end with @code{.2.ada}. GNAT will follow this scheme if the following
2122two pragmas appear:
2123
2124@example
2125pragma Source_File_Name
2126  (Spec_File_Name => ".1.ada");
2127pragma Source_File_Name
2128  (Body_File_Name => ".2.ada");
2129@end example
2130
2131The default GNAT scheme is actually implemented by providing the following
2132default pragmas internally:
2133
2134@example
2135pragma Source_File_Name
2136  (Spec_File_Name => ".ads", Dot_Replacement => "-");
2137pragma Source_File_Name
2138  (Body_File_Name => ".adb", Dot_Replacement => "-");
2139@end example
2140
2141Our final example implements a scheme typically used with one of the
2142Ada 83 compilers, where the separator character for subunits was '__'
2143(two underscores), specs were identified by adding @code{_.ADA}, bodies
2144by adding @code{.ADA}, and subunits by
2145adding @code{.SEP}. All file names were
2146upper case. Child units were not present of course since this was an
2147Ada 83 compiler, but it seems reasonable to extend this scheme to use
2148the same double underscore separator for child units.
2149
2150@example
2151pragma Source_File_Name
2152  (Spec_File_Name => "_.ADA",
2153   Dot_Replacement => "__",
2154   Casing = Uppercase);
2155pragma Source_File_Name
2156  (Body_File_Name => ".ADA",
2157   Dot_Replacement => "__",
2158   Casing = Uppercase);
2159pragma Source_File_Name
2160  (Subunit_File_Name => ".SEP",
2161   Dot_Replacement => "__",
2162   Casing = Uppercase);
2163@end example
2164
2165@geindex gnatname
2166
2167@node Handling Arbitrary File Naming Conventions with gnatname,File Name Krunching with gnatkr,Alternative File Naming Schemes,File Naming Topics and Utilities
2168@anchor{gnat_ugn/the_gnat_compilation_model handling-arbitrary-file-naming-conventions-with-gnatname}@anchor{5b}@anchor{gnat_ugn/the_gnat_compilation_model id12}@anchor{5c}
2169@subsection Handling Arbitrary File Naming Conventions with @cite{gnatname}
2170
2171
2172@geindex File Naming Conventions
2173
2174@menu
2175* Arbitrary File Naming Conventions:: 
2176* Running gnatname:: 
2177* Switches for gnatname:: 
2178* Examples of gnatname Usage:: 
2179
2180@end menu
2181
2182@node Arbitrary File Naming Conventions,Running gnatname,,Handling Arbitrary File Naming Conventions with gnatname
2183@anchor{gnat_ugn/the_gnat_compilation_model arbitrary-file-naming-conventions}@anchor{5d}@anchor{gnat_ugn/the_gnat_compilation_model id13}@anchor{5e}
2184@subsubsection Arbitrary File Naming Conventions
2185
2186
2187The GNAT compiler must be able to know the source file name of a compilation
2188unit.  When using the standard GNAT default file naming conventions
2189(@cite{.ads} for specs, @cite{.adb} for bodies), the GNAT compiler
2190does not need additional information.
2191
2192When the source file names do not follow the standard GNAT default file naming
2193conventions, the GNAT compiler must be given additional information through
2194a configuration pragmas file (@ref{16,,Configuration Pragmas})
2195or a project file.
2196When the non-standard file naming conventions are well-defined,
2197a small number of pragmas @cite{Source_File_Name} specifying a naming pattern
2198(@ref{5a,,Alternative File Naming Schemes}) may be sufficient. However,
2199if the file naming conventions are irregular or arbitrary, a number
2200of pragma @cite{Source_File_Name} for individual compilation units
2201must be defined.
2202To help maintain the correspondence between compilation unit names and
2203source file names within the compiler,
2204GNAT provides a tool @cite{gnatname} to generate the required pragmas for a
2205set of files.
2206
2207@node Running gnatname,Switches for gnatname,Arbitrary File Naming Conventions,Handling Arbitrary File Naming Conventions with gnatname
2208@anchor{gnat_ugn/the_gnat_compilation_model running-gnatname}@anchor{5f}@anchor{gnat_ugn/the_gnat_compilation_model id14}@anchor{60}
2209@subsubsection Running @cite{gnatname}
2210
2211
2212The usual form of the @cite{gnatname} command is:
2213
2214@example
2215$ gnatname [`switches`] `naming_pattern` [`naming_patterns`]
2216    [--and [`switches`] `naming_pattern` [`naming_patterns`]]
2217@end example
2218
2219All of the arguments are optional. If invoked without any argument,
2220@cite{gnatname} will display its usage.
2221
2222When used with at least one naming pattern, @cite{gnatname} will attempt to
2223find all the compilation units in files that follow at least one of the
2224naming patterns. To find these compilation units,
2225@cite{gnatname} will use the GNAT compiler in syntax-check-only mode on all
2226regular files.
2227
2228One or several Naming Patterns may be given as arguments to @cite{gnatname}.
2229Each Naming Pattern is enclosed between double quotes (or single
2230quotes on Windows).
2231A Naming Pattern is a regular expression similar to the wildcard patterns
2232used in file names by the Unix shells or the DOS prompt.
2233
2234@cite{gnatname} may be called with several sections of directories/patterns.
2235Sections are separated by switch @cite{--and}. In each section, there must be
2236at least one pattern. If no directory is specified in a section, the current
2237directory (or the project directory is @cite{-P} is used) is implied.
2238The options other that the directory switches and the patterns apply globally
2239even if they are in different sections.
2240
2241Examples of Naming Patterns are:
2242
2243@example
2244"*.[12].ada"
2245"*.ad[sb]*"
2246"body_*"    "spec_*"
2247@end example
2248
2249For a more complete description of the syntax of Naming Patterns,
2250see the second kind of regular expressions described in @code{g-regexp.ads}
2251(the 'Glob' regular expressions).
2252
2253When invoked with no switch @cite{-P}, @cite{gnatname} will create a
2254configuration pragmas file @code{gnat.adc} in the current working directory,
2255with pragmas @cite{Source_File_Name} for each file that contains a valid Ada
2256unit.
2257
2258@node Switches for gnatname,Examples of gnatname Usage,Running gnatname,Handling Arbitrary File Naming Conventions with gnatname
2259@anchor{gnat_ugn/the_gnat_compilation_model id15}@anchor{61}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatname}@anchor{62}
2260@subsubsection Switches for @cite{gnatname}
2261
2262
2263Switches for @cite{gnatname} must precede any specified Naming Pattern.
2264
2265You may specify any of the following switches to @cite{gnatname}:
2266
2267@geindex --version (gnatname)
2268
2269
2270@table @asis
2271
2272@item @code{--version}
2273
2274Display Copyright and version, then exit disregarding all other options.
2275@end table
2276
2277@geindex --help (gnatname)
2278
2279
2280@table @asis
2281
2282@item @code{--help}
2283
2284If @emph{--version} was not used, display usage, then exit disregarding
2285all other options.
2286
2287@item @code{--subdirs=@emph{dir}}
2288
2289Real object, library or exec directories are subdirectories <dir> of the
2290specified ones.
2291
2292@item @code{--no-backup}
2293
2294Do not create a backup copy of an existing project file.
2295
2296@item @code{--and}
2297
2298Start another section of directories/patterns.
2299@end table
2300
2301@geindex -c (gnatname)
2302
2303
2304@table @asis
2305
2306@item @code{-c@emph{filename}}
2307
2308Create a configuration pragmas file @code{filename} (instead of the default
2309@code{gnat.adc}).
2310There may be zero, one or more space between @emph{-c} and
2311@code{filename}.
2312@code{filename} may include directory information. @code{filename} must be
2313writable. There may be only one switch @emph{-c}.
2314When a switch @emph{-c} is
2315specified, no switch @emph{-P} may be specified (see below).
2316@end table
2317
2318@geindex -d (gnatname)
2319
2320
2321@table @asis
2322
2323@item @code{-d@emph{dir}}
2324
2325Look for source files in directory @code{dir}. There may be zero, one or more
2326spaces between @emph{-d} and @code{dir}.
2327@code{dir} may end with @cite{/**}, that is it may be of the form
2328@cite{root_dir/**}. In this case, the directory @cite{root_dir} and all of its
2329subdirectories, recursively, have to be searched for sources.
2330When a switch @emph{-d}
2331is specified, the current working directory will not be searched for source
2332files, unless it is explicitly specified with a @emph{-d}
2333or @emph{-D} switch.
2334Several switches @emph{-d} may be specified.
2335If @code{dir} is a relative path, it is relative to the directory of
2336the configuration pragmas file specified with switch
2337@emph{-c},
2338or to the directory of the project file specified with switch
2339@emph{-P} or,
2340if neither switch @emph{-c}
2341nor switch @emph{-P} are specified, it is relative to the
2342current working directory. The directory
2343specified with switch @emph{-d} must exist and be readable.
2344@end table
2345
2346@geindex -D (gnatname)
2347
2348
2349@table @asis
2350
2351@item @code{-D@emph{filename}}
2352
2353Look for source files in all directories listed in text file @code{filename}.
2354There may be zero, one or more spaces between @emph{-D}
2355and @code{filename}.
2356@code{filename} must be an existing, readable text file.
2357Each nonempty line in @code{filename} must be a directory.
2358Specifying switch @emph{-D} is equivalent to specifying as many
2359switches @emph{-d} as there are nonempty lines in
2360@code{file}.
2361
2362@item @code{-eL}
2363
2364Follow symbolic links when processing project files.
2365
2366@geindex -f (gnatname)
2367
2368@item @code{-f@emph{pattern}}
2369
2370Foreign patterns. Using this switch, it is possible to add sources of languages
2371other than Ada to the list of sources of a project file.
2372It is only useful if a -P switch is used.
2373For example,
2374
2375@example
2376gnatname -Pprj -f"*.c" "*.ada"
2377@end example
2378
2379will look for Ada units in all files with the @code{.ada} extension,
2380and will add to the list of file for project @code{prj.gpr} the C files
2381with extension @code{.c}.
2382
2383@geindex -h (gnatname)
2384
2385@item @code{-h}
2386
2387Output usage (help) information. The output is written to @code{stdout}.
2388
2389@geindex -P (gnatname)
2390
2391@item @code{-P@emph{proj}}
2392
2393Create or update project file @code{proj}. There may be zero, one or more space
2394between @emph{-P} and @code{proj}. @code{proj} may include directory
2395information. @code{proj} must be writable.
2396There may be only one switch @emph{-P}.
2397When a switch @emph{-P} is specified,
2398no switch @emph{-c} may be specified.
2399On all platforms, except on VMS, when @cite{gnatname} is invoked for an
2400existing project file <proj>.gpr, a backup copy of the project file is created
2401in the project directory with file name <proj>.gpr.saved_x. 'x' is the first
2402non negative number that makes this backup copy a new file.
2403
2404@geindex -v (gnatname)
2405
2406@item @code{-v}
2407
2408Verbose mode. Output detailed explanation of behavior to @code{stdout}.
2409This includes name of the file written, the name of the directories to search
2410and, for each file in those directories whose name matches at least one of
2411the Naming Patterns, an indication of whether the file contains a unit,
2412and if so the name of the unit.
2413@end table
2414
2415@geindex -v -v (gnatname)
2416
2417
2418@table @asis
2419
2420@item @code{-v -v}
2421
2422Very Verbose mode. In addition to the output produced in verbose mode,
2423for each file in the searched directories whose name matches none of
2424the Naming Patterns, an indication is given that there is no match.
2425
2426@geindex -x (gnatname)
2427
2428@item @code{-x@emph{pattern}}
2429
2430Excluded patterns. Using this switch, it is possible to exclude some files
2431that would match the name patterns. For example,
2432
2433@example
2434gnatname -x "*_nt.ada" "*.ada"
2435@end example
2436
2437will look for Ada units in all files with the @code{.ada} extension,
2438except those whose names end with @code{_nt.ada}.
2439@end table
2440
2441@node Examples of gnatname Usage,,Switches for gnatname,Handling Arbitrary File Naming Conventions with gnatname
2442@anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatname-usage}@anchor{63}@anchor{gnat_ugn/the_gnat_compilation_model id16}@anchor{64}
2443@subsubsection Examples of @cite{gnatname} Usage
2444
2445
2446@example
2447$ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
2448@end example
2449
2450In this example, the directory @code{/home/me} must already exist
2451and be writable. In addition, the directory
2452@code{/home/me/sources} (specified by
2453@emph{-d sources}) must exist and be readable.
2454
2455Note the optional spaces after @emph{-c} and @emph{-d}.
2456
2457@example
2458$ gnatname -P/home/me/proj -x "*_nt_body.ada"
2459-dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
2460@end example
2461
2462Note that several switches @emph{-d} may be used,
2463even in conjunction with one or several switches
2464@emph{-D}. Several Naming Patterns and one excluded pattern
2465are used in this example.
2466
2467@node File Name Krunching with gnatkr,Renaming Files with gnatchop,Handling Arbitrary File Naming Conventions with gnatname,File Naming Topics and Utilities
2468@anchor{gnat_ugn/the_gnat_compilation_model file-name-krunching-with-gnatkr}@anchor{65}@anchor{gnat_ugn/the_gnat_compilation_model id17}@anchor{66}
2469@subsection File Name Krunching with @cite{gnatkr}
2470
2471
2472@geindex gnatkr
2473
2474This chapter discusses the method used by the compiler to shorten
2475the default file names chosen for Ada units so that they do not
2476exceed the maximum length permitted. It also describes the
2477@cite{gnatkr} utility that can be used to determine the result of
2478applying this shortening.
2479
2480@menu
2481* About gnatkr:: 
2482* Using gnatkr:: 
2483* Krunching Method:: 
2484* Examples of gnatkr Usage:: 
2485
2486@end menu
2487
2488@node About gnatkr,Using gnatkr,,File Name Krunching with gnatkr
2489@anchor{gnat_ugn/the_gnat_compilation_model id18}@anchor{67}@anchor{gnat_ugn/the_gnat_compilation_model about-gnatkr}@anchor{68}
2490@subsubsection About @cite{gnatkr}
2491
2492
2493The default file naming rule in GNAT
2494is that the file name must be derived from
2495the unit name. The exact default rule is as follows:
2496
2497
2498@itemize *
2499
2500@item 
2501Take the unit name and replace all dots by hyphens.
2502
2503@item 
2504If such a replacement occurs in the
2505second character position of a name, and the first character is
2506@code{a}, @code{g}, @code{s}, or @code{i},
2507then replace the dot by the character
2508@code{~} (tilde)
2509instead of a minus.
2510
2511The reason for this exception is to avoid clashes
2512with the standard names for children of System, Ada, Interfaces,
2513and GNAT, which use the prefixes
2514@code{s-}, @code{a-}, @code{i-}, and @code{g-},
2515respectively.
2516@end itemize
2517
2518The @code{-gnatk@emph{nn}}
2519switch of the compiler activates a 'krunching'
2520circuit that limits file names to nn characters (where nn is a decimal
2521integer).
2522
2523The @cite{gnatkr} utility can be used to determine the krunched name for
2524a given file, when krunched to a specified maximum length.
2525
2526@node Using gnatkr,Krunching Method,About gnatkr,File Name Krunching with gnatkr
2527@anchor{gnat_ugn/the_gnat_compilation_model id19}@anchor{69}@anchor{gnat_ugn/the_gnat_compilation_model using-gnatkr}@anchor{56}
2528@subsubsection Using @cite{gnatkr}
2529
2530
2531The @cite{gnatkr} command has the form:
2532
2533@example
2534$ gnatkr `name` [`length`]
2535@end example
2536
2537@cite{name} is the uncrunched file name, derived from the name of the unit
2538in the standard manner described in the previous section (i.e., in particular
2539all dots are replaced by hyphens). The file name may or may not have an
2540extension (defined as a suffix of the form period followed by arbitrary
2541characters other than period). If an extension is present then it will
2542be preserved in the output. For example, when krunching @code{hellofile.ads}
2543to eight characters, the result will be hellofil.ads.
2544
2545Note: for compatibility with previous versions of @cite{gnatkr} dots may
2546appear in the name instead of hyphens, but the last dot will always be
2547taken as the start of an extension. So if @cite{gnatkr} is given an argument
2548such as @code{Hello.World.adb} it will be treated exactly as if the first
2549period had been a hyphen, and for example krunching to eight characters
2550gives the result @code{hellworl.adb}.
2551
2552Note that the result is always all lower case.
2553Characters of the other case are folded as required.
2554
2555@cite{length} represents the length of the krunched name. The default
2556when no argument is given is 8 characters. A length of zero stands for
2557unlimited, in other words do not chop except for system files where the
2558implied crunching length is always eight characters.
2559
2560The output is the krunched name. The output has an extension only if the
2561original argument was a file name with an extension.
2562
2563@node Krunching Method,Examples of gnatkr Usage,Using gnatkr,File Name Krunching with gnatkr
2564@anchor{gnat_ugn/the_gnat_compilation_model id20}@anchor{6a}@anchor{gnat_ugn/the_gnat_compilation_model krunching-method}@anchor{6b}
2565@subsubsection Krunching Method
2566
2567
2568The initial file name is determined by the name of the unit that the file
2569contains. The name is formed by taking the full expanded name of the
2570unit and replacing the separating dots with hyphens and
2571using lowercase
2572for all letters, except that a hyphen in the second character position is
2573replaced by a tilde if the first character is
2574@code{a}, @code{i}, @code{g}, or @code{s}.
2575The extension is @cite{.ads} for a
2576spec and @cite{.adb} for a body.
2577Krunching does not affect the extension, but the file name is shortened to
2578the specified length by following these rules:
2579
2580
2581@itemize *
2582
2583@item 
2584The name is divided into segments separated by hyphens, tildes or
2585underscores and all hyphens, tildes, and underscores are
2586eliminated. If this leaves the name short enough, we are done.
2587
2588@item 
2589If the name is too long, the longest segment is located (left-most
2590if there are two of equal length), and shortened by dropping
2591its last character. This is repeated until the name is short enough.
2592
2593As an example, consider the krunching of @code{our-strings-wide_fixed.adb}
2594to fit the name into 8 characters as required by some operating systems:
2595
2596@example
2597our-strings-wide_fixed 22
2598our strings wide fixed 19
2599our string  wide fixed 18
2600our strin   wide fixed 17
2601our stri    wide fixed 16
2602our stri    wide fixe  15
2603our str     wide fixe  14
2604our str     wid  fixe  13
2605our str     wid  fix   12
2606ou  str     wid  fix   11
2607ou  st      wid  fix   10
2608ou  st      wi   fix   9
2609ou  st      wi   fi    8
2610Final file name: oustwifi.adb
2611@end example
2612
2613@item 
2614The file names for all predefined units are always krunched to eight
2615characters. The krunching of these predefined units uses the following
2616special prefix replacements:
2617
2618
2619@multitable {xxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx} 
2620@item
2621
2622Prefix
2623
2624@tab
2625
2626Replacement
2627
2628@item
2629
2630@code{ada-}
2631
2632@tab
2633
2634@code{a-}
2635
2636@item
2637
2638@code{gnat-}
2639
2640@tab
2641
2642@code{g-}
2643
2644@item
2645
2646@code{interfac es-}
2647
2648@tab
2649
2650@code{i-}
2651
2652@item
2653
2654@code{system-}
2655
2656@tab
2657
2658@code{s-}
2659
2660@end multitable
2661
2662
2663These system files have a hyphen in the second character position. That
2664is why normal user files replace such a character with a
2665tilde, to avoid confusion with system file names.
2666
2667As an example of this special rule, consider
2668@code{ada-strings-wide_fixed.adb}, which gets krunched as follows:
2669
2670@example
2671ada-strings-wide_fixed 22
2672a-  strings wide fixed 18
2673a-  string  wide fixed 17
2674a-  strin   wide fixed 16
2675a-  stri    wide fixed 15
2676a-  stri    wide fixe  14
2677a-  str     wide fixe  13
2678a-  str     wid  fixe  12
2679a-  str     wid  fix   11
2680a-  st      wid  fix   10
2681a-  st      wi   fix   9
2682a-  st      wi   fi    8
2683Final file name: a-stwifi.adb
2684@end example
2685@end itemize
2686
2687Of course no file shortening algorithm can guarantee uniqueness over all
2688possible unit names, and if file name krunching is used then it is your
2689responsibility to ensure that no name clashes occur. The utility
2690program @cite{gnatkr} is supplied for conveniently determining the
2691krunched name of a file.
2692
2693@node Examples of gnatkr Usage,,Krunching Method,File Name Krunching with gnatkr
2694@anchor{gnat_ugn/the_gnat_compilation_model id21}@anchor{6c}@anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatkr-usage}@anchor{6d}
2695@subsubsection Examples of @cite{gnatkr} Usage
2696
2697
2698@example
2699$ gnatkr very_long_unit_name.ads      --> velounna.ads
2700$ gnatkr grandparent-parent-child.ads --> grparchi.ads
2701$ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
2702$ gnatkr grandparent-parent-child     --> grparchi
2703$ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
2704$ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
2705@end example
2706
2707@node Renaming Files with gnatchop,,File Name Krunching with gnatkr,File Naming Topics and Utilities
2708@anchor{gnat_ugn/the_gnat_compilation_model id22}@anchor{6e}@anchor{gnat_ugn/the_gnat_compilation_model renaming-files-with-gnatchop}@anchor{38}
2709@subsection Renaming Files with @cite{gnatchop}
2710
2711
2712@geindex gnatchop
2713
2714This chapter discusses how to handle files with multiple units by using
2715the @cite{gnatchop} utility. This utility is also useful in renaming
2716files to meet the standard GNAT default file naming conventions.
2717
2718@menu
2719* Handling Files with Multiple Units:: 
2720* Operating gnatchop in Compilation Mode:: 
2721* Command Line for gnatchop:: 
2722* Switches for gnatchop:: 
2723* Examples of gnatchop Usage:: 
2724
2725@end menu
2726
2727@node Handling Files with Multiple Units,Operating gnatchop in Compilation Mode,,Renaming Files with gnatchop
2728@anchor{gnat_ugn/the_gnat_compilation_model id23}@anchor{6f}@anchor{gnat_ugn/the_gnat_compilation_model handling-files-with-multiple-units}@anchor{70}
2729@subsubsection Handling Files with Multiple Units
2730
2731
2732The basic compilation model of GNAT requires that a file submitted to the
2733compiler have only one unit and there be a strict correspondence
2734between the file name and the unit name.
2735
2736The @cite{gnatchop} utility allows both of these rules to be relaxed,
2737allowing GNAT to process files which contain multiple compilation units
2738and files with arbitrary file names. @cite{gnatchop}
2739reads the specified file and generates one or more output files,
2740containing one unit per file. The unit and the file name correspond,
2741as required by GNAT.
2742
2743If you want to permanently restructure a set of 'foreign' files so that
2744they match the GNAT rules, and do the remaining development using the
2745GNAT structure, you can simply use @emph{gnatchop} once, generate the
2746new set of files and work with them from that point on.
2747
2748Alternatively, if you want to keep your files in the 'foreign' format,
2749perhaps to maintain compatibility with some other Ada compilation
2750system, you can set up a procedure where you use @emph{gnatchop} each
2751time you compile, regarding the source files that it writes as temporary
2752files that you throw away.
2753
2754Note that if your file containing multiple units starts with a byte order
2755mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
2756will each start with a copy of this BOM, meaning that they can be compiled
2757automatically in UTF-8 mode without needing to specify an explicit encoding.
2758
2759@node Operating gnatchop in Compilation Mode,Command Line for gnatchop,Handling Files with Multiple Units,Renaming Files with gnatchop
2760@anchor{gnat_ugn/the_gnat_compilation_model operating-gnatchop-in-compilation-mode}@anchor{71}@anchor{gnat_ugn/the_gnat_compilation_model id24}@anchor{72}
2761@subsubsection Operating gnatchop in Compilation Mode
2762
2763
2764The basic function of @cite{gnatchop} is to take a file with multiple units
2765and split it into separate files. The boundary between files is reasonably
2766clear, except for the issue of comments and pragmas. In default mode, the
2767rule is that any pragmas between units belong to the previous unit, except
2768that configuration pragmas always belong to the following unit. Any comments
2769belong to the following unit. These rules
2770almost always result in the right choice of
2771the split point without needing to mark it explicitly and most users will
2772find this default to be what they want. In this default mode it is incorrect to
2773submit a file containing only configuration pragmas, or one that ends in
2774configuration pragmas, to @cite{gnatchop}.
2775
2776However, using a special option to activate 'compilation mode',
2777@cite{gnatchop}
2778can perform another function, which is to provide exactly the semantics
2779required by the RM for handling of configuration pragmas in a compilation.
2780In the absence of configuration pragmas (at the main file level), this
2781option has no effect, but it causes such configuration pragmas to be handled
2782in a quite different manner.
2783
2784First, in compilation mode, if @cite{gnatchop} is given a file that consists of
2785only configuration pragmas, then this file is appended to the
2786@code{gnat.adc} file in the current directory. This behavior provides
2787the required behavior described in the RM for the actions to be taken
2788on submitting such a file to the compiler, namely that these pragmas
2789should apply to all subsequent compilations in the same compilation
2790environment. Using GNAT, the current directory, possibly containing a
2791@code{gnat.adc} file is the representation
2792of a compilation environment. For more information on the
2793@code{gnat.adc} file, see @ref{58,,Handling of Configuration Pragmas}.
2794
2795Second, in compilation mode, if @cite{gnatchop}
2796is given a file that starts with
2797configuration pragmas, and contains one or more units, then these
2798configuration pragmas are prepended to each of the chopped files. This
2799behavior provides the required behavior described in the RM for the
2800actions to be taken on compiling such a file, namely that the pragmas
2801apply to all units in the compilation, but not to subsequently compiled
2802units.
2803
2804Finally, if configuration pragmas appear between units, they are appended
2805to the previous unit. This results in the previous unit being illegal,
2806since the compiler does not accept configuration pragmas that follow
2807a unit. This provides the required RM behavior that forbids configuration
2808pragmas other than those preceding the first compilation unit of a
2809compilation.
2810
2811For most purposes, @cite{gnatchop} will be used in default mode. The
2812compilation mode described above is used only if you need exactly
2813accurate behavior with respect to compilations, and you have files
2814that contain multiple units and configuration pragmas. In this
2815circumstance the use of @cite{gnatchop} with the compilation mode
2816switch provides the required behavior, and is for example the mode
2817in which GNAT processes the ACVC tests.
2818
2819@node Command Line for gnatchop,Switches for gnatchop,Operating gnatchop in Compilation Mode,Renaming Files with gnatchop
2820@anchor{gnat_ugn/the_gnat_compilation_model id25}@anchor{73}@anchor{gnat_ugn/the_gnat_compilation_model command-line-for-gnatchop}@anchor{74}
2821@subsubsection Command Line for @cite{gnatchop}
2822
2823
2824The @cite{gnatchop} command has the form:
2825
2826@example
2827$ gnatchop switches file_name [file_name ...]
2828      [directory]
2829@end example
2830
2831The only required argument is the file name of the file to be chopped.
2832There are no restrictions on the form of this file name. The file itself
2833contains one or more Ada units, in normal GNAT format, concatenated
2834together. As shown, more than one file may be presented to be chopped.
2835
2836When run in default mode, @cite{gnatchop} generates one output file in
2837the current directory for each unit in each of the files.
2838
2839@cite{directory}, if specified, gives the name of the directory to which
2840the output files will be written. If it is not specified, all files are
2841written to the current directory.
2842
2843For example, given a
2844file called @code{hellofiles} containing
2845
2846@example
2847procedure Hello;
2848
2849with Ada.Text_IO; use Ada.Text_IO;
2850procedure Hello is
2851begin
2852   Put_Line ("Hello");
2853end Hello;
2854@end example
2855
2856the command
2857
2858@example
2859$ gnatchop hellofiles
2860@end example
2861
2862generates two files in the current directory, one called
2863@code{hello.ads} containing the single line that is the procedure spec,
2864and the other called @code{hello.adb} containing the remaining text. The
2865original file is not affected. The generated files can be compiled in
2866the normal manner.
2867
2868When gnatchop is invoked on a file that is empty or that contains only empty
2869lines and/or comments, gnatchop will not fail, but will not produce any
2870new sources.
2871
2872For example, given a
2873file called @code{toto.txt} containing
2874
2875@example
2876--  Just a comment
2877@end example
2878
2879the command
2880
2881@example
2882$ gnatchop toto.txt
2883@end example
2884
2885will not produce any new file and will result in the following warnings:
2886
2887@example
2888toto.txt:1:01: warning: empty file, contains no compilation units
2889no compilation units found
2890no source files written
2891@end example
2892
2893@node Switches for gnatchop,Examples of gnatchop Usage,Command Line for gnatchop,Renaming Files with gnatchop
2894@anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatchop}@anchor{75}@anchor{gnat_ugn/the_gnat_compilation_model id26}@anchor{76}
2895@subsubsection Switches for @cite{gnatchop}
2896
2897
2898@emph{gnatchop} recognizes the following switches:
2899
2900@geindex --version (gnatchop)
2901
2902
2903@table @asis
2904
2905@item @code{--version}
2906
2907Display Copyright and version, then exit disregarding all other options.
2908@end table
2909
2910@geindex --help (gnatchop)
2911
2912
2913@table @asis
2914
2915@item @code{--help}
2916
2917If @emph{--version} was not used, display usage, then exit disregarding
2918all other options.
2919@end table
2920
2921@geindex -c (gnatchop)
2922
2923
2924@table @asis
2925
2926@item @code{-c}
2927
2928Causes @cite{gnatchop} to operate in compilation mode, in which
2929configuration pragmas are handled according to strict RM rules. See
2930previous section for a full description of this mode.
2931
2932@item @code{-gnat@emph{xxx}}
2933
2934This passes the given @emph{-gnat`xxx*` switch to `gnat` which is
2935used to parse the given file. Not all `xxx` options make sense,
2936but for example, the use of *-gnati2} allows @cite{gnatchop} to
2937process a source file that uses Latin-2 coding for identifiers.
2938
2939@item @code{-h}
2940
2941Causes @cite{gnatchop} to generate a brief help summary to the standard
2942output file showing usage information.
2943@end table
2944
2945@geindex -k (gnatchop)
2946
2947
2948@table @asis
2949
2950@item @code{-k@emph{mm}}
2951
2952Limit generated file names to the specified number @cite{mm}
2953of characters.
2954This is useful if the
2955resulting set of files is required to be interoperable with systems
2956which limit the length of file names.
2957No space is allowed between the @emph{-k} and the numeric value. The numeric
2958value may be omitted in which case a default of @emph{-k8},
2959suitable for use
2960with DOS-like file systems, is used. If no @emph{-k} switch
2961is present then
2962there is no limit on the length of file names.
2963@end table
2964
2965@geindex -p (gnatchop)
2966
2967
2968@table @asis
2969
2970@item @code{-p}
2971
2972Causes the file modification time stamp of the input file to be
2973preserved and used for the time stamp of the output file(s). This may be
2974useful for preserving coherency of time stamps in an environment where
2975@cite{gnatchop} is used as part of a standard build process.
2976@end table
2977
2978@geindex -q (gnatchop)
2979
2980
2981@table @asis
2982
2983@item @code{-q}
2984
2985Causes output of informational messages indicating the set of generated
2986files to be suppressed. Warnings and error messages are unaffected.
2987@end table
2988
2989@geindex -r (gnatchop)
2990
2991@geindex Source_Reference pragmas
2992
2993
2994@table @asis
2995
2996@item @code{-r}
2997
2998Generate @cite{Source_Reference} pragmas. Use this switch if the output
2999files are regarded as temporary and development is to be done in terms
3000of the original unchopped file. This switch causes
3001@cite{Source_Reference} pragmas to be inserted into each of the
3002generated files to refers back to the original file name and line number.
3003The result is that all error messages refer back to the original
3004unchopped file.
3005In addition, the debugging information placed into the object file (when
3006the @emph{-g} switch of @emph{gcc} or @emph{gnatmake} is
3007specified)
3008also refers back to this original file so that tools like profilers and
3009debuggers will give information in terms of the original unchopped file.
3010
3011If the original file to be chopped itself contains
3012a @cite{Source_Reference}
3013pragma referencing a third file, then gnatchop respects
3014this pragma, and the generated @cite{Source_Reference} pragmas
3015in the chopped file refer to the original file, with appropriate
3016line numbers. This is particularly useful when @cite{gnatchop}
3017is used in conjunction with @cite{gnatprep} to compile files that
3018contain preprocessing statements and multiple units.
3019@end table
3020
3021@geindex -v (gnatchop)
3022
3023
3024@table @asis
3025
3026@item @code{-v}
3027
3028Causes @cite{gnatchop} to operate in verbose mode. The version
3029number and copyright notice are output, as well as exact copies of
3030the gnat1 commands spawned to obtain the chop control information.
3031@end table
3032
3033@geindex -w (gnatchop)
3034
3035
3036@table @asis
3037
3038@item @code{-w}
3039
3040Overwrite existing file names. Normally @cite{gnatchop} regards it as a
3041fatal error if there is already a file with the same name as a
3042file it would otherwise output, in other words if the files to be
3043chopped contain duplicated units. This switch bypasses this
3044check, and causes all but the last instance of such duplicated
3045units to be skipped.
3046@end table
3047
3048@geindex --GCC= (gnatchop)
3049
3050
3051@table @asis
3052
3053@item @code{--GCC=@emph{xxxx}}
3054
3055Specify the path of the GNAT parser to be used. When this switch is used,
3056no attempt is made to add the prefix to the GNAT parser executable.
3057@end table
3058
3059@node Examples of gnatchop Usage,,Switches for gnatchop,Renaming Files with gnatchop
3060@anchor{gnat_ugn/the_gnat_compilation_model id27}@anchor{77}@anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatchop-usage}@anchor{78}
3061@subsubsection Examples of @cite{gnatchop} Usage
3062
3063
3064@example
3065$ gnatchop -w hello_s.ada prerelease/files
3066@end example
3067
3068Chops the source file @code{hello_s.ada}. The output files will be
3069placed in the directory @code{prerelease/files},
3070overwriting any
3071files with matching names in that directory (no files in the current
3072directory are modified).
3073
3074@example
3075$ gnatchop archive
3076@end example
3077
3078Chops the source file @code{archive}
3079into the current directory. One
3080useful application of @cite{gnatchop} is in sending sets of sources
3081around, for example in email messages. The required sources are simply
3082concatenated (for example, using a Unix @cite{cat}
3083command), and then
3084@emph{gnatchop} is used at the other end to reconstitute the original
3085file names.
3086
3087@example
3088$ gnatchop file1 file2 file3 direc
3089@end example
3090
3091Chops all units in files @code{file1}, @code{file2}, @code{file3}, placing
3092the resulting files in the directory @code{direc}. Note that if any units
3093occur more than once anywhere within this set of files, an error message
3094is generated, and no files are written. To override this check, use the
3095@emph{-w} switch,
3096in which case the last occurrence in the last file will
3097be the one that is output, and earlier duplicate occurrences for a given
3098unit will be skipped.
3099
3100@node Configuration Pragmas,Generating Object Files,File Naming Topics and Utilities,The GNAT Compilation Model
3101@anchor{gnat_ugn/the_gnat_compilation_model id28}@anchor{79}@anchor{gnat_ugn/the_gnat_compilation_model configuration-pragmas}@anchor{16}
3102@section Configuration Pragmas
3103
3104
3105@geindex Configuration pragmas
3106
3107@geindex Pragmas
3108@geindex configuration
3109
3110Configuration pragmas include those pragmas described as
3111such in the Ada Reference Manual, as well as
3112implementation-dependent pragmas that are configuration pragmas.
3113See the @cite{Implementation_Defined_Pragmas} chapter in the
3114@cite{GNAT_Reference_Manual} for details on these
3115additional GNAT-specific configuration pragmas.
3116Most notably, the pragma @cite{Source_File_Name}, which allows
3117specifying non-default names for source files, is a configuration
3118pragma. The following is a complete list of configuration pragmas
3119recognized by GNAT:
3120
3121@example
3122Ada_83
3123Ada_95
3124Ada_05
3125Ada_2005
3126Ada_12
3127Ada_2012
3128Allow_Integer_Address
3129Annotate
3130Assertion_Policy
3131Assume_No_Invalid_Values
3132C_Pass_By_Copy
3133Check_Name
3134Check_Policy
3135Compile_Time_Error
3136Compile_Time_Warning
3137Compiler_Unit
3138Component_Alignment
3139Convention_Identifier
3140Debug_Policy
3141Detect_Blocking
3142Default_Storage_Pool
3143Discard_Names
3144Elaboration_Checks
3145Eliminate
3146Extend_System
3147Extensions_Allowed
3148External_Name_Casing
3149Fast_Math
3150Favor_Top_Level
3151Float_Representation
3152Implicit_Packing
3153Initialize_Scalars
3154Interrupt_State
3155License
3156Locking_Policy
3157Long_Float
3158No_Run_Time
3159No_Strict_Aliasing
3160Normalize_Scalars
3161Optimize_Alignment
3162Persistent_BSS
3163Polling
3164Priority_Specific_Dispatching
3165Profile
3166Profile_Warnings
3167Propagate_Exceptions
3168Queuing_Policy
3169Ravenscar
3170Restricted_Run_Time
3171Restrictions
3172Restrictions_Warnings
3173Reviewable
3174Short_Circuit_And_Or
3175Source_File_Name
3176Source_File_Name_Project
3177SPARK_Mode
3178Style_Checks
3179Suppress
3180Suppress_Exception_Locations
3181Task_Dispatching_Policy
3182Universal_Data
3183Unsuppress
3184Use_VADS_Size
3185Validity_Checks
3186Warnings
3187Wide_Character_Encoding
3188@end example
3189
3190@menu
3191* Handling of Configuration Pragmas:: 
3192* The Configuration Pragmas Files:: 
3193
3194@end menu
3195
3196@node Handling of Configuration Pragmas,The Configuration Pragmas Files,,Configuration Pragmas
3197@anchor{gnat_ugn/the_gnat_compilation_model id29}@anchor{7a}@anchor{gnat_ugn/the_gnat_compilation_model handling-of-configuration-pragmas}@anchor{58}
3198@subsection Handling of Configuration Pragmas
3199
3200
3201Configuration pragmas may either appear at the start of a compilation
3202unit, or they can appear in a configuration pragma file to apply to
3203all compilations performed in a given compilation environment.
3204
3205GNAT also provides the @cite{gnatchop} utility to provide an automatic
3206way to handle configuration pragmas following the semantics for
3207compilations (that is, files with multiple units), described in the RM.
3208See @ref{71,,Operating gnatchop in Compilation Mode} for details.
3209However, for most purposes, it will be more convenient to edit the
3210@code{gnat.adc} file that contains configuration pragmas directly,
3211as described in the following section.
3212
3213In the case of @cite{Restrictions} pragmas appearing as configuration
3214pragmas in individual compilation units, the exact handling depends on
3215the type of restriction.
3216
3217Restrictions that require partition-wide consistency (like
3218@cite{No_Tasking}) are
3219recognized wherever they appear
3220and can be freely inherited, e.g. from a @emph{with}ed unit to the @emph{with}ing
3221unit. This makes sense since the binder will in any case insist on seeing
3222consistent use, so any unit not conforming to any restrictions that are
3223anywhere in the partition will be rejected, and you might as well find
3224that out at compile time rather than at bind time.
3225
3226For restrictions that do not require partition-wide consistency, e.g.
3227SPARK or No_Implementation_Attributes, in general the restriction applies
3228only to the unit in which the pragma appears, and not to any other units.
3229
3230The exception is No_Elaboration_Code which always applies to the entire
3231object file from a compilation, i.e. to the body, spec, and all subunits.
3232This restriction can be specified in a configuration pragma file, or it
3233can be on the body and/or the spec (in eithe case it applies to all the
3234relevant units). It can appear on a subunit only if it has previously
3235appeared in the body of spec.
3236
3237@node The Configuration Pragmas Files,,Handling of Configuration Pragmas,Configuration Pragmas
3238@anchor{gnat_ugn/the_gnat_compilation_model the-configuration-pragmas-files}@anchor{7b}@anchor{gnat_ugn/the_gnat_compilation_model id30}@anchor{7c}
3239@subsection The Configuration Pragmas Files
3240
3241
3242@geindex gnat.adc
3243
3244In GNAT a compilation environment is defined by the current
3245directory at the time that a compile command is given. This current
3246directory is searched for a file whose name is @code{gnat.adc}. If
3247this file is present, it is expected to contain one or more
3248configuration pragmas that will be applied to the current compilation.
3249However, if the switch @emph{-gnatA} is used, @code{gnat.adc} is not
3250considered. When taken into account, @code{gnat.adc} is added to the
3251dependencies, so that if @code{gnat.adc} is modified later, an invocation of
3252@emph{gnatmake} will recompile the source.
3253
3254Configuration pragmas may be entered into the @code{gnat.adc} file
3255either by running @cite{gnatchop} on a source file that consists only of
3256configuration pragmas, or more conveniently by direct editing of the
3257@code{gnat.adc} file, which is a standard format source file.
3258
3259Besides @code{gnat.adc}, additional files containing configuration
3260pragmas may be applied to the current compilation using the switch
3261@code{-gnatec=@emph{path}} where @cite{path} must designate an existing file that
3262contains only configuration pragmas. These configuration pragmas are
3263in addition to those found in @code{gnat.adc} (provided @code{gnat.adc}
3264is present and switch @emph{-gnatA} is not used).
3265
3266It is allowable to specify several switches @emph{-gnatec=}, all of which
3267will be taken into account.
3268
3269Files containing configuration pragmas specified with switches
3270@emph{-gnatec=} are added to the dependencies, unless they are
3271temporary files. A file is considered temporary if its name ends in
3272@code{.tmp} or @code{.TMP}. Certain tools follow this naming
3273convention because they pass information to @emph{gcc} via
3274temporary files that are immediately deleted; it doesn't make sense to
3275depend on a file that no longer exists. Such tools include
3276@emph{gprbuild}, @emph{gnatmake}, and @emph{gnatcheck}.
3277
3278If you are using project file, a separate mechanism is provided using
3279project attributes, see @ref{7d,,Specifying Configuration Pragmas} for more
3280details.
3281
3282@node Generating Object Files,Source Dependencies,Configuration Pragmas,The GNAT Compilation Model
3283@anchor{gnat_ugn/the_gnat_compilation_model generating-object-files}@anchor{42}@anchor{gnat_ugn/the_gnat_compilation_model id31}@anchor{7e}
3284@section Generating Object Files
3285
3286
3287An Ada program consists of a set of source files, and the first step in
3288compiling the program is to generate the corresponding object files.
3289These are generated by compiling a subset of these source files.
3290The files you need to compile are the following:
3291
3292
3293@itemize *
3294
3295@item 
3296If a package spec has no body, compile the package spec to produce the
3297object file for the package.
3298
3299@item 
3300If a package has both a spec and a body, compile the body to produce the
3301object file for the package. The source file for the package spec need
3302not be compiled in this case because there is only one object file, which
3303contains the code for both the spec and body of the package.
3304
3305@item 
3306For a subprogram, compile the subprogram body to produce the object file
3307for the subprogram. The spec, if one is present, is as usual in a
3308separate file, and need not be compiled.
3309@end itemize
3310
3311@geindex Subunits
3312
3313
3314@itemize *
3315
3316@item 
3317In the case of subunits, only compile the parent unit. A single object
3318file is generated for the entire subunit tree, which includes all the
3319subunits.
3320
3321@item 
3322Compile child units independently of their parent units
3323(though, of course, the spec of all the ancestor unit must be present in order
3324to compile a child unit).
3325
3326@geindex Generics
3327
3328@item 
3329Compile generic units in the same manner as any other units. The object
3330files in this case are small dummy files that contain at most the
3331flag used for elaboration checking. This is because GNAT always handles generic
3332instantiation by means of macro expansion. However, it is still necessary to
3333compile generic units, for dependency checking and elaboration purposes.
3334@end itemize
3335
3336The preceding rules describe the set of files that must be compiled to
3337generate the object files for a program. Each object file has the same
3338name as the corresponding source file, except that the extension is
3339@code{.o} as usual.
3340
3341You may wish to compile other files for the purpose of checking their
3342syntactic and semantic correctness. For example, in the case where a
3343package has a separate spec and body, you would not normally compile the
3344spec. However, it is convenient in practice to compile the spec to make
3345sure it is error-free before compiling clients of this spec, because such
3346compilations will fail if there is an error in the spec.
3347
3348GNAT provides an option for compiling such files purely for the
3349purposes of checking correctness; such compilations are not required as
3350part of the process of building a program. To compile a file in this
3351checking mode, use the @emph{-gnatc} switch.
3352
3353@node Source Dependencies,The Ada Library Information Files,Generating Object Files,The GNAT Compilation Model
3354@anchor{gnat_ugn/the_gnat_compilation_model id32}@anchor{7f}@anchor{gnat_ugn/the_gnat_compilation_model source-dependencies}@anchor{43}
3355@section Source Dependencies
3356
3357
3358A given object file clearly depends on the source file which is compiled
3359to produce it. Here we are using "depends" in the sense of a typical
3360@cite{make} utility; in other words, an object file depends on a source
3361file if changes to the source file require the object file to be
3362recompiled.
3363In addition to this basic dependency, a given object may depend on
3364additional source files as follows:
3365
3366
3367@itemize *
3368
3369@item 
3370If a file being compiled @emph{with}s a unit @cite{X}, the object file
3371depends on the file containing the spec of unit @cite{X}. This includes
3372files that are @emph{with}ed implicitly either because they are parents
3373of @emph{with}ed child units or they are run-time units required by the
3374language constructs used in a particular unit.
3375
3376@item 
3377If a file being compiled instantiates a library level generic unit, the
3378object file depends on both the spec and body files for this generic
3379unit.
3380
3381@item 
3382If a file being compiled instantiates a generic unit defined within a
3383package, the object file depends on the body file for the package as
3384well as the spec file.
3385@end itemize
3386
3387@geindex Inline
3388
3389@geindex -gnatn switch
3390
3391
3392@itemize *
3393
3394@item 
3395If a file being compiled contains a call to a subprogram for which
3396pragma @cite{Inline} applies and inlining is activated with the
3397@emph{-gnatn} switch, the object file depends on the file containing the
3398body of this subprogram as well as on the file containing the spec. Note
3399that for inlining to actually occur as a result of the use of this switch,
3400it is necessary to compile in optimizing mode.
3401
3402@geindex -gnatN switch
3403
3404The use of @emph{-gnatN} activates  inlining optimization
3405that is performed by the front end of the compiler. This inlining does
3406not require that the code generation be optimized. Like @emph{-gnatn},
3407the use of this switch generates additional dependencies.
3408
3409When using a gcc-based back end (in practice this means using any version
3410of GNAT other than for the JVM, .NET or GNAAMP platforms), then the use of
3411@emph{-gnatN} is deprecated, and the use of @emph{-gnatn} is preferred.
3412Historically front end inlining was more extensive than the gcc back end
3413inlining, but that is no longer the case.
3414
3415@item 
3416If an object file @code{O} depends on the proper body of a subunit through
3417inlining or instantiation, it depends on the parent unit of the subunit.
3418This means that any modification of the parent unit or one of its subunits
3419affects the compilation of @code{O}.
3420
3421@item 
3422The object file for a parent unit depends on all its subunit body files.
3423
3424@item 
3425The previous two rules meant that for purposes of computing dependencies and
3426recompilation, a body and all its subunits are treated as an indivisible whole.
3427
3428These rules are applied transitively: if unit @cite{A} @emph{with}s
3429unit @cite{B}, whose elaboration calls an inlined procedure in package
3430@cite{C}, the object file for unit @cite{A} will depend on the body of
3431@cite{C}, in file @code{c.adb}.
3432
3433The set of dependent files described by these rules includes all the
3434files on which the unit is semantically dependent, as dictated by the
3435Ada language standard. However, it is a superset of what the
3436standard describes, because it includes generic, inline, and subunit
3437dependencies.
3438
3439An object file must be recreated by recompiling the corresponding source
3440file if any of the source files on which it depends are modified. For
3441example, if the @cite{make} utility is used to control compilation,
3442the rule for an Ada object file must mention all the source files on
3443which the object file depends, according to the above definition.
3444The determination of the necessary
3445recompilations is done automatically when one uses @emph{gnatmake}.
3446@end itemize
3447
3448@node The Ada Library Information Files,Binding an Ada Program,Source Dependencies,The GNAT Compilation Model
3449@anchor{gnat_ugn/the_gnat_compilation_model id33}@anchor{80}@anchor{gnat_ugn/the_gnat_compilation_model the-ada-library-information-files}@anchor{44}
3450@section The Ada Library Information Files
3451
3452
3453@geindex Ada Library Information files
3454
3455@geindex ALI files
3456
3457Each compilation actually generates two output files. The first of these
3458is the normal object file that has a @code{.o} extension. The second is a
3459text file containing full dependency information. It has the same
3460name as the source file, but an @code{.ali} extension.
3461This file is known as the Ada Library Information (@code{ALI}) file.
3462The following information is contained in the @code{ALI} file.
3463
3464
3465@itemize *
3466
3467@item 
3468Version information (indicates which version of GNAT was used to compile
3469the unit(s) in question)
3470
3471@item 
3472Main program information (including priority and time slice settings,
3473as well as the wide character encoding used during compilation).
3474
3475@item 
3476List of arguments used in the @emph{gcc} command for the compilation
3477
3478@item 
3479Attributes of the unit, including configuration pragmas used, an indication
3480of whether the compilation was successful, exception model used etc.
3481
3482@item 
3483A list of relevant restrictions applying to the unit (used for consistency)
3484checking.
3485
3486@item 
3487Categorization information (e.g., use of pragma @cite{Pure}).
3488
3489@item 
3490Information on all @emph{with}ed units, including presence of
3491Elaborate` or @cite{Elaborate_All} pragmas.
3492
3493@item 
3494Information from any @cite{Linker_Options} pragmas used in the unit
3495
3496@item 
3497Information on the use of @cite{Body_Version} or @cite{Version}
3498attributes in the unit.
3499
3500@item 
3501Dependency information. This is a list of files, together with
3502time stamp and checksum information. These are files on which
3503the unit depends in the sense that recompilation is required
3504if any of these units are modified.
3505
3506@item 
3507Cross-reference data. Contains information on all entities referenced
3508in the unit. Used by tools like @cite{gnatxref} and @cite{gnatfind} to
3509provide cross-reference information.
3510@end itemize
3511
3512For a full detailed description of the format of the @code{ALI} file,
3513see the source of the body of unit @cite{Lib.Writ}, contained in file
3514@code{lib-writ.adb} in the GNAT compiler sources.
3515
3516@node Binding an Ada Program,GNAT and Libraries,The Ada Library Information Files,The GNAT Compilation Model
3517@anchor{gnat_ugn/the_gnat_compilation_model id34}@anchor{81}@anchor{gnat_ugn/the_gnat_compilation_model binding-an-ada-program}@anchor{45}
3518@section Binding an Ada Program
3519
3520
3521When using languages such as C and C++, once the source files have been
3522compiled the only remaining step in building an executable program
3523is linking the object modules together. This means that it is possible to
3524link an inconsistent version of a program, in which two units have
3525included different versions of the same header.
3526
3527The rules of Ada do not permit such an inconsistent program to be built.
3528For example, if two clients have different versions of the same package,
3529it is illegal to build a program containing these two clients.
3530These rules are enforced by the GNAT binder, which also determines an
3531elaboration order consistent with the Ada rules.
3532
3533The GNAT binder is run after all the object files for a program have
3534been created. It is given the name of the main program unit, and from
3535this it determines the set of units required by the program, by reading the
3536corresponding ALI files. It generates error messages if the program is
3537inconsistent or if no valid order of elaboration exists.
3538
3539If no errors are detected, the binder produces a main program, in Ada by
3540default, that contains calls to the elaboration procedures of those
3541compilation unit that require them, followed by
3542a call to the main program. This Ada program is compiled to generate the
3543object file for the main program. The name of
3544the Ada file is @code{b~xxx}.adb` (with the corresponding spec
3545@code{b~xxx}.ads`) where @cite{xxx} is the name of the
3546main program unit.
3547
3548Finally, the linker is used to build the resulting executable program,
3549using the object from the main program from the bind step as well as the
3550object files for the Ada units of the program.
3551
3552@node GNAT and Libraries,Conditional Compilation,Binding an Ada Program,The GNAT Compilation Model
3553@anchor{gnat_ugn/the_gnat_compilation_model gnat-and-libraries}@anchor{17}@anchor{gnat_ugn/the_gnat_compilation_model id35}@anchor{82}
3554@section GNAT and Libraries
3555
3556
3557@geindex Library building and using
3558
3559This chapter describes how to build and use libraries with GNAT, and also shows
3560how to recompile the GNAT run-time library. You should be familiar with the
3561Project Manager facility (@ref{b,,GNAT Project Manager}) before reading this
3562chapter.
3563
3564@menu
3565* Introduction to Libraries in GNAT:: 
3566* General Ada Libraries:: 
3567* Stand-alone Ada Libraries:: 
3568* Rebuilding the GNAT Run-Time Library:: 
3569
3570@end menu
3571
3572@node Introduction to Libraries in GNAT,General Ada Libraries,,GNAT and Libraries
3573@anchor{gnat_ugn/the_gnat_compilation_model introduction-to-libraries-in-gnat}@anchor{83}@anchor{gnat_ugn/the_gnat_compilation_model id36}@anchor{84}
3574@subsection Introduction to Libraries in GNAT
3575
3576
3577A library is, conceptually, a collection of objects which does not have its
3578own main thread of execution, but rather provides certain services to the
3579applications that use it. A library can be either statically linked with the
3580application, in which case its code is directly included in the application,
3581or, on platforms that support it, be dynamically linked, in which case
3582its code is shared by all applications making use of this library.
3583
3584GNAT supports both types of libraries.
3585In the static case, the compiled code can be provided in different ways. The
3586simplest approach is to provide directly the set of objects resulting from
3587compilation of the library source files. Alternatively, you can group the
3588objects into an archive using whatever commands are provided by the operating
3589system. For the latter case, the objects are grouped into a shared library.
3590
3591In the GNAT environment, a library has three types of components:
3592
3593
3594@itemize *
3595
3596@item 
3597Source files,
3598
3599@item 
3600@code{ALI} files (see @ref{44,,The Ada Library Information Files}), and
3601
3602@item 
3603Object files, an archive or a shared library.
3604@end itemize
3605
3606A GNAT library may expose all its source files, which is useful for
3607documentation purposes. Alternatively, it may expose only the units needed by
3608an external user to make use of the library. That is to say, the specs
3609reflecting the library services along with all the units needed to compile
3610those specs, which can include generic bodies or any body implementing an
3611inlined routine. In the case of @emph{stand-alone libraries} those exposed
3612units are called @emph{interface units} (@ref{85,,Stand-alone Ada Libraries}).
3613
3614All compilation units comprising an application, including those in a library,
3615need to be elaborated in an order partially defined by Ada's semantics. GNAT
3616computes the elaboration order from the @code{ALI} files and this is why they
3617constitute a mandatory part of GNAT libraries.
3618@emph{Stand-alone libraries} are the exception to this rule because a specific
3619library elaboration routine is produced independently of the application(s)
3620using the library.
3621
3622@node General Ada Libraries,Stand-alone Ada Libraries,Introduction to Libraries in GNAT,GNAT and Libraries
3623@anchor{gnat_ugn/the_gnat_compilation_model general-ada-libraries}@anchor{86}@anchor{gnat_ugn/the_gnat_compilation_model id37}@anchor{87}
3624@subsection General Ada Libraries
3625
3626
3627@menu
3628* Building a library:: 
3629* Installing a library:: 
3630* Using a library:: 
3631
3632@end menu
3633
3634@node Building a library,Installing a library,,General Ada Libraries
3635@anchor{gnat_ugn/the_gnat_compilation_model building-a-library}@anchor{88}@anchor{gnat_ugn/the_gnat_compilation_model id38}@anchor{89}
3636@subsubsection Building a library
3637
3638
3639The easiest way to build a library is to use the Project Manager,
3640which supports a special type of project called a @emph{Library Project}
3641(see @ref{8a,,Library Projects}).
3642
3643A project is considered a library project, when two project-level attributes
3644are defined in it: @cite{Library_Name} and @cite{Library_Dir}. In order to
3645control different aspects of library configuration, additional optional
3646project-level attributes can be specified:
3647
3648
3649@itemize *
3650
3651@item 
3652
3653@table @asis
3654
3655@item @emph{Library_Kind}
3656
3657This attribute controls whether the library is to be static or dynamic
3658@end table
3659
3660@item 
3661
3662@table @asis
3663
3664@item @emph{Library_Version}
3665
3666This attribute specifies the library version; this value is used
3667during dynamic linking of shared libraries to determine if the currently
3668installed versions of the binaries are compatible.
3669@end table
3670
3671@item 
3672@emph{Library_Options}
3673
3674@item 
3675
3676@table @asis
3677
3678@item @emph{Library_GCC}
3679
3680These attributes specify additional low-level options to be used during
3681library generation, and redefine the actual application used to generate
3682library.
3683@end table
3684@end itemize
3685
3686The GNAT Project Manager takes full care of the library maintenance task,
3687including recompilation of the source files for which objects do not exist
3688or are not up to date, assembly of the library archive, and installation of
3689the library (i.e., copying associated source, object and @code{ALI} files
3690to the specified location).
3691
3692Here is a simple library project file:
3693
3694@example
3695project My_Lib is
3696  for Source_Dirs use ("src1", "src2");
3697  for Object_Dir use "obj";
3698  for Library_Name use "mylib";
3699  for Library_Dir use "lib";
3700  for Library_Kind use "dynamic";
3701end My_lib;
3702@end example
3703
3704and the compilation command to build and install the library:
3705
3706@example
3707$ gnatmake -Pmy_lib
3708@end example
3709
3710It is not entirely trivial to perform manually all the steps required to
3711produce a library. We recommend that you use the GNAT Project Manager
3712for this task. In special cases where this is not desired, the necessary
3713steps are discussed below.
3714
3715There are various possibilities for compiling the units that make up the
3716library: for example with a Makefile (@ref{21,,Using the GNU make Utility}) or
3717with a conventional script. For simple libraries, it is also possible to create
3718a dummy main program which depends upon all the packages that comprise the
3719interface of the library. This dummy main program can then be given to
3720@emph{gnatmake}, which will ensure that all necessary objects are built.
3721
3722After this task is accomplished, you should follow the standard procedure
3723of the underlying operating system to produce the static or shared library.
3724
3725Here is an example of such a dummy program:
3726
3727@example
3728with My_Lib.Service1;
3729with My_Lib.Service2;
3730with My_Lib.Service3;
3731procedure My_Lib_Dummy is
3732begin
3733   null;
3734end;
3735@end example
3736
3737Here are the generic commands that will build an archive or a shared library.
3738
3739@example
3740# compiling the library
3741$ gnatmake -c my_lib_dummy.adb
3742
3743# we don't need the dummy object itself
3744$ rm my_lib_dummy.o my_lib_dummy.ali
3745
3746# create an archive with the remaining objects
3747$ ar rc libmy_lib.a *.o
3748# some systems may require "ranlib" to be run as well
3749
3750# or create a shared library
3751$ gcc -shared -o libmy_lib.so *.o
3752# some systems may require the code to have been compiled with -fPIC
3753
3754# remove the object files that are now in the library
3755$ rm *.o
3756
3757# Make the ALI files read-only so that gnatmake will not try to
3758# regenerate the objects that are in the library
3759$ chmod -w *.ali
3760@end example
3761
3762Please note that the library must have a name of the form @code{lib@emph{xxx}.a}
3763or @code{lib@emph{xxx}.so} (or @code{lib@emph{xxx}.dll} on Windows) in order to
3764be accessed by the directive @code{-l@emph{xxx}} at link time.
3765
3766@node Installing a library,Using a library,Building a library,General Ada Libraries
3767@anchor{gnat_ugn/the_gnat_compilation_model installing-a-library}@anchor{8b}@anchor{gnat_ugn/the_gnat_compilation_model id39}@anchor{8c}
3768@subsubsection Installing a library
3769
3770
3771@geindex ADA_PROJECT_PATH
3772
3773@geindex GPR_PROJECT_PATH
3774
3775If you use project files, library installation is part of the library build
3776process (@ref{8d,,Installing a library with project files}).
3777
3778When project files are not an option, it is also possible, but not recommended,
3779to install the library so that the sources needed to use the library are on the
3780Ada source path and the ALI files & libraries be on the Ada Object path (see
3781@ref{8e,,Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
3782administrator can place general-purpose libraries in the default compiler
3783paths, by specifying the libraries' location in the configuration files
3784@code{ada_source_path} and @code{ada_object_path}. These configuration files
3785must be located in the GNAT installation tree at the same place as the gcc spec
3786file. The location of the gcc spec file can be determined as follows:
3787
3788@example
3789$ gcc -v
3790@end example
3791
3792The configuration files mentioned above have a simple format: each line
3793must contain one unique directory name.
3794Those names are added to the corresponding path
3795in their order of appearance in the file. The names can be either absolute
3796or relative; in the latter case, they are relative to where theses files
3797are located.
3798
3799The files @code{ada_source_path} and @code{ada_object_path} might not be
3800present in a
3801GNAT installation, in which case, GNAT will look for its run-time library in
3802the directories @code{adainclude} (for the sources) and @code{adalib} (for the
3803objects and @code{ALI} files). When the files exist, the compiler does not
3804look in @code{adainclude} and @code{adalib}, and thus the
3805@code{ada_source_path} file
3806must contain the location for the GNAT run-time sources (which can simply
3807be @code{adainclude}). In the same way, the @code{ada_object_path} file must
3808contain the location for the GNAT run-time objects (which can simply
3809be @code{adalib}).
3810
3811You can also specify a new default path to the run-time library at compilation
3812time with the switch @emph{--RTS=rts-path}. You can thus choose / change
3813the run-time library you want your program to be compiled with. This switch is
3814recognized by @emph{gcc}, @emph{gnatmake}, @emph{gnatbind},
3815@emph{gnatls}, @emph{gnatfind} and @emph{gnatxref}.
3816
3817It is possible to install a library before or after the standard GNAT
3818library, by reordering the lines in the configuration files. In general, a
3819library must be installed before the GNAT library if it redefines
3820any part of it.
3821
3822@node Using a library,,Installing a library,General Ada Libraries
3823@anchor{gnat_ugn/the_gnat_compilation_model using-a-library}@anchor{8f}@anchor{gnat_ugn/the_gnat_compilation_model id40}@anchor{90}
3824@subsubsection Using a library
3825
3826
3827Once again, the project facility greatly simplifies the use of
3828libraries. In this context, using a library is just a matter of adding a
3829@emph{with} clause in the user project. For instance, to make use of the
3830library @cite{My_Lib} shown in examples in earlier sections, you can
3831write:
3832
3833@example
3834with "my_lib";
3835project My_Proj is
3836  ...
3837end My_Proj;
3838@end example
3839
3840Even if you have a third-party, non-Ada library, you can still use GNAT's
3841Project Manager facility to provide a wrapper for it. For example, the
3842following project, when @emph{with}ed by your main project, will link with the
3843third-party library @code{liba.a}:
3844
3845@example
3846project Liba is
3847   for Externally_Built use "true";
3848   for Source_Files use ();
3849   for Library_Dir use "lib";
3850   for Library_Name use "a";
3851   for Library_Kind use "static";
3852end Liba;
3853@end example
3854
3855This is an alternative to the use of @cite{pragma Linker_Options}. It is
3856especially interesting in the context of systems with several interdependent
3857static libraries where finding a proper linker order is not easy and best be
3858left to the tools having visibility over project dependence information.
3859
3860In order to use an Ada library manually, you need to make sure that this
3861library is on both your source and object path
3862(see @ref{8e,,Search Paths and the Run-Time Library (RTL)}
3863and @ref{91,,Search Paths for gnatbind}). Furthermore, when the objects are grouped
3864in an archive or a shared library, you need to specify the desired
3865library at link time.
3866
3867For example, you can use the library @code{mylib} installed in
3868@code{/dir/my_lib_src} and @code{/dir/my_lib_obj} with the following commands:
3869
3870@example
3871$ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \\
3872  -largs -lmy_lib
3873@end example
3874
3875This can be expressed more simply:
3876
3877@example
3878$ gnatmake my_appl
3879@end example
3880
3881when the following conditions are met:
3882
3883
3884@itemize *
3885
3886@item 
3887@code{/dir/my_lib_src} has been added by the user to the environment
3888variable 
3889@geindex ADA_INCLUDE_PATH
3890@geindex environment variable; ADA_INCLUDE_PATH
3891@code{ADA_INCLUDE_PATH}, or by the administrator to the file
3892@code{ada_source_path}
3893
3894@item 
3895@code{/dir/my_lib_obj} has been added by the user to the environment
3896variable 
3897@geindex ADA_OBJECTS_PATH
3898@geindex environment variable; ADA_OBJECTS_PATH
3899@code{ADA_OBJECTS_PATH}, or by the administrator to the file
3900@code{ada_object_path}
3901
3902@item 
3903a pragma @cite{Linker_Options} has been added to one of the sources.
3904For example:
3905
3906@example
3907pragma Linker_Options ("-lmy_lib");
3908@end example
3909@end itemize
3910
3911Note that you may also load a library dynamically at
3912run time given its filename, as illustrated in the GNAT @code{plugins} example
3913in the directory @code{share/examples/gnat/plugins} within the GNAT
3914install area.
3915
3916@node Stand-alone Ada Libraries,Rebuilding the GNAT Run-Time Library,General Ada Libraries,GNAT and Libraries
3917@anchor{gnat_ugn/the_gnat_compilation_model stand-alone-ada-libraries}@anchor{85}@anchor{gnat_ugn/the_gnat_compilation_model id41}@anchor{92}
3918@subsection Stand-alone Ada Libraries
3919
3920
3921@geindex Stand-alone libraries
3922
3923@menu
3924* Introduction to Stand-alone Libraries:: 
3925* Building a Stand-alone Library:: 
3926* Creating a Stand-alone Library to be used in a non-Ada context:: 
3927* Restrictions in Stand-alone Libraries:: 
3928
3929@end menu
3930
3931@node Introduction to Stand-alone Libraries,Building a Stand-alone Library,,Stand-alone Ada Libraries
3932@anchor{gnat_ugn/the_gnat_compilation_model introduction-to-stand-alone-libraries}@anchor{93}@anchor{gnat_ugn/the_gnat_compilation_model id42}@anchor{94}
3933@subsubsection Introduction to Stand-alone Libraries
3934
3935
3936A Stand-alone Library (abbreviated 'SAL') is a library that contains the
3937necessary code to
3938elaborate the Ada units that are included in the library. In contrast with
3939an ordinary library, which consists of all sources, objects and @code{ALI}
3940files of the
3941library, a SAL may specify a restricted subset of compilation units
3942to serve as a library interface. In this case, the fully
3943self-sufficient set of files will normally consist of an objects
3944archive, the sources of interface units' specs, and the @code{ALI}
3945files of interface units.
3946If an interface spec contains a generic unit or an inlined subprogram,
3947the body's
3948source must also be provided; if the units that must be provided in the source
3949form depend on other units, the source and @code{ALI} files of those must
3950also be provided.
3951
3952The main purpose of a SAL is to minimize the recompilation overhead of client
3953applications when a new version of the library is installed. Specifically,
3954if the interface sources have not changed, client applications do not need to
3955be recompiled. If, furthermore, a SAL is provided in the shared form and its
3956version, controlled by @cite{Library_Version} attribute, is not changed,
3957then the clients do not need to be relinked.
3958
3959SALs also allow the library providers to minimize the amount of library source
3960text exposed to the clients.  Such 'information hiding' might be useful or
3961necessary for various reasons.
3962
3963Stand-alone libraries are also well suited to be used in an executable whose
3964main routine is not written in Ada.
3965
3966@node Building a Stand-alone Library,Creating a Stand-alone Library to be used in a non-Ada context,Introduction to Stand-alone Libraries,Stand-alone Ada Libraries
3967@anchor{gnat_ugn/the_gnat_compilation_model id43}@anchor{95}@anchor{gnat_ugn/the_gnat_compilation_model building-a-stand-alone-library}@anchor{96}
3968@subsubsection Building a Stand-alone Library
3969
3970
3971GNAT's Project facility provides a simple way of building and installing
3972stand-alone libraries; see @ref{97,,Stand-alone Library Projects}.
3973To be a Stand-alone Library Project, in addition to the two attributes
3974that make a project a Library Project (@cite{Library_Name} and
3975@cite{Library_Dir}; see @ref{8a,,Library Projects}), the attribute
3976@cite{Library_Interface} must be defined.  For example:
3977
3978@example
3979for Library_Dir use "lib_dir";
3980for Library_Name use "dummy";
3981for Library_Interface use ("int1", "int1.child");
3982@end example
3983
3984Attribute @cite{Library_Interface} has a non-empty string list value,
3985each string in the list designating a unit contained in an immediate source
3986of the project file.
3987
3988When a Stand-alone Library is built, first the binder is invoked to build
3989a package whose name depends on the library name
3990(@code{b~dummy.ads/b} in the example above).
3991This binder-generated package includes initialization and
3992finalization procedures whose
3993names depend on the library name (@cite{dummyinit} and @cite{dummyfinal}
3994in the example
3995above). The object corresponding to this package is included in the library.
3996
3997You must ensure timely (e.g., prior to any use of interfaces in the SAL)
3998calling of these procedures if a static SAL is built, or if a shared SAL
3999is built
4000with the project-level attribute @cite{Library_Auto_Init} set to
4001@cite{"false"}.
4002
4003For a Stand-Alone Library, only the @code{ALI} files of the Interface Units
4004(those that are listed in attribute @cite{Library_Interface}) are copied to
4005the Library Directory. As a consequence, only the Interface Units may be
4006imported from Ada units outside of the library. If other units are imported,
4007the binding phase will fail.
4008
4009It is also possible to build an encapsulated library where not only
4010the code to elaborate and finalize the library is embedded but also
4011ensuring that the library is linked only against static
4012libraries. So an encapsulated library only depends on system
4013libraries, all other code, including the GNAT runtime, is embedded. To
4014build an encapsulated library the attribute
4015@cite{Library_Standalone} must be set to @cite{encapsulated}:
4016
4017@example
4018for Library_Dir use "lib_dir";
4019for Library_Name use "dummy";
4020for Library_Kind use "dynamic";
4021for Library_Interface use ("int1", "int1.child");
4022for Library_Standalone use "encapsulated";
4023@end example
4024
4025The default value for this attribute is @cite{standard} in which case
4026a stand-alone library is built.
4027
4028The attribute @cite{Library_Src_Dir} may be specified for a
4029Stand-Alone Library. @cite{Library_Src_Dir} is a simple attribute that has a
4030single string value. Its value must be the path (absolute or relative to the
4031project directory) of an existing directory. This directory cannot be the
4032object directory or one of the source directories, but it can be the same as
4033the library directory. The sources of the Interface
4034Units of the library that are needed by an Ada client of the library will be
4035copied to the designated directory, called the Interface Copy directory.
4036These sources include the specs of the Interface Units, but they may also
4037include bodies and subunits, when pragmas @cite{Inline} or @cite{Inline_Always}
4038are used, or when there is a generic unit in the spec. Before the sources
4039are copied to the Interface Copy directory, an attempt is made to delete all
4040files in the Interface Copy directory.
4041
4042Building stand-alone libraries by hand is somewhat tedious, but for those
4043occasions when it is necessary here are the steps that you need to perform:
4044
4045
4046@itemize *
4047
4048@item 
4049Compile all library sources.
4050
4051@item 
4052Invoke the binder with the switch @emph{-n} (No Ada main program),
4053with all the @code{ALI} files of the interfaces, and
4054with the switch @emph{-L} to give specific names to the @cite{init}
4055and @cite{final} procedures.  For example:
4056
4057@example
4058$ gnatbind -n int1.ali int2.ali -Lsal1
4059@end example
4060
4061@item 
4062Compile the binder generated file:
4063
4064@example
4065$ gcc -c b~int2.adb
4066@end example
4067
4068@item 
4069Link the dynamic library with all the necessary object files,
4070indicating to the linker the names of the @cite{init} (and possibly
4071@cite{final}) procedures for automatic initialization (and finalization).
4072The built library should be placed in a directory different from
4073the object directory.
4074
4075@item 
4076Copy the @cite{ALI} files of the interface to the library directory,
4077add in this copy an indication that it is an interface to a SAL
4078(i.e., add a word @emph{SL} on the line in the @code{ALI} file that starts
4079with letter 'P') and make the modified copy of the @code{ALI} file
4080read-only.
4081@end itemize
4082
4083Using SALs is not different from using other libraries
4084(see @ref{8f,,Using a library}).
4085
4086@node Creating a Stand-alone Library to be used in a non-Ada context,Restrictions in Stand-alone Libraries,Building a Stand-alone Library,Stand-alone Ada Libraries
4087@anchor{gnat_ugn/the_gnat_compilation_model creating-a-stand-alone-library-to-be-used-in-a-non-ada-context}@anchor{98}@anchor{gnat_ugn/the_gnat_compilation_model id44}@anchor{99}
4088@subsubsection Creating a Stand-alone Library to be used in a non-Ada context
4089
4090
4091It is easy to adapt the SAL build procedure discussed above for use of a SAL in
4092a non-Ada context.
4093
4094The only extra step required is to ensure that library interface subprograms
4095are compatible with the main program, by means of @cite{pragma Export}
4096or @cite{pragma Convention}.
4097
4098Here is an example of simple library interface for use with C main program:
4099
4100@example
4101package My_Package is
4102
4103   procedure Do_Something;
4104   pragma Export (C, Do_Something, "do_something");
4105
4106   procedure Do_Something_Else;
4107   pragma Export (C, Do_Something_Else, "do_something_else");
4108
4109end My_Package;
4110@end example
4111
4112On the foreign language side, you must provide a 'foreign' view of the
4113library interface; remember that it should contain elaboration routines in
4114addition to interface subprograms.
4115
4116The example below shows the content of @cite{mylib_interface.h} (note
4117that there is no rule for the naming of this file, any name can be used)
4118
4119@example
4120/* the library elaboration procedure */
4121extern void mylibinit (void);
4122
4123/* the library finalization procedure */
4124extern void mylibfinal (void);
4125
4126/* the interface exported by the library */
4127extern void do_something (void);
4128extern void do_something_else (void);
4129@end example
4130
4131Libraries built as explained above can be used from any program, provided
4132that the elaboration procedures (named @cite{mylibinit} in the previous
4133example) are called before the library services are used. Any number of
4134libraries can be used simultaneously, as long as the elaboration
4135procedure of each library is called.
4136
4137Below is an example of a C program that uses the @cite{mylib} library.
4138
4139@example
4140#include "mylib_interface.h"
4141
4142int
4143main (void)
4144@{
4145   /* First, elaborate the library before using it */
4146   mylibinit ();
4147
4148   /* Main program, using the library exported entities */
4149   do_something ();
4150   do_something_else ();
4151
4152   /* Library finalization at the end of the program */
4153   mylibfinal ();
4154   return 0;
4155@}
4156@end example
4157
4158Note that invoking any library finalization procedure generated by
4159@cite{gnatbind} shuts down the Ada run-time environment.
4160Consequently, the
4161finalization of all Ada libraries must be performed at the end of the program.
4162No call to these libraries or to the Ada run-time library should be made
4163after the finalization phase.
4164
4165Note also that special care must be taken with multi-tasks
4166applications. The initialization and finalization routines are not
4167protected against concurrent access. If such requirement is needed it
4168must be ensured at the application level using a specific operating
4169system services like a mutex or a critical-section.
4170
4171@node Restrictions in Stand-alone Libraries,,Creating a Stand-alone Library to be used in a non-Ada context,Stand-alone Ada Libraries
4172@anchor{gnat_ugn/the_gnat_compilation_model id45}@anchor{9a}@anchor{gnat_ugn/the_gnat_compilation_model restrictions-in-stand-alone-libraries}@anchor{9b}
4173@subsubsection Restrictions in Stand-alone Libraries
4174
4175
4176The pragmas listed below should be used with caution inside libraries,
4177as they can create incompatibilities with other Ada libraries:
4178
4179
4180@itemize *
4181
4182@item 
4183pragma @cite{Locking_Policy}
4184
4185@item 
4186pragma @cite{Partition_Elaboration_Policy}
4187
4188@item 
4189pragma @cite{Queuing_Policy}
4190
4191@item 
4192pragma @cite{Task_Dispatching_Policy}
4193
4194@item 
4195pragma @cite{Unreserve_All_Interrupts}
4196@end itemize
4197
4198When using a library that contains such pragmas, the user must make sure
4199that all libraries use the same pragmas with the same values. Otherwise,
4200@cite{Program_Error} will
4201be raised during the elaboration of the conflicting
4202libraries. The usage of these pragmas and its consequences for the user
4203should therefore be well documented.
4204
4205Similarly, the traceback in the exception occurrence mechanism should be
4206enabled or disabled in a consistent manner across all libraries.
4207Otherwise, Program_Error will be raised during the elaboration of the
4208conflicting libraries.
4209
4210If the @cite{Version} or @cite{Body_Version}
4211attributes are used inside a library, then you need to
4212perform a @cite{gnatbind} step that specifies all @code{ALI} files in all
4213libraries, so that version identifiers can be properly computed.
4214In practice these attributes are rarely used, so this is unlikely
4215to be a consideration.
4216
4217@node Rebuilding the GNAT Run-Time Library,,Stand-alone Ada Libraries,GNAT and Libraries
4218@anchor{gnat_ugn/the_gnat_compilation_model id46}@anchor{9c}@anchor{gnat_ugn/the_gnat_compilation_model rebuilding-the-gnat-run-time-library}@anchor{9d}
4219@subsection Rebuilding the GNAT Run-Time Library
4220
4221
4222@geindex GNAT Run-Time Library
4223@geindex rebuilding
4224
4225@geindex Building the GNAT Run-Time Library
4226
4227@geindex Rebuilding the GNAT Run-Time Library
4228
4229@geindex Run-Time Library
4230@geindex rebuilding
4231
4232It may be useful to recompile the GNAT library in various contexts, the
4233most important one being the use of partition-wide configuration pragmas
4234such as @cite{Normalize_Scalars}. A special Makefile called
4235@cite{Makefile.adalib} is provided to that effect and can be found in
4236the directory containing the GNAT library. The location of this
4237directory depends on the way the GNAT environment has been installed and can
4238be determined by means of the command:
4239
4240@example
4241$ gnatls -v
4242@end example
4243
4244The last entry in the object search path usually contains the
4245gnat library. This Makefile contains its own documentation and in
4246particular the set of instructions needed to rebuild a new library and
4247to use it.
4248
4249@geindex Conditional compilation
4250
4251@node Conditional Compilation,Mixed Language Programming,GNAT and Libraries,The GNAT Compilation Model
4252@anchor{gnat_ugn/the_gnat_compilation_model id47}@anchor{9e}@anchor{gnat_ugn/the_gnat_compilation_model conditional-compilation}@anchor{18}
4253@section Conditional Compilation
4254
4255
4256This section presents some guidelines for modeling conditional compilation in Ada and describes the
4257gnatprep preprocessor utility.
4258
4259@geindex Conditional compilation
4260
4261@menu
4262* Modeling Conditional Compilation in Ada:: 
4263* Preprocessing with gnatprep:: 
4264* Integrated Preprocessing:: 
4265
4266@end menu
4267
4268@node Modeling Conditional Compilation in Ada,Preprocessing with gnatprep,,Conditional Compilation
4269@anchor{gnat_ugn/the_gnat_compilation_model modeling-conditional-compilation-in-ada}@anchor{9f}@anchor{gnat_ugn/the_gnat_compilation_model id48}@anchor{a0}
4270@subsection Modeling Conditional Compilation in Ada
4271
4272
4273It is often necessary to arrange for a single source program
4274to serve multiple purposes, where it is compiled in different
4275ways to achieve these different goals. Some examples of the
4276need for this feature are
4277
4278
4279@itemize *
4280
4281@item 
4282Adapting a program to a different hardware environment
4283
4284@item 
4285Adapting a program to a different target architecture
4286
4287@item 
4288Turning debugging features on and off
4289
4290@item 
4291Arranging for a program to compile with different compilers
4292@end itemize
4293
4294In C, or C++, the typical approach would be to use the preprocessor
4295that is defined as part of the language. The Ada language does not
4296contain such a feature. This is not an oversight, but rather a very
4297deliberate design decision, based on the experience that overuse of
4298the preprocessing features in C and C++ can result in programs that
4299are extremely difficult to maintain. For example, if we have ten
4300switches that can be on or off, this means that there are a thousand
4301separate programs, any one of which might not even be syntactically
4302correct, and even if syntactically correct, the resulting program
4303might not work correctly. Testing all combinations can quickly become
4304impossible.
4305
4306Nevertheless, the need to tailor programs certainly exists, and in
4307this section we will discuss how this can
4308be achieved using Ada in general, and GNAT in particular.
4309
4310@menu
4311* Use of Boolean Constants:: 
4312* Debugging - A Special Case:: 
4313* Conditionalizing Declarations:: 
4314* Use of Alternative Implementations:: 
4315* Preprocessing:: 
4316
4317@end menu
4318
4319@node Use of Boolean Constants,Debugging - A Special Case,,Modeling Conditional Compilation in Ada
4320@anchor{gnat_ugn/the_gnat_compilation_model id49}@anchor{a1}@anchor{gnat_ugn/the_gnat_compilation_model use-of-boolean-constants}@anchor{a2}
4321@subsubsection Use of Boolean Constants
4322
4323
4324In the case where the difference is simply which code
4325sequence is executed, the cleanest solution is to use Boolean
4326constants to control which code is executed.
4327
4328@example
4329FP_Initialize_Required : constant Boolean := True;
4330...
4331if FP_Initialize_Required then
4332...
4333end if;
4334@end example
4335
4336Not only will the code inside the @cite{if} statement not be executed if
4337the constant Boolean is @cite{False}, but it will also be completely
4338deleted from the program.
4339However, the code is only deleted after the @cite{if} statement
4340has been checked for syntactic and semantic correctness.
4341(In contrast, with preprocessors the code is deleted before the
4342compiler ever gets to see it, so it is not checked until the switch
4343is turned on.)
4344
4345@geindex Preprocessors (contrasted with conditional compilation)
4346
4347Typically the Boolean constants will be in a separate package,
4348something like:
4349
4350@example
4351package Config is
4352   FP_Initialize_Required : constant Boolean := True;
4353   Reset_Available        : constant Boolean := False;
4354   ...
4355end Config;
4356@end example
4357
4358The @cite{Config} package exists in multiple forms for the various targets,
4359with an appropriate script selecting the version of @cite{Config} needed.
4360Then any other unit requiring conditional compilation can do a @emph{with}
4361of @cite{Config} to make the constants visible.
4362
4363@node Debugging - A Special Case,Conditionalizing Declarations,Use of Boolean Constants,Modeling Conditional Compilation in Ada
4364@anchor{gnat_ugn/the_gnat_compilation_model debugging-a-special-case}@anchor{a3}@anchor{gnat_ugn/the_gnat_compilation_model id50}@anchor{a4}
4365@subsubsection Debugging - A Special Case
4366
4367
4368A common use of conditional code is to execute statements (for example
4369dynamic checks, or output of intermediate results) under control of a
4370debug switch, so that the debugging behavior can be turned on and off.
4371This can be done using a Boolean constant to control whether the code
4372is active:
4373
4374@example
4375if Debugging then
4376   Put_Line ("got to the first stage!");
4377end if;
4378@end example
4379
4380or
4381
4382@example
4383if Debugging and then Temperature > 999.0 then
4384   raise Temperature_Crazy;
4385end if;
4386@end example
4387
4388@geindex pragma Assert
4389
4390Since this is a common case, there are special features to deal with
4391this in a convenient manner. For the case of tests, Ada 2005 has added
4392a pragma @cite{Assert} that can be used for such tests. This pragma is modeled
4393on the @cite{Assert} pragma that has always been available in GNAT, so this
4394feature may be used with GNAT even if you are not using Ada 2005 features.
4395The use of pragma @cite{Assert} is described in the
4396@cite{GNAT_Reference_Manual}, but as an
4397example, the last test could be written:
4398
4399@example
4400pragma Assert (Temperature <= 999.0, "Temperature Crazy");
4401@end example
4402
4403or simply
4404
4405@example
4406pragma Assert (Temperature <= 999.0);
4407@end example
4408
4409In both cases, if assertions are active and the temperature is excessive,
4410the exception @cite{Assert_Failure} will be raised, with the given string in
4411the first case or a string indicating the location of the pragma in the second
4412case used as the exception message.
4413
4414@geindex pragma Assertion_Policy
4415
4416You can turn assertions on and off by using the @cite{Assertion_Policy}
4417pragma.
4418
4419@geindex -gnata switch
4420
4421This is an Ada 2005 pragma which is implemented in all modes by
4422GNAT. Alternatively, you can use the @emph{-gnata} switch
4423to enable assertions from the command line, which applies to
4424all versions of Ada.
4425
4426@geindex pragma Debug
4427
4428For the example above with the @cite{Put_Line}, the GNAT-specific pragma
4429@cite{Debug} can be used:
4430
4431@example
4432pragma Debug (Put_Line ("got to the first stage!"));
4433@end example
4434
4435If debug pragmas are enabled, the argument, which must be of the form of
4436a procedure call, is executed (in this case, @cite{Put_Line} will be called).
4437Only one call can be present, but of course a special debugging procedure
4438containing any code you like can be included in the program and then
4439called in a pragma @cite{Debug} argument as needed.
4440
4441One advantage of pragma @cite{Debug} over the @cite{if Debugging then}
4442construct is that pragma @cite{Debug} can appear in declarative contexts,
4443such as at the very beginning of a procedure, before local declarations have
4444been elaborated.
4445
4446@geindex pragma Debug_Policy
4447
4448Debug pragmas are enabled using either the @emph{-gnata} switch that also
4449controls assertions, or with a separate Debug_Policy pragma.
4450
4451The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
4452in Ada 95 and Ada 83 programs as well), and is analogous to
4453pragma @cite{Assertion_Policy} to control assertions.
4454
4455@cite{Assertion_Policy} and @cite{Debug_Policy} are configuration pragmas,
4456and thus they can appear in @code{gnat.adc} if you are not using a
4457project file, or in the file designated to contain configuration pragmas
4458in a project file.
4459They then apply to all subsequent compilations. In practice the use of
4460the @emph{-gnata} switch is often the most convenient method of controlling
4461the status of these pragmas.
4462
4463Note that a pragma is not a statement, so in contexts where a statement
4464sequence is required, you can't just write a pragma on its own. You have
4465to add a @cite{null} statement.
4466
4467@example
4468if ... then
4469   ... -- some statements
4470else
4471   pragma Assert (Num_Cases < 10);
4472   null;
4473end if;
4474@end example
4475
4476@node Conditionalizing Declarations,Use of Alternative Implementations,Debugging - A Special Case,Modeling Conditional Compilation in Ada
4477@anchor{gnat_ugn/the_gnat_compilation_model conditionalizing-declarations}@anchor{a5}@anchor{gnat_ugn/the_gnat_compilation_model id51}@anchor{a6}
4478@subsubsection Conditionalizing Declarations
4479
4480
4481In some cases it may be necessary to conditionalize declarations to meet
4482different requirements. For example we might want a bit string whose length
4483is set to meet some hardware message requirement.
4484
4485This may be possible using declare blocks controlled
4486by conditional constants:
4487
4488@example
4489if Small_Machine then
4490   declare
4491      X : Bit_String (1 .. 10);
4492   begin
4493      ...
4494   end;
4495else
4496   declare
4497      X : Large_Bit_String (1 .. 1000);
4498   begin
4499      ...
4500   end;
4501end if;
4502@end example
4503
4504Note that in this approach, both declarations are analyzed by the
4505compiler so this can only be used where both declarations are legal,
4506even though one of them will not be used.
4507
4508Another approach is to define integer constants, e.g., @cite{Bits_Per_Word},
4509or Boolean constants, e.g., @cite{Little_Endian}, and then write declarations
4510that are parameterized by these constants. For example
4511
4512@example
4513for Rec use
4514  Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
4515end record;
4516@end example
4517
4518If @cite{Bits_Per_Word} is set to 32, this generates either
4519
4520@example
4521for Rec use
4522  Field1 at 0 range 0 .. 32;
4523end record;
4524@end example
4525
4526for the big endian case, or
4527
4528@example
4529for Rec use record
4530    Field1 at 0 range 10 .. 32;
4531end record;
4532@end example
4533
4534for the little endian case. Since a powerful subset of Ada expression
4535notation is usable for creating static constants, clever use of this
4536feature can often solve quite difficult problems in conditionalizing
4537compilation (note incidentally that in Ada 95, the little endian
4538constant was introduced as @cite{System.Default_Bit_Order}, so you do not
4539need to define this one yourself).
4540
4541@node Use of Alternative Implementations,Preprocessing,Conditionalizing Declarations,Modeling Conditional Compilation in Ada
4542@anchor{gnat_ugn/the_gnat_compilation_model use-of-alternative-implementations}@anchor{a7}@anchor{gnat_ugn/the_gnat_compilation_model id52}@anchor{a8}
4543@subsubsection Use of Alternative Implementations
4544
4545
4546In some cases, none of the approaches described above are adequate. This
4547can occur for example if the set of declarations required is radically
4548different for two different configurations.
4549
4550In this situation, the official Ada way of dealing with conditionalizing
4551such code is to write separate units for the different cases. As long as
4552this does not result in excessive duplication of code, this can be done
4553without creating maintenance problems. The approach is to share common
4554code as far as possible, and then isolate the code and declarations
4555that are different. Subunits are often a convenient method for breaking
4556out a piece of a unit that is to be conditionalized, with separate files
4557for different versions of the subunit for different targets, where the
4558build script selects the right one to give to the compiler.
4559
4560@geindex Subunits (and conditional compilation)
4561
4562As an example, consider a situation where a new feature in Ada 2005
4563allows something to be done in a really nice way. But your code must be able
4564to compile with an Ada 95 compiler. Conceptually you want to say:
4565
4566@example
4567if Ada_2005 then
4568   ... neat Ada 2005 code
4569else
4570   ... not quite as neat Ada 95 code
4571end if;
4572@end example
4573
4574where @cite{Ada_2005} is a Boolean constant.
4575
4576But this won't work when @cite{Ada_2005} is set to @cite{False},
4577since the @cite{then} clause will be illegal for an Ada 95 compiler.
4578(Recall that although such unreachable code would eventually be deleted
4579by the compiler, it still needs to be legal.  If it uses features
4580introduced in Ada 2005, it will be illegal in Ada 95.)
4581
4582So instead we write
4583
4584@example
4585procedure Insert is separate;
4586@end example
4587
4588Then we have two files for the subunit @cite{Insert}, with the two sets of
4589code.
4590If the package containing this is called @cite{File_Queries}, then we might
4591have two files
4592
4593
4594@itemize *
4595
4596@item 
4597@code{file_queries-insert-2005.adb}
4598
4599@item 
4600@code{file_queries-insert-95.adb}
4601@end itemize
4602
4603and the build script renames the appropriate file to @code{file_queries-insert.adb} and then carries out the compilation.
4604
4605This can also be done with project files' naming schemes. For example:
4606
4607@example
4608for body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
4609@end example
4610
4611Note also that with project files it is desirable to use a different extension
4612than @code{ads} / @code{adb} for alternative versions. Otherwise a naming
4613conflict may arise through another commonly used feature: to declare as part
4614of the project a set of directories containing all the sources obeying the
4615default naming scheme.
4616
4617The use of alternative units is certainly feasible in all situations,
4618and for example the Ada part of the GNAT run-time is conditionalized
4619based on the target architecture using this approach. As a specific example,
4620consider the implementation of the AST feature in VMS. There is one
4621spec: @code{s-asthan.ads} which is the same for all architectures, and three
4622bodies:
4623
4624
4625@itemize *
4626
4627@item 
4628
4629@table @asis
4630
4631@item @code{s-asthan.adb}
4632
4633used for all non-VMS operating systems
4634@end table
4635
4636@item 
4637
4638@table @asis
4639
4640@item @code{s-asthan-vms-alpha.adb}
4641
4642used for VMS on the Alpha
4643@end table
4644
4645@item 
4646
4647@table @asis
4648
4649@item @code{s-asthan-vms-ia64.adb}
4650
4651used for VMS on the ia64
4652@end table
4653@end itemize
4654
4655The dummy version @code{s-asthan.adb} simply raises exceptions noting that
4656this operating system feature is not available, and the two remaining
4657versions interface with the corresponding versions of VMS to provide
4658VMS-compatible AST handling. The GNAT build script knows the architecture
4659and operating system, and automatically selects the right version,
4660renaming it if necessary to @code{s-asthan.adb} before the run-time build.
4661
4662Another style for arranging alternative implementations is through Ada's
4663access-to-subprogram facility.
4664In case some functionality is to be conditionally included,
4665you can declare an access-to-procedure variable @cite{Ref} that is initialized
4666to designate a 'do nothing' procedure, and then invoke @cite{Ref.all}
4667when appropriate.
4668In some library package, set @cite{Ref} to @cite{Proc'Access} for some
4669procedure @cite{Proc} that performs the relevant processing.
4670The initialization only occurs if the library package is included in the
4671program.
4672The same idea can also be implemented using tagged types and dispatching
4673calls.
4674
4675@node Preprocessing,,Use of Alternative Implementations,Modeling Conditional Compilation in Ada
4676@anchor{gnat_ugn/the_gnat_compilation_model preprocessing}@anchor{a9}@anchor{gnat_ugn/the_gnat_compilation_model id53}@anchor{aa}
4677@subsubsection Preprocessing
4678
4679
4680@geindex Preprocessing
4681
4682Although it is quite possible to conditionalize code without the use of
4683C-style preprocessing, as described earlier in this section, it is
4684nevertheless convenient in some cases to use the C approach. Moreover,
4685older Ada compilers have often provided some preprocessing capability,
4686so legacy code may depend on this approach, even though it is not
4687standard.
4688
4689To accommodate such use, GNAT provides a preprocessor (modeled to a large
4690extent on the various preprocessors that have been used
4691with legacy code on other compilers, to enable easier transition).
4692
4693@geindex gnatprep
4694
4695The preprocessor may be used in two separate modes. It can be used quite
4696separately from the compiler, to generate a separate output source file
4697that is then fed to the compiler as a separate step. This is the
4698@cite{gnatprep} utility, whose use is fully described in
4699@ref{19,,Preprocessing with gnatprep}.
4700
4701The preprocessing language allows such constructs as
4702
4703@example
4704#if DEBUG or else (PRIORITY > 4) then
4705   bunch of declarations
4706#else
4707   completely different bunch of declarations
4708#end if;
4709@end example
4710
4711The values of the symbols @cite{DEBUG} and @cite{PRIORITY} can be
4712defined either on the command line or in a separate file.
4713
4714The other way of running the preprocessor is even closer to the C style and
4715often more convenient. In this approach the preprocessing is integrated into
4716the compilation process. The compiler is fed the preprocessor input which
4717includes @cite{#if} lines etc, and then the compiler carries out the
4718preprocessing internally and processes the resulting output.
4719For more details on this approach, see @ref{1a,,Integrated Preprocessing}.
4720
4721@node Preprocessing with gnatprep,Integrated Preprocessing,Modeling Conditional Compilation in Ada,Conditional Compilation
4722@anchor{gnat_ugn/the_gnat_compilation_model id54}@anchor{ab}@anchor{gnat_ugn/the_gnat_compilation_model preprocessing-with-gnatprep}@anchor{19}
4723@subsection Preprocessing with @cite{gnatprep}
4724
4725
4726@geindex gnatprep
4727
4728@geindex Preprocessing (gnatprep)
4729
4730This section discusses how to use GNAT's @cite{gnatprep} utility for simple
4731preprocessing.
4732Although designed for use with GNAT, @cite{gnatprep} does not depend on any
4733special GNAT features.
4734For further discussion of conditional compilation in general, see
4735@ref{18,,Conditional Compilation}.
4736
4737@menu
4738* Preprocessing Symbols:: 
4739* Using gnatprep:: 
4740* Switches for gnatprep:: 
4741* Form of Definitions File:: 
4742* Form of Input Text for gnatprep:: 
4743
4744@end menu
4745
4746@node Preprocessing Symbols,Using gnatprep,,Preprocessing with gnatprep
4747@anchor{gnat_ugn/the_gnat_compilation_model id55}@anchor{ac}@anchor{gnat_ugn/the_gnat_compilation_model preprocessing-symbols}@anchor{ad}
4748@subsubsection Preprocessing Symbols
4749
4750
4751Preprocessing symbols are defined in definition files and referred to in
4752sources to be preprocessed. A Preprocessing symbol is an identifier, following
4753normal Ada (case-insensitive) rules for its syntax, with the restriction that
4754all characters need to be in the ASCII set (no accented letters).
4755
4756@node Using gnatprep,Switches for gnatprep,Preprocessing Symbols,Preprocessing with gnatprep
4757@anchor{gnat_ugn/the_gnat_compilation_model using-gnatprep}@anchor{ae}@anchor{gnat_ugn/the_gnat_compilation_model id56}@anchor{af}
4758@subsubsection Using @cite{gnatprep}
4759
4760
4761To call @cite{gnatprep} use:
4762
4763@example
4764$ gnatprep [`switches`] `infile` `outfile` [`deffile`]
4765@end example
4766
4767where
4768
4769
4770@itemize *
4771
4772@item 
4773
4774@table @asis
4775
4776@item @emph{switches}
4777
4778is an optional sequence of switches as described in the next section.
4779@end table
4780
4781@item 
4782
4783@table @asis
4784
4785@item @emph{infile}
4786
4787is the full name of the input file, which is an Ada source
4788file containing preprocessor directives.
4789@end table
4790
4791@item 
4792
4793@table @asis
4794
4795@item @emph{outfile}
4796
4797is the full name of the output file, which is an Ada source
4798in standard Ada form. When used with GNAT, this file name will
4799normally have an ads or adb suffix.
4800@end table
4801
4802@item 
4803
4804@table @asis
4805
4806@item @emph{deffile}
4807
4808is the full name of a text file containing definitions of
4809preprocessing symbols to be referenced by the preprocessor. This argument is
4810optional, and can be replaced by the use of the @emph{-D} switch.
4811@end table
4812@end itemize
4813
4814@node Switches for gnatprep,Form of Definitions File,Using gnatprep,Preprocessing with gnatprep
4815@anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatprep}@anchor{b0}@anchor{gnat_ugn/the_gnat_compilation_model id57}@anchor{b1}
4816@subsubsection Switches for @cite{gnatprep}
4817
4818
4819@geindex -b (gnatprep)
4820
4821
4822@table @asis
4823
4824@item @code{-b}
4825
4826Causes both preprocessor lines and the lines deleted by
4827preprocessing to be replaced by blank lines in the output source file,
4828preserving line numbers in the output file.
4829@end table
4830
4831@geindex -c (gnatprep)
4832
4833
4834@table @asis
4835
4836@item @code{-c}
4837
4838Causes both preprocessor lines and the lines deleted
4839by preprocessing to be retained in the output source as comments marked
4840with the special string @cite{"--! "}. This option will result in line numbers
4841being preserved in the output file.
4842@end table
4843
4844@geindex -C (gnatprep)
4845
4846
4847@table @asis
4848
4849@item @code{-C}
4850
4851Causes comments to be scanned. Normally comments are ignored by gnatprep.
4852If this option is specified, then comments are scanned and any $symbol
4853substitutions performed as in program text. This is particularly useful
4854when structured comments are used (e.g., when writing programs in the
4855SPARK dialect of Ada). Note that this switch is not available when
4856doing integrated preprocessing (it would be useless in this context
4857since comments are ignored by the compiler in any case).
4858@end table
4859
4860@geindex -D (gnatprep)
4861
4862
4863@table @asis
4864
4865@item @code{-D@emph{symbol}=@emph{value}}
4866
4867Defines a new preprocessing symbol, associated with value. If no value is given
4868on the command line, then symbol is considered to be @cite{True}. This switch
4869can be used in place of a definition file.
4870@end table
4871
4872@geindex -r (gnatprep)
4873
4874
4875@table @asis
4876
4877@item @code{-r}
4878
4879Causes a @cite{Source_Reference} pragma to be generated that
4880references the original input file, so that error messages will use
4881the file name of this original file. The use of this switch implies
4882that preprocessor lines are not to be removed from the file, so its
4883use will force @emph{-b} mode if @emph{-c}
4884has not been specified explicitly.
4885
4886Note that if the file to be preprocessed contains multiple units, then
4887it will be necessary to @cite{gnatchop} the output file from
4888@cite{gnatprep}. If a @cite{Source_Reference} pragma is present
4889in the preprocessed file, it will be respected by
4890@cite{gnatchop -r}
4891so that the final chopped files will correctly refer to the original
4892input source file for @cite{gnatprep}.
4893@end table
4894
4895@geindex -s (gnatprep)
4896
4897
4898@table @asis
4899
4900@item @code{-s}
4901
4902Causes a sorted list of symbol names and values to be
4903listed on the standard output file.
4904@end table
4905
4906@geindex -u (gnatprep)
4907
4908
4909@table @asis
4910
4911@item @code{-u}
4912
4913Causes undefined symbols to be treated as having the value FALSE in the context
4914of a preprocessor test. In the absence of this option, an undefined symbol in
4915a @cite{#if} or @cite{#elsif} test will be treated as an error.
4916@end table
4917
4918Note: if neither @emph{-b} nor @emph{-c} is present,
4919then preprocessor lines and
4920deleted lines are completely removed from the output, unless -r is
4921specified, in which case -b is assumed.
4922
4923@node Form of Definitions File,Form of Input Text for gnatprep,Switches for gnatprep,Preprocessing with gnatprep
4924@anchor{gnat_ugn/the_gnat_compilation_model form-of-definitions-file}@anchor{b2}@anchor{gnat_ugn/the_gnat_compilation_model id58}@anchor{b3}
4925@subsubsection Form of Definitions File
4926
4927
4928The definitions file contains lines of the form:
4929
4930@example
4931symbol := value
4932@end example
4933
4934where @cite{symbol} is a preprocessing symbol, and @cite{value} is one of the following:
4935
4936
4937@itemize *
4938
4939@item 
4940Empty, corresponding to a null substitution,
4941
4942@item 
4943A string literal using normal Ada syntax, or
4944
4945@item 
4946Any sequence of characters from the set @{letters, digits, period, underline@}.
4947@end itemize
4948
4949Comment lines may also appear in the definitions file, starting with
4950the usual @code{--},
4951and comments may be added to the definitions lines.
4952
4953@node Form of Input Text for gnatprep,,Form of Definitions File,Preprocessing with gnatprep
4954@anchor{gnat_ugn/the_gnat_compilation_model id59}@anchor{b4}@anchor{gnat_ugn/the_gnat_compilation_model form-of-input-text-for-gnatprep}@anchor{b5}
4955@subsubsection Form of Input Text for @cite{gnatprep}
4956
4957
4958The input text may contain preprocessor conditional inclusion lines,
4959as well as general symbol substitution sequences.
4960
4961The preprocessor conditional inclusion commands have the form:
4962
4963@example
4964#if <expression> [then]
4965   lines
4966#elsif <expression> [then]
4967   lines
4968#elsif <expression> [then]
4969   lines
4970...
4971#else
4972   lines
4973#end if;
4974@end example
4975
4976In this example, <expression> is defined by the following grammar:
4977
4978@example
4979<expression> ::=  <symbol>
4980<expression> ::=  <symbol> = "<value>"
4981<expression> ::=  <symbol> = <symbol>
4982<expression> ::=  <symbol> = <integer>
4983<expression> ::=  <symbol> > <integer>
4984<expression> ::=  <symbol> >= <integer>
4985<expression> ::=  <symbol> < <integer>
4986<expression> ::=  <symbol> <= <integer>
4987<expression> ::=  <symbol> 'Defined
4988<expression> ::=  not <expression>
4989<expression> ::=  <expression> and <expression>
4990<expression> ::=  <expression> or <expression>
4991<expression> ::=  <expression> and then <expression>
4992<expression> ::=  <expression> or else <expression>
4993<expression> ::=  ( <expression> )
4994@end example
4995
4996Note the following restriction: it is not allowed to have "and" or "or"
4997following "not" in the same expression without parentheses. For example, this
4998is not allowed:
4999
5000@example
5001not X or Y
5002@end example
5003
5004This can be expressed instead as one of the following forms:
5005
5006@example
5007(not X) or Y
5008not (X or Y)
5009@end example
5010
5011For the first test (<expression> ::= <symbol>) the symbol must have
5012either the value true or false, that is to say the right-hand of the
5013symbol definition must be one of the (case-insensitive) literals
5014@cite{True} or @cite{False}. If the value is true, then the
5015corresponding lines are included, and if the value is false, they are
5016excluded.
5017
5018When comparing a symbol to an integer, the integer is any non negative
5019literal integer as defined in the Ada Reference Manual, such as 3, 16#FF# or
50202#11#. The symbol value must also be a non negative integer. Integer values
5021in the range 0 .. 2**31-1 are supported.
5022
5023The test (<expression> ::= <symbol>'Defined) is true only if
5024the symbol has been defined in the definition file or by a @emph{-D}
5025switch on the command line. Otherwise, the test is false.
5026
5027The equality tests are case insensitive, as are all the preprocessor lines.
5028
5029If the symbol referenced is not defined in the symbol definitions file,
5030then the effect depends on whether or not switch @emph{-u}
5031is specified. If so, then the symbol is treated as if it had the value
5032false and the test fails. If this switch is not specified, then
5033it is an error to reference an undefined symbol. It is also an error to
5034reference a symbol that is defined with a value other than @cite{True}
5035or @cite{False}.
5036
5037The use of the @cite{not} operator inverts the sense of this logical test.
5038The @cite{not} operator cannot be combined with the @cite{or} or @cite{and}
5039operators, without parentheses. For example, "if not X or Y then" is not
5040allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
5041
5042The @cite{then} keyword is optional as shown
5043
5044The @cite{#} must be the first non-blank character on a line, but
5045otherwise the format is free form. Spaces or tabs may appear between
5046the @cite{#} and the keyword. The keywords and the symbols are case
5047insensitive as in normal Ada code. Comments may be used on a
5048preprocessor line, but other than that, no other tokens may appear on a
5049preprocessor line. Any number of @cite{elsif} clauses can be present,
5050including none at all. The @cite{else} is optional, as in Ada.
5051
5052The @cite{#} marking the start of a preprocessor line must be the first
5053non-blank character on the line, i.e., it must be preceded only by
5054spaces or horizontal tabs.
5055
5056Symbol substitution outside of preprocessor lines is obtained by using
5057the sequence:
5058
5059@example
5060$symbol
5061@end example
5062
5063anywhere within a source line, except in a comment or within a
5064string literal. The identifier
5065following the @cite{$} must match one of the symbols defined in the symbol
5066definition file, and the result is to substitute the value of the
5067symbol in place of @cite{$symbol} in the output file.
5068
5069Note that although the substitution of strings within a string literal
5070is not possible, it is possible to have a symbol whose defined value is
5071a string literal. So instead of setting XYZ to @cite{hello} and writing:
5072
5073@example
5074Header : String := "$XYZ";
5075@end example
5076
5077you should set XYZ to @cite{"hello"} and write:
5078
5079@example
5080Header : String := $XYZ;
5081@end example
5082
5083and then the substitution will occur as desired.
5084
5085@node Integrated Preprocessing,,Preprocessing with gnatprep,Conditional Compilation
5086@anchor{gnat_ugn/the_gnat_compilation_model id60}@anchor{b6}@anchor{gnat_ugn/the_gnat_compilation_model integrated-preprocessing}@anchor{1a}
5087@subsection Integrated Preprocessing
5088
5089
5090GNAT sources may be preprocessed immediately before compilation.
5091In this case, the actual
5092text of the source is not the text of the source file, but is derived from it
5093through a process called preprocessing. Integrated preprocessing is specified
5094through switches @emph{-gnatep} and/or @emph{-gnateD}. @emph{-gnatep}
5095indicates, through a text file, the preprocessing data to be used.
5096@code{-gnateD} specifies or modifies the values of preprocessing symbol.
5097Note that integrated preprocessing applies only to Ada source files, it is
5098not available for configuration pragma files.
5099
5100Note that when integrated preprocessing is used, the output from the
5101preprocessor is not written to any external file. Instead it is passed
5102internally to the compiler. If you need to preserve the result of
5103preprocessing in a file, then you should use @emph{gnatprep}
5104to perform the desired preprocessing in stand-alone mode.
5105
5106It is recommended that @emph{gnatmake} switch -s should be
5107used when Integrated Preprocessing is used. The reason is that preprocessing
5108with another Preprocessing Data file without changing the sources will
5109not trigger recompilation without this switch.
5110
5111Note that @emph{gnatmake} switch -m will almost
5112always trigger recompilation for sources that are preprocessed,
5113because @emph{gnatmake} cannot compute the checksum of the source after
5114preprocessing.
5115
5116The actual preprocessing function is described in detail in section
5117@ref{19,,Preprocessing with gnatprep}. This section only describes how integrated
5118preprocessing is triggered and parameterized.
5119
5120@geindex -gnatep (gcc)
5121
5122
5123@table @asis
5124
5125@item @code{-gnatep=@emph{file}}
5126
5127This switch indicates to the compiler the file name (without directory
5128information) of the preprocessor data file to use. The preprocessor data file
5129should be found in the source directories. Note that when the compiler is
5130called by a builder such as (@emph{gnatmake} with a project
5131file, if the object directory is not also a source directory, the builder needs
5132to be called with @emph{-x}.
5133
5134A preprocessing data file is a text file with significant lines indicating
5135how should be preprocessed either a specific source or all sources not
5136mentioned in other lines. A significant line is a nonempty, non-comment line.
5137Comments are similar to Ada comments.
5138
5139Each significant line starts with either a literal string or the character '*'.
5140A literal string is the file name (without directory information) of the source
5141to preprocess. A character '*' indicates the preprocessing for all the sources
5142that are not specified explicitly on other lines (order of the lines is not
5143significant). It is an error to have two lines with the same file name or two
5144lines starting with the character '*'.
5145
5146After the file name or the character '*', another optional literal string
5147indicating the file name of the definition file to be used for preprocessing
5148(@ref{b2,,Form of Definitions File}). The definition files are found by the
5149compiler in one of the source directories. In some cases, when compiling
5150a source in a directory other than the current directory, if the definition
5151file is in the current directory, it may be necessary to add the current
5152directory as a source directory through switch -I., otherwise
5153the compiler would not find the definition file.
5154
5155Then, optionally, switches similar to those of @cite{gnatprep} may
5156be found. Those switches are:
5157
5158
5159@table @asis
5160
5161@item @code{-b}
5162
5163Causes both preprocessor lines and the lines deleted by
5164preprocessing to be replaced by blank lines, preserving the line number.
5165This switch is always implied; however, if specified after @emph{-c}
5166it cancels the effect of @emph{-c}.
5167
5168@item @code{-c}
5169
5170Causes both preprocessor lines and the lines deleted
5171by preprocessing to be retained as comments marked
5172with the special string '@cite{--!}'.
5173
5174@item @code{-Dsymbol=@emph{value}}
5175
5176Define or redefine a symbol, associated with value. A symbol is an Ada
5177identifier, or an Ada reserved word, with the exception of @cite{if},
5178@cite{else}, @cite{elsif}, @cite{end}, @cite{and}, @cite{or} and @cite{then}.
5179@cite{value} is either a literal string, an Ada identifier or any Ada reserved
5180word. A symbol declared with this switch replaces a symbol with the
5181same name defined in a definition file.
5182
5183@item @code{-s}
5184
5185Causes a sorted list of symbol names and values to be
5186listed on the standard output file.
5187
5188@item @code{-u}
5189
5190Causes undefined symbols to be treated as having the value @cite{FALSE}
5191in the context
5192of a preprocessor test. In the absence of this option, an undefined symbol in
5193a @cite{#if} or @cite{#elsif} test will be treated as an error.
5194@end table
5195
5196Examples of valid lines in a preprocessor data file:
5197
5198@example
5199"toto.adb"  "prep.def" -u
5200--  preprocess "toto.adb", using definition file "prep.def",
5201--  undefined symbol are False.
5202
5203* -c -DVERSION=V101
5204--  preprocess all other sources without a definition file;
5205--  suppressed lined are commented; symbol VERSION has the value V101.
5206
5207"titi.adb" "prep2.def" -s
5208--  preprocess "titi.adb", using definition file "prep2.def";
5209--  list all symbols with their values.
5210@end example
5211@end table
5212
5213@geindex -gnateD (gcc)
5214
5215
5216@table @asis
5217
5218@item @code{-gnateDsymbol[=value]}
5219
5220Define or redefine a preprocessing symbol, associated with value. If no value
5221is given on the command line, then the value of the symbol is @cite{True}.
5222A symbol is an identifier, following normal Ada (case-insensitive)
5223rules for its syntax, and value is either an arbitrary string between double
5224quotes or any sequence (including an empty sequence) of characters from the
5225set (letters, digits, period, underline).
5226Ada reserved words may be used as symbols, with the exceptions of @cite{if},
5227@cite{else}, @cite{elsif}, @cite{end}, @cite{and}, @cite{or} and @cite{then}.
5228
5229Examples:
5230
5231@example
5232-gnateDToto=Titi
5233-gnateDFoo
5234-gnateDFoo=\"Foo-Bar\"
5235@end example
5236
5237A symbol declared with this switch on the command line replaces a
5238symbol with the same name either in a definition file or specified with a
5239switch -D in the preprocessor data file.
5240
5241This switch is similar to switch @emph{-D} of @cite{gnatprep}.
5242
5243@item @code{-gnateG}
5244
5245When integrated preprocessing is performed and the preprocessor modifies
5246the source text, write the result of this preprocessing into a file
5247<source>.prep.
5248@end table
5249
5250@node Mixed Language Programming,GNAT and Other Compilation Models,Conditional Compilation,The GNAT Compilation Model
5251@anchor{gnat_ugn/the_gnat_compilation_model mixed-language-programming}@anchor{46}@anchor{gnat_ugn/the_gnat_compilation_model id61}@anchor{b7}
5252@section Mixed Language Programming
5253
5254
5255@geindex Mixed Language Programming
5256
5257This section describes how to develop a mixed-language program,
5258with a focus on combining Ada with C or C++.
5259
5260@menu
5261* Interfacing to C:: 
5262* Calling Conventions:: 
5263* Building Mixed Ada and C++ Programs:: 
5264* Generating Ada Bindings for C and C++ headers:: 
5265
5266@end menu
5267
5268@node Interfacing to C,Calling Conventions,,Mixed Language Programming
5269@anchor{gnat_ugn/the_gnat_compilation_model interfacing-to-c}@anchor{b8}@anchor{gnat_ugn/the_gnat_compilation_model id62}@anchor{b9}
5270@subsection Interfacing to C
5271
5272
5273Interfacing Ada with a foreign language such as C involves using
5274compiler directives to import and/or export entity definitions in each
5275language -- using @cite{extern} statements in C, for instance, and the
5276@cite{Import}, @cite{Export}, and @cite{Convention} pragmas in Ada.
5277A full treatment of these topics is provided in Appendix B, section 1
5278of the Ada Reference Manual.
5279
5280There are two ways to build a program using GNAT that contains some Ada
5281sources and some foreign language sources, depending on whether or not
5282the main subprogram is written in Ada.  Here is a source example with
5283the main subprogram in Ada:
5284
5285@example
5286/* file1.c */
5287#include <stdio.h>
5288
5289void print_num (int num)
5290@{
5291  printf ("num is %d.\\n", num);
5292  return;
5293@}
5294@end example
5295
5296@example
5297/* file2.c */
5298
5299/* num_from_Ada is declared in my_main.adb */
5300extern int num_from_Ada;
5301
5302int get_num (void)
5303@{
5304  return num_from_Ada;
5305@}
5306@end example
5307
5308@example
5309--  my_main.adb
5310procedure My_Main is
5311
5312   --  Declare then export an Integer entity called num_from_Ada
5313   My_Num : Integer := 10;
5314   pragma Export (C, My_Num, "num_from_Ada");
5315
5316   --  Declare an Ada function spec for Get_Num, then use
5317   --  C function get_num for the implementation.
5318   function Get_Num return Integer;
5319   pragma Import (C, Get_Num, "get_num");
5320
5321   --  Declare an Ada procedure spec for Print_Num, then use
5322   --  C function print_num for the implementation.
5323   procedure Print_Num (Num : Integer);
5324   pragma Import (C, Print_Num, "print_num";
5325
5326begin
5327   Print_Num (Get_Num);
5328end My_Main;
5329@end example
5330
5331To build this example:
5332
5333
5334@itemize *
5335
5336@item 
5337First compile the foreign language files to
5338generate object files:
5339
5340@example
5341$ gcc -c file1.c
5342$ gcc -c file2.c
5343@end example
5344
5345@item 
5346Then, compile the Ada units to produce a set of object files and ALI
5347files:
5348
5349@example
5350$ gnatmake -c my_main.adb
5351@end example
5352
5353@item 
5354Run the Ada binder on the Ada main program:
5355
5356@example
5357$ gnatbind my_main.ali
5358@end example
5359
5360@item 
5361Link the Ada main program, the Ada objects and the other language
5362objects:
5363
5364@example
5365$ gnatlink my_main.ali file1.o file2.o
5366@end example
5367@end itemize
5368
5369The last three steps can be grouped in a single command:
5370
5371@example
5372$ gnatmake my_main.adb -largs file1.o file2.o
5373@end example
5374
5375@geindex Binder output file
5376
5377If the main program is in a language other than Ada, then you may have
5378more than one entry point into the Ada subsystem. You must use a special
5379binder option to generate callable routines that initialize and
5380finalize the Ada units (@ref{ba,,Binding with Non-Ada Main Programs}).
5381Calls to the initialization and finalization routines must be inserted
5382in the main program, or some other appropriate point in the code. The
5383call to initialize the Ada units must occur before the first Ada
5384subprogram is called, and the call to finalize the Ada units must occur
5385after the last Ada subprogram returns. The binder will place the
5386initialization and finalization subprograms into the
5387@code{b~xxx.adb} file where they can be accessed by your C
5388sources.  To illustrate, we have the following example:
5389
5390@example
5391/* main.c */
5392extern void adainit (void);
5393extern void adafinal (void);
5394extern int add (int, int);
5395extern int sub (int, int);
5396
5397int main (int argc, char *argv[])
5398@{
5399   int a = 21, b = 7;
5400
5401   adainit();
5402
5403   /* Should print "21 + 7 = 28" */
5404   printf ("%d + %d = %d\\n", a, b, add (a, b));
5405
5406   /* Should print "21 - 7 = 14" */
5407   printf ("%d - %d = %d\\n", a, b, sub (a, b));
5408
5409   adafinal();
5410@}
5411@end example
5412
5413@example
5414--  unit1.ads
5415package Unit1 is
5416   function Add (A, B : Integer) return Integer;
5417   pragma Export (C, Add, "add");
5418end Unit1;
5419@end example
5420
5421@example
5422--  unit1.adb
5423package body Unit1 is
5424   function Add (A, B : Integer) return Integer is
5425   begin
5426      return A + B;
5427   end Add;
5428end Unit1;
5429@end example
5430
5431@example
5432--  unit2.ads
5433package Unit2 is
5434   function Sub (A, B : Integer) return Integer;
5435   pragma Export (C, Sub, "sub");
5436end Unit2;
5437@end example
5438
5439@example
5440--  unit2.adb
5441package body Unit2 is
5442   function Sub (A, B : Integer) return Integer is
5443   begin
5444      return A - B;
5445   end Sub;
5446end Unit2;
5447@end example
5448
5449The build procedure for this application is similar to the last
5450example's:
5451
5452
5453@itemize *
5454
5455@item 
5456First, compile the foreign language files to generate object files:
5457
5458@example
5459$ gcc -c main.c
5460@end example
5461
5462@item 
5463Next, compile the Ada units to produce a set of object files and ALI
5464files:
5465
5466@example
5467$ gnatmake -c unit1.adb
5468$ gnatmake -c unit2.adb
5469@end example
5470
5471@item 
5472Run the Ada binder on every generated ALI file.  Make sure to use the
5473@code{-n} option to specify a foreign main program:
5474
5475@example
5476$ gnatbind -n unit1.ali unit2.ali
5477@end example
5478
5479@item 
5480Link the Ada main program, the Ada objects and the foreign language
5481objects. You need only list the last ALI file here:
5482
5483@example
5484$ gnatlink unit2.ali main.o -o exec_file
5485@end example
5486
5487This procedure yields a binary executable called @code{exec_file}.
5488@end itemize
5489
5490Depending on the circumstances (for example when your non-Ada main object
5491does not provide symbol @cite{main}), you may also need to instruct the
5492GNAT linker not to include the standard startup objects by passing the
5493@code{-nostartfiles} switch to @cite{gnatlink}.
5494
5495@node Calling Conventions,Building Mixed Ada and C++ Programs,Interfacing to C,Mixed Language Programming
5496@anchor{gnat_ugn/the_gnat_compilation_model calling-conventions}@anchor{bb}@anchor{gnat_ugn/the_gnat_compilation_model id63}@anchor{bc}
5497@subsection Calling Conventions
5498
5499
5500@geindex Foreign Languages
5501
5502@geindex Calling Conventions
5503
5504GNAT follows standard calling sequence conventions and will thus interface
5505to any other language that also follows these conventions. The following
5506Convention identifiers are recognized by GNAT:
5507
5508@geindex Interfacing to Ada
5509
5510@geindex Other Ada compilers
5511
5512@geindex Convention Ada
5513
5514
5515@table @asis
5516
5517@item @emph{Ada}
5518
5519This indicates that the standard Ada calling sequence will be
5520used and all Ada data items may be passed without any limitations in the
5521case where GNAT is used to generate both the caller and callee. It is also
5522possible to mix GNAT generated code and code generated by another Ada
5523compiler. In this case, the data types should be restricted to simple
5524cases, including primitive types. Whether complex data types can be passed
5525depends on the situation. Probably it is safe to pass simple arrays, such
5526as arrays of integers or floats. Records may or may not work, depending
5527on whether both compilers lay them out identically. Complex structures
5528involving variant records, access parameters, tasks, or protected types,
5529are unlikely to be able to be passed.
5530
5531Note that in the case of GNAT running
5532on a platform that supports HP Ada 83, a higher degree of compatibility
5533can be guaranteed, and in particular records are laid out in an identical
5534manner in the two compilers. Note also that if output from two different
5535compilers is mixed, the program is responsible for dealing with elaboration
5536issues. Probably the safest approach is to write the main program in the
5537version of Ada other than GNAT, so that it takes care of its own elaboration
5538requirements, and then call the GNAT-generated adainit procedure to ensure
5539elaboration of the GNAT components. Consult the documentation of the other
5540Ada compiler for further details on elaboration.
5541
5542However, it is not possible to mix the tasking run time of GNAT and
5543HP Ada 83, All the tasking operations must either be entirely within
5544GNAT compiled sections of the program, or entirely within HP Ada 83
5545compiled sections of the program.
5546@end table
5547
5548@geindex Interfacing to Assembly
5549
5550@geindex Convention Assembler
5551
5552
5553@table @asis
5554
5555@item @emph{Assembler}
5556
5557Specifies assembler as the convention. In practice this has the
5558same effect as convention Ada (but is not equivalent in the sense of being
5559considered the same convention).
5560@end table
5561
5562@geindex Convention Asm
5563
5564@geindex Asm
5565
5566
5567@table @asis
5568
5569@item @emph{Asm}
5570
5571Equivalent to Assembler.
5572
5573@geindex Interfacing to COBOL
5574
5575@geindex Convention COBOL
5576@end table
5577
5578@geindex COBOL
5579
5580
5581@table @asis
5582
5583@item @emph{COBOL}
5584
5585Data will be passed according to the conventions described
5586in section B.4 of the Ada Reference Manual.
5587@end table
5588
5589@geindex C
5590
5591@geindex Interfacing to C
5592
5593@geindex Convention C
5594
5595
5596@table @asis
5597
5598@item @emph{C}
5599
5600Data will be passed according to the conventions described
5601in section B.3 of the Ada Reference Manual.
5602
5603A note on interfacing to a C 'varargs' function:
5604
5605@quotation
5606
5607@geindex C varargs function
5608
5609@geindex Interfacing to C varargs function
5610
5611@geindex varargs function interfaces
5612
5613In C, @cite{varargs} allows a function to take a variable number of
5614arguments. There is no direct equivalent in this to Ada. One
5615approach that can be used is to create a C wrapper for each
5616different profile and then interface to this C wrapper. For
5617example, to print an @cite{int} value using @cite{printf},
5618create a C function @cite{printfi} that takes two arguments, a
5619pointer to a string and an int, and calls @cite{printf}.
5620Then in the Ada program, use pragma @cite{Import} to
5621interface to @cite{printfi}.
5622
5623It may work on some platforms to directly interface to
5624a @cite{varargs} function by providing a specific Ada profile
5625for a particular call. However, this does not work on
5626all platforms, since there is no guarantee that the
5627calling sequence for a two argument normal C function
5628is the same as for calling a @cite{varargs} C function with
5629the same two arguments.
5630@end quotation
5631@end table
5632
5633@geindex Convention Default
5634
5635@geindex Default
5636
5637
5638@table @asis
5639
5640@item @emph{Default}
5641
5642Equivalent to C.
5643@end table
5644
5645@geindex Convention External
5646
5647@geindex External
5648
5649
5650@table @asis
5651
5652@item @emph{External}
5653
5654Equivalent to C.
5655@end table
5656
5657@geindex C++
5658
5659@geindex Interfacing to C++
5660
5661@geindex Convention C++
5662
5663
5664@table @asis
5665
5666@item @emph{C_Plus_Plus (or CPP)}
5667
5668This stands for C++. For most purposes this is identical to C.
5669See the separate description of the specialized GNAT pragmas relating to
5670C++ interfacing for further details.
5671@end table
5672
5673@geindex Fortran
5674
5675@geindex Interfacing to Fortran
5676
5677@geindex Convention Fortran
5678
5679
5680@table @asis
5681
5682@item @emph{Fortran}
5683
5684Data will be passed according to the conventions described
5685in section B.5 of the Ada Reference Manual.
5686
5687@item @emph{Intrinsic}
5688
5689This applies to an intrinsic operation, as defined in the Ada
5690Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
5691this means that the body of the subprogram is provided by the compiler itself,
5692usually by means of an efficient code sequence, and that the user does not
5693supply an explicit body for it. In an application program, the pragma may
5694be applied to the following sets of names:
5695
5696
5697@itemize *
5698
5699@item 
5700Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_Arithmetic.
5701The corresponding subprogram declaration must have
5702two formal parameters. The
5703first one must be a signed integer type or a modular type with a binary
5704modulus, and the second parameter must be of type Natural.
5705The return type must be the same as the type of the first argument. The size
5706of this type can only be 8, 16, 32, or 64.
5707
5708@item 
5709Binary arithmetic operators: '+', '-', '*', '/'.
5710The corresponding operator declaration must have parameters and result type
5711that have the same root numeric type (for example, all three are long_float
5712types). This simplifies the definition of operations that use type checking
5713to perform dimensional checks:
5714@end itemize
5715
5716@c code-block: ada
5717@c 
5718@c   type Distance is new Long_Float;
5719@c   type Time     is new Long_Float;
5720@c   type Velocity is new Long_Float;
5721@c   function "/" (D : Distance; T : Time)
5722@c     return Velocity;
5723@c   pragma Import (Intrinsic, "/");
5724@c 
5725@c This common idiom is often programmed with a generic definition and an
5726@c explicit body. The pragma makes it simpler to introduce such declarations.
5727@c It incurs no overhead in compilation time or code size, because it is
5728@c implemented as a single machine instruction.
5729
5730
5731@itemize *
5732
5733@item 
5734General subprogram entities. This is used  to bind an Ada subprogram
5735declaration to
5736a compiler builtin by name with back-ends where such interfaces are
5737available. A typical example is the set of @cite{__builtin} functions
5738exposed by the GCC back-end, as in the following example:
5739
5740@example
5741function builtin_sqrt (F : Float) return Float;
5742pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
5743@end example
5744
5745Most of the GCC builtins are accessible this way, and as for other
5746import conventions (e.g. C), it is the user's responsibility to ensure
5747that the Ada subprogram profile matches the underlying builtin
5748expectations.
5749@end itemize
5750@end table
5751
5752@geindex Stdcall
5753
5754@geindex Convention Stdcall
5755
5756
5757@table @asis
5758
5759@item @emph{Stdcall}
5760
5761This is relevant only to Windows XP/2000/NT implementations of GNAT,
5762and specifies that the @cite{Stdcall} calling sequence will be used,
5763as defined by the NT API. Nevertheless, to ease building
5764cross-platform bindings this convention will be handled as a @cite{C} calling
5765convention on non-Windows platforms.
5766@end table
5767
5768@geindex DLL
5769
5770@geindex Convention DLL
5771
5772
5773@table @asis
5774
5775@item @emph{DLL}
5776
5777This is equivalent to @cite{Stdcall}.
5778@end table
5779
5780@geindex Win32
5781
5782@geindex Convention Win32
5783
5784
5785@table @asis
5786
5787@item @emph{Win32}
5788
5789This is equivalent to @cite{Stdcall}.
5790@end table
5791
5792@geindex Stubbed
5793
5794@geindex Convention Stubbed
5795
5796
5797@table @asis
5798
5799@item @emph{Stubbed}
5800
5801This is a special convention that indicates that the compiler
5802should provide a stub body that raises @cite{Program_Error}.
5803@end table
5804
5805GNAT additionally provides a useful pragma @cite{Convention_Identifier}
5806that can be used to parameterize conventions and allow additional synonyms
5807to be specified. For example if you have legacy code in which the convention
5808identifier Fortran77 was used for Fortran, you can use the configuration
5809pragma:
5810
5811@example
5812pragma Convention_Identifier (Fortran77, Fortran);
5813@end example
5814
5815And from now on the identifier Fortran77 may be used as a convention
5816identifier (for example in an @cite{Import} pragma) with the same
5817meaning as Fortran.
5818
5819@node Building Mixed Ada and C++ Programs,Generating Ada Bindings for C and C++ headers,Calling Conventions,Mixed Language Programming
5820@anchor{gnat_ugn/the_gnat_compilation_model id64}@anchor{bd}@anchor{gnat_ugn/the_gnat_compilation_model building-mixed-ada-and-c-programs}@anchor{be}
5821@subsection Building Mixed Ada and C++ Programs
5822
5823
5824A programmer inexperienced with mixed-language development may find that
5825building an application containing both Ada and C++ code can be a
5826challenge.  This section gives a few hints that should make this task easier.
5827
5828@menu
5829* Interfacing to C++:: 
5830* Linking a Mixed C++ & Ada Program:: 
5831* A Simple Example:: 
5832* Interfacing with C++ constructors:: 
5833* Interfacing with C++ at the Class Level:: 
5834
5835@end menu
5836
5837@node Interfacing to C++,Linking a Mixed C++ & Ada Program,,Building Mixed Ada and C++ Programs
5838@anchor{gnat_ugn/the_gnat_compilation_model id65}@anchor{bf}@anchor{gnat_ugn/the_gnat_compilation_model id66}@anchor{c0}
5839@subsubsection Interfacing to C++
5840
5841
5842GNAT supports interfacing with the G++ compiler (or any C++ compiler
5843generating code that is compatible with the G++ Application Binary
5844Interface ---see @indicateurl{http://www.codesourcery.com/archives/cxx-abi}).
5845
5846Interfacing can be done at 3 levels: simple data, subprograms, and
5847classes. In the first two cases, GNAT offers a specific @cite{Convention C_Plus_Plus}
5848(or @cite{CPP}) that behaves exactly like @cite{Convention C}.
5849Usually, C++ mangles the names of subprograms. To generate proper mangled
5850names automatically, see @ref{1b,,Generating Ada Bindings for C and C++ headers}).
5851This problem can also be addressed manually in two ways:
5852
5853
5854@itemize *
5855
5856@item 
5857by modifying the C++ code in order to force a C convention using
5858the @cite{extern "C"} syntax.
5859
5860@item 
5861by figuring out the mangled name (using e.g. @emph{nm}) and using it as the
5862Link_Name argument of the pragma import.
5863@end itemize
5864
5865Interfacing at the class level can be achieved by using the GNAT specific
5866pragmas such as @cite{CPP_Constructor}.  See the @cite{GNAT_Reference_Manual} for additional information.
5867
5868@node Linking a Mixed C++ & Ada Program,A Simple Example,Interfacing to C++,Building Mixed Ada and C++ Programs
5869@anchor{gnat_ugn/the_gnat_compilation_model linking-a-mixed-c-ada-program}@anchor{c1}@anchor{gnat_ugn/the_gnat_compilation_model linking-a-mixed-c-and-ada-program}@anchor{c2}
5870@subsubsection Linking a Mixed C++ & Ada Program
5871
5872
5873Usually the linker of the C++ development system must be used to link
5874mixed applications because most C++ systems will resolve elaboration
5875issues (such as calling constructors on global class instances)
5876transparently during the link phase. GNAT has been adapted to ease the
5877use of a foreign linker for the last phase. Three cases can be
5878considered:
5879
5880
5881@itemize *
5882
5883@item 
5884Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
5885The C++ linker can simply be called by using the C++ specific driver
5886called @cite{g++}.
5887
5888Note that if the C++ code uses inline functions, you will need to
5889compile your C++ code with the @cite{-fkeep-inline-functions} switch in
5890order to provide an existing function implementation that the Ada code can
5891link with.
5892
5893@example
5894$ g++ -c -fkeep-inline-functions file1.C
5895$ g++ -c -fkeep-inline-functions file2.C
5896$ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
5897@end example
5898
5899@item 
5900Using GNAT and G++ from two different GCC installations: If both
5901compilers are on the :envvar`PATH`, the previous method may be used. It is
5902important to note that environment variables such as
5903@geindex C_INCLUDE_PATH
5904@geindex environment variable; C_INCLUDE_PATH
5905@code{C_INCLUDE_PATH}, 
5906@geindex GCC_EXEC_PREFIX
5907@geindex environment variable; GCC_EXEC_PREFIX
5908@code{GCC_EXEC_PREFIX},
5909@geindex BINUTILS_ROOT
5910@geindex environment variable; BINUTILS_ROOT
5911@code{BINUTILS_ROOT}, and
5912@geindex GCC_ROOT
5913@geindex environment variable; GCC_ROOT
5914@code{GCC_ROOT} will affect both compilers
5915at the same time and may make one of the two compilers operate
5916improperly if set during invocation of the wrong compiler.  It is also
5917very important that the linker uses the proper @code{libgcc.a} GCC
5918library -- that is, the one from the C++ compiler installation. The
5919implicit link command as suggested in the @cite{gnatmake} command
5920from the former example can be replaced by an explicit link command with
5921the full-verbosity option in order to verify which library is used:
5922
5923@example
5924$ gnatbind ada_unit
5925$ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
5926@end example
5927
5928If there is a problem due to interfering environment variables, it can
5929be worked around by using an intermediate script. The following example
5930shows the proper script to use when GNAT has not been installed at its
5931default location and g++ has been installed at its default location:
5932
5933@example
5934$ cat ./my_script
5935#!/bin/sh
5936unset BINUTILS_ROOT
5937unset GCC_ROOT
5938c++ $*
5939$ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
5940@end example
5941
5942@item 
5943Using a non-GNU C++ compiler: The commands previously described can be
5944used to insure that the C++ linker is used. Nonetheless, you need to add
5945a few more parameters to the link command line, depending on the exception
5946mechanism used.
5947
5948If the @cite{setjmp/longjmp} exception mechanism is used, only the paths
5949to the libgcc libraries are required:
5950
5951@example
5952$ cat ./my_script
5953#!/bin/sh
5954CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
5955$ gnatlink ada_unit file1.o file2.o --LINK=./my_script
5956@end example
5957
5958where CC is the name of the non-GNU C++ compiler.
5959
5960If the @cite{zero cost} exception mechanism is used, and the platform
5961supports automatic registration of exception tables (e.g., Solaris),
5962paths to more objects are required:
5963
5964@example
5965$ cat ./my_script
5966#!/bin/sh
5967CC `gcc -print-file-name=crtbegin.o` $* \\
5968`gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \\
5969`gcc -print-file-name=crtend.o`
5970$ gnatlink ada_unit file1.o file2.o --LINK=./my_script
5971@end example
5972
5973If the "zero cost exception" mechanism is used, and the platform
5974doesn't support automatic registration of exception tables (e.g., HP-UX
5975or AIX), the simple approach described above will not work and
5976a pre-linking phase using GNAT will be necessary.
5977@end itemize
5978
5979Another alternative is to use the @code{gprbuild} multi-language builder
5980which has a large knowledge base and knows how to link Ada and C++ code
5981together automatically in most cases.
5982
5983@node A Simple Example,Interfacing with C++ constructors,Linking a Mixed C++ & Ada Program,Building Mixed Ada and C++ Programs
5984@anchor{gnat_ugn/the_gnat_compilation_model id67}@anchor{c3}@anchor{gnat_ugn/the_gnat_compilation_model a-simple-example}@anchor{c4}
5985@subsubsection A Simple Example
5986
5987
5988The following example, provided as part of the GNAT examples, shows how
5989to achieve procedural interfacing between Ada and C++ in both
5990directions. The C++ class A has two methods. The first method is exported
5991to Ada by the means of an extern C wrapper function. The second method
5992calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
5993a limited record with a layout comparable to the C++ class. The Ada
5994subprogram, in turn, calls the C++ method. So, starting from the C++
5995main program, the process passes back and forth between the two
5996languages.
5997
5998Here are the compilation commands:
5999
6000@example
6001$ gnatmake -c simple_cpp_interface
6002$ g++ -c cpp_main.C
6003$ g++ -c ex7.C
6004$ gnatbind -n simple_cpp_interface
6005$ gnatlink simple_cpp_interface -o cpp_main --LINK=g++ -lstdc++ ex7.o cpp_main.o
6006@end example
6007
6008Here are the corresponding sources:
6009
6010@example
6011//cpp_main.C
6012
6013#include "ex7.h"
6014
6015extern "C" @{
6016  void adainit (void);
6017  void adafinal (void);
6018  void method1 (A *t);
6019@}
6020
6021void method1 (A *t)
6022@{
6023  t->method1 ();
6024@}
6025
6026int main ()
6027@{
6028  A obj;
6029  adainit ();
6030  obj.method2 (3030);
6031  adafinal ();
6032@}
6033@end example
6034
6035@example
6036//ex7.h
6037
6038class Origin @{
6039 public:
6040  int o_value;
6041@};
6042class A : public Origin @{
6043 public:
6044  void method1 (void);
6045  void method2 (int v);
6046  A();
6047  int   a_value;
6048@};
6049@end example
6050
6051@example
6052//ex7.C
6053
6054#include "ex7.h"
6055#include <stdio.h>
6056
6057extern "C" @{ void ada_method2 (A *t, int v);@}
6058
6059void A::method1 (void)
6060@{
6061  a_value = 2020;
6062  printf ("in A::method1, a_value = %d \\n",a_value);
6063@}
6064
6065void A::method2 (int v)
6066@{
6067   ada_method2 (this, v);
6068   printf ("in A::method2, a_value = %d \\n",a_value);
6069@}
6070
6071A::A(void)
6072@{
6073   a_value = 1010;
6074  printf ("in A::A, a_value = %d \\n",a_value);
6075@}
6076@end example
6077
6078@example
6079-- simple_cpp_interface.ads
6080with System;
6081package Simple_Cpp_Interface is
6082   type A is limited
6083      record
6084         Vptr    : System.Address;
6085         O_Value : Integer;
6086         A_Value : Integer;
6087      end record;
6088   pragma Convention (C, A);
6089
6090   procedure Method1 (This : in out A);
6091   pragma Import (C, Method1);
6092
6093   procedure Ada_Method2 (This : in out A; V : Integer);
6094   pragma Export (C, Ada_Method2);
6095
6096end Simple_Cpp_Interface;
6097@end example
6098
6099@example
6100-- simple_cpp_interface.adb
6101package body Simple_Cpp_Interface is
6102
6103   procedure Ada_Method2 (This : in out A; V : Integer) is
6104   begin
6105      Method1 (This);
6106      This.A_Value := V;
6107   end Ada_Method2;
6108
6109end Simple_Cpp_Interface;
6110@end example
6111
6112@node Interfacing with C++ constructors,Interfacing with C++ at the Class Level,A Simple Example,Building Mixed Ada and C++ Programs
6113@anchor{gnat_ugn/the_gnat_compilation_model id68}@anchor{c5}@anchor{gnat_ugn/the_gnat_compilation_model interfacing-with-c-constructors}@anchor{c6}
6114@subsubsection Interfacing with C++ constructors
6115
6116
6117In order to interface with C++ constructors GNAT provides the
6118@cite{pragma CPP_Constructor} (see the @cite{GNAT_Reference_Manual}
6119for additional information).
6120In this section we present some common uses of C++ constructors
6121in mixed-languages programs in GNAT.
6122
6123Let us assume that we need to interface with the following
6124C++ class:
6125
6126@example
6127class Root @{
6128public:
6129  int  a_value;
6130  int  b_value;
6131  virtual int Get_Value ();
6132  Root();              // Default constructor
6133  Root(int v);         // 1st non-default constructor
6134  Root(int v, int w);  // 2nd non-default constructor
6135@};
6136@end example
6137
6138For this purpose we can write the following package spec (further
6139information on how to build this spec is available in
6140@ref{c7,,Interfacing with C++ at the Class Level} and
6141@ref{1b,,Generating Ada Bindings for C and C++ headers}).
6142
6143@example
6144with Interfaces.C; use Interfaces.C;
6145package Pkg_Root is
6146  type Root is tagged limited record
6147     A_Value : int;
6148     B_Value : int;
6149  end record;
6150  pragma Import (CPP, Root);
6151
6152  function Get_Value (Obj : Root) return int;
6153  pragma Import (CPP, Get_Value);
6154
6155  function Constructor return Root;
6156  pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
6157
6158  function Constructor (v : Integer) return Root;
6159  pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
6160
6161  function Constructor (v, w : Integer) return Root;
6162  pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
6163end Pkg_Root;
6164@end example
6165
6166On the Ada side the constructor is represented by a function (whose
6167name is arbitrary) that returns the classwide type corresponding to
6168the imported C++ class. Although the constructor is described as a
6169function, it is typically a procedure with an extra implicit argument
6170(the object being initialized) at the implementation level. GNAT
6171issues the appropriate call, whatever it is, to get the object
6172properly initialized.
6173
6174Constructors can only appear in the following contexts:
6175
6176
6177@itemize *
6178
6179@item 
6180On the right side of an initialization of an object of type @cite{T}.
6181
6182@item 
6183On the right side of an initialization of a record component of type @cite{T}.
6184
6185@item 
6186In an Ada 2005 limited aggregate.
6187
6188@item 
6189In an Ada 2005 nested limited aggregate.
6190
6191@item 
6192In an Ada 2005 limited aggregate that initializes an object built in
6193place by an extended return statement.
6194@end itemize
6195
6196In a declaration of an object whose type is a class imported from C++,
6197either the default C++ constructor is implicitly called by GNAT, or
6198else the required C++ constructor must be explicitly called in the
6199expression that initializes the object. For example:
6200
6201@example
6202Obj1 : Root;
6203Obj2 : Root := Constructor;
6204Obj3 : Root := Constructor (v => 10);
6205Obj4 : Root := Constructor (30, 40);
6206@end example
6207
6208The first two declarations are equivalent: in both cases the default C++
6209constructor is invoked (in the former case the call to the constructor is
6210implicit, and in the latter case the call is explicit in the object
6211declaration). @cite{Obj3} is initialized by the C++ non-default constructor
6212that takes an integer argument, and @cite{Obj4} is initialized by the
6213non-default C++ constructor that takes two integers.
6214
6215Let us derive the imported C++ class in the Ada side. For example:
6216
6217@example
6218type DT is new Root with record
6219   C_Value : Natural := 2009;
6220end record;
6221@end example
6222
6223In this case the components DT inherited from the C++ side must be
6224initialized by a C++ constructor, and the additional Ada components
6225of type DT are initialized by GNAT. The initialization of such an
6226object is done either by default, or by means of a function returning
6227an aggregate of type DT, or by means of an extension aggregate.
6228
6229@example
6230Obj5 : DT;
6231Obj6 : DT := Function_Returning_DT (50);
6232Obj7 : DT := (Constructor (30,40) with C_Value => 50);
6233@end example
6234
6235The declaration of @cite{Obj5} invokes the default constructors: the
6236C++ default constructor of the parent type takes care of the initialization
6237of the components inherited from Root, and GNAT takes care of the default
6238initialization of the additional Ada components of type DT (that is,
6239@cite{C_Value} is initialized to value 2009). The order of invocation of
6240the constructors is consistent with the order of elaboration required by
6241Ada and C++. That is, the constructor of the parent type is always called
6242before the constructor of the derived type.
6243
6244Let us now consider a record that has components whose type is imported
6245from C++. For example:
6246
6247@example
6248type Rec1 is limited record
6249   Data1 : Root := Constructor (10);
6250   Value : Natural := 1000;
6251end record;
6252
6253type Rec2 (D : Integer := 20) is limited record
6254   Rec   : Rec1;
6255   Data2 : Root := Constructor (D, 30);
6256end record;
6257@end example
6258
6259The initialization of an object of type @cite{Rec2} will call the
6260non-default C++ constructors specified for the imported components.
6261For example:
6262
6263@example
6264Obj8 : Rec2 (40);
6265@end example
6266
6267Using Ada 2005 we can use limited aggregates to initialize an object
6268invoking C++ constructors that differ from those specified in the type
6269declarations. For example:
6270
6271@example
6272Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
6273                        others => <>),
6274                others => <>);
6275@end example
6276
6277The above declaration uses an Ada 2005 limited aggregate to
6278initialize @cite{Obj9}, and the C++ constructor that has two integer
6279arguments is invoked to initialize the @cite{Data1} component instead
6280of the constructor specified in the declaration of type @cite{Rec1}. In
6281Ada 2005 the box in the aggregate indicates that unspecified components
6282are initialized using the expression (if any) available in the component
6283declaration. That is, in this case discriminant @cite{D} is initialized
6284to value @cite{20}, @cite{Value} is initialized to value 1000, and the
6285non-default C++ constructor that handles two integers takes care of
6286initializing component @cite{Data2} with values @cite{20@comma{}30}.
6287
6288In Ada 2005 we can use the extended return statement to build the Ada
6289equivalent to C++ non-default constructors. For example:
6290
6291@example
6292function Constructor (V : Integer) return Rec2 is
6293begin
6294   return Obj : Rec2 := (Rec => (Data1  => Constructor (V, 20),
6295                                 others => <>),
6296                         others => <>) do
6297      --  Further actions required for construction of
6298      --  objects of type Rec2
6299      ...
6300   end record;
6301end Constructor;
6302@end example
6303
6304In this example the extended return statement construct is used to
6305build in place the returned object whose components are initialized
6306by means of a limited aggregate. Any further action associated with
6307the constructor can be placed inside the construct.
6308
6309@node Interfacing with C++ at the Class Level,,Interfacing with C++ constructors,Building Mixed Ada and C++ Programs
6310@anchor{gnat_ugn/the_gnat_compilation_model interfacing-with-c-at-the-class-level}@anchor{c7}@anchor{gnat_ugn/the_gnat_compilation_model id69}@anchor{c8}
6311@subsubsection Interfacing with C++ at the Class Level
6312
6313
6314In this section we demonstrate the GNAT features for interfacing with
6315C++ by means of an example making use of Ada 2005 abstract interface
6316types. This example consists of a classification of animals; classes
6317have been used to model our main classification of animals, and
6318interfaces provide support for the management of secondary
6319classifications. We first demonstrate a case in which the types and
6320constructors are defined on the C++ side and imported from the Ada
6321side, and latter the reverse case.
6322
6323The root of our derivation will be the @cite{Animal} class, with a
6324single private attribute (the @cite{Age} of the animal), a constructor,
6325and two public primitives to set and get the value of this attribute.
6326
6327@example
6328class Animal @{
6329 public:
6330   virtual void Set_Age (int New_Age);
6331   virtual int Age ();
6332   Animal() @{Age_Count = 0;@};
6333 private:
6334   int Age_Count;
6335@};
6336@end example
6337
6338Abstract interface types are defined in C++ by means of classes with pure
6339virtual functions and no data members. In our example we will use two
6340interfaces that provide support for the common management of @cite{Carnivore}
6341and @cite{Domestic} animals:
6342
6343@example
6344class Carnivore @{
6345public:
6346   virtual int Number_Of_Teeth () = 0;
6347@};
6348
6349class Domestic @{
6350public:
6351   virtual void Set_Owner (char* Name) = 0;
6352@};
6353@end example
6354
6355Using these declarations, we can now say that a @cite{Dog} is an animal that is
6356both Carnivore and Domestic, that is:
6357
6358@example
6359class Dog : Animal, Carnivore, Domestic @{
6360 public:
6361   virtual int  Number_Of_Teeth ();
6362   virtual void Set_Owner (char* Name);
6363
6364   Dog(); // Constructor
6365 private:
6366   int  Tooth_Count;
6367   char *Owner;
6368@};
6369@end example
6370
6371In the following examples we will assume that the previous declarations are
6372located in a file named @cite{animals.h}. The following package demonstrates
6373how to import these C++ declarations from the Ada side:
6374
6375@example
6376with Interfaces.C.Strings; use Interfaces.C.Strings;
6377package Animals is
6378  type Carnivore is limited interface;
6379  pragma Convention (C_Plus_Plus, Carnivore);
6380  function Number_Of_Teeth (X : Carnivore)
6381     return Natural is abstract;
6382
6383  type Domestic is limited interface;
6384  pragma Convention (C_Plus_Plus, Domestic);
6385  procedure Set_Owner
6386    (X    : in out Domestic;
6387     Name : Chars_Ptr) is abstract;
6388
6389  type Animal is tagged limited record
6390    Age : Natural;
6391  end record;
6392  pragma Import (C_Plus_Plus, Animal);
6393
6394  procedure Set_Age (X : in out Animal; Age : Integer);
6395  pragma Import (C_Plus_Plus, Set_Age);
6396
6397  function Age (X : Animal) return Integer;
6398  pragma Import (C_Plus_Plus, Age);
6399
6400  function New_Animal return Animal;
6401  pragma CPP_Constructor (New_Animal);
6402  pragma Import (CPP, New_Animal, "_ZN6AnimalC1Ev");
6403
6404  type Dog is new Animal and Carnivore and Domestic with record
6405    Tooth_Count : Natural;
6406    Owner       : String (1 .. 30);
6407  end record;
6408  pragma Import (C_Plus_Plus, Dog);
6409
6410  function Number_Of_Teeth (A : Dog) return Natural;
6411  pragma Import (C_Plus_Plus, Number_Of_Teeth);
6412
6413  procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
6414  pragma Import (C_Plus_Plus, Set_Owner);
6415
6416  function New_Dog return Dog;
6417  pragma CPP_Constructor (New_Dog);
6418  pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
6419end Animals;
6420@end example
6421
6422Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
6423interfacing with these C++ classes is easy. The only requirement is that all
6424the primitives and components must be declared exactly in the same order in
6425the two languages.
6426
6427Regarding the abstract interfaces, we must indicate to the GNAT compiler by
6428means of a @cite{pragma Convention (C_Plus_Plus)}, the convention used to pass
6429the arguments to the called primitives will be the same as for C++. For the
6430imported classes we use @cite{pragma Import} with convention @cite{C_Plus_Plus}
6431to indicate that they have been defined on the C++ side; this is required
6432because the dispatch table associated with these tagged types will be built
6433in the C++ side and therefore will not contain the predefined Ada primitives
6434which Ada would otherwise expect.
6435
6436As the reader can see there is no need to indicate the C++ mangled names
6437associated with each subprogram because it is assumed that all the calls to
6438these primitives will be dispatching calls. The only exception is the
6439constructor, which must be registered with the compiler by means of
6440@cite{pragma CPP_Constructor} and needs to provide its associated C++
6441mangled name because the Ada compiler generates direct calls to it.
6442
6443With the above packages we can now declare objects of type Dog on the Ada side
6444and dispatch calls to the corresponding subprograms on the C++ side. We can
6445also extend the tagged type Dog with further fields and primitives, and
6446override some of its C++ primitives on the Ada side. For example, here we have
6447a type derivation defined on the Ada side that inherits all the dispatching
6448primitives of the ancestor from the C++ side.
6449
6450@example
6451with Animals; use Animals;
6452package Vaccinated_Animals is
6453  type Vaccinated_Dog is new Dog with null record;
6454  function Vaccination_Expired (A : Vaccinated_Dog) return Boolean;
6455end Vaccinated_Animals;
6456@end example
6457
6458It is important to note that, because of the ABI compatibility, the programmer
6459does not need to add any further information to indicate either the object
6460layout or the dispatch table entry associated with each dispatching operation.
6461
6462Now let us define all the types and constructors on the Ada side and export
6463them to C++, using the same hierarchy of our previous example:
6464
6465@example
6466with Interfaces.C.Strings;
6467use Interfaces.C.Strings;
6468package Animals is
6469  type Carnivore is limited interface;
6470  pragma Convention (C_Plus_Plus, Carnivore);
6471  function Number_Of_Teeth (X : Carnivore)
6472     return Natural is abstract;
6473
6474  type Domestic is limited interface;
6475  pragma Convention (C_Plus_Plus, Domestic);
6476  procedure Set_Owner
6477    (X    : in out Domestic;
6478     Name : Chars_Ptr) is abstract;
6479
6480  type Animal is tagged record
6481    Age : Natural;
6482  end record;
6483  pragma Convention (C_Plus_Plus, Animal);
6484
6485  procedure Set_Age (X : in out Animal; Age : Integer);
6486  pragma Export (C_Plus_Plus, Set_Age);
6487
6488  function Age (X : Animal) return Integer;
6489  pragma Export (C_Plus_Plus, Age);
6490
6491  function New_Animal return Animal'Class;
6492  pragma Export (C_Plus_Plus, New_Animal);
6493
6494  type Dog is new Animal and Carnivore and Domestic with record
6495    Tooth_Count : Natural;
6496    Owner       : String (1 .. 30);
6497  end record;
6498  pragma Convention (C_Plus_Plus, Dog);
6499
6500  function Number_Of_Teeth (A : Dog) return Natural;
6501  pragma Export (C_Plus_Plus, Number_Of_Teeth);
6502
6503  procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
6504  pragma Export (C_Plus_Plus, Set_Owner);
6505
6506  function New_Dog return Dog'Class;
6507  pragma Export (C_Plus_Plus, New_Dog);
6508end Animals;
6509@end example
6510
6511Compared with our previous example the only differences are the use of
6512@cite{pragma Convention} (instead of @cite{pragma Import}), and the use of
6513@cite{pragma Export} to indicate to the GNAT compiler that the primitives will
6514be available to C++. Thanks to the ABI compatibility, on the C++ side there is
6515nothing else to be done; as explained above, the only requirement is that all
6516the primitives and components are declared in exactly the same order.
6517
6518For completeness, let us see a brief C++ main program that uses the
6519declarations available in @cite{animals.h} (presented in our first example) to
6520import and use the declarations from the Ada side, properly initializing and
6521finalizing the Ada run-time system along the way:
6522
6523@example
6524#include "animals.h"
6525#include <iostream>
6526using namespace std;
6527
6528void Check_Carnivore (Carnivore *obj) @{...@}
6529void Check_Domestic (Domestic *obj)   @{...@}
6530void Check_Animal (Animal *obj)       @{...@}
6531void Check_Dog (Dog *obj)             @{...@}
6532
6533extern "C" @{
6534  void adainit (void);
6535  void adafinal (void);
6536  Dog* new_dog ();
6537@}
6538
6539void test ()
6540@{
6541  Dog *obj = new_dog();  // Ada constructor
6542  Check_Carnivore (obj); // Check secondary DT
6543  Check_Domestic (obj);  // Check secondary DT
6544  Check_Animal (obj);    // Check primary DT
6545  Check_Dog (obj);       // Check primary DT
6546@}
6547
6548int main ()
6549@{
6550  adainit ();  test();  adafinal ();
6551  return 0;
6552@}
6553@end example
6554
6555@node Generating Ada Bindings for C and C++ headers,,Building Mixed Ada and C++ Programs,Mixed Language Programming
6556@anchor{gnat_ugn/the_gnat_compilation_model id70}@anchor{c9}@anchor{gnat_ugn/the_gnat_compilation_model generating-ada-bindings-for-c-and-c-headers}@anchor{1b}
6557@subsection Generating Ada Bindings for C and C++ headers
6558
6559
6560@geindex Binding generation (for C and C++ headers)
6561
6562@geindex C headers (binding generation)
6563
6564@geindex C++ headers (binding generation)
6565
6566GNAT includes a binding generator for C and C++ headers which is
6567intended to do 95% of the tedious work of generating Ada specs from C
6568or C++ header files.
6569
6570Note that this capability is not intended to generate 100% correct Ada specs,
6571and will is some cases require manual adjustments, although it can often
6572be used out of the box in practice.
6573
6574Some of the known limitations include:
6575
6576
6577@itemize *
6578
6579@item 
6580only very simple character constant macros are translated into Ada
6581constants. Function macros (macros with arguments) are partially translated
6582as comments, to be completed manually if needed.
6583
6584@item 
6585some extensions (e.g. vector types) are not supported
6586
6587@item 
6588pointers to pointers or complex structures are mapped to System.Address
6589
6590@item 
6591identifiers with identical name (except casing) will generate compilation
6592errors (e.g. @cite{shm_get} vs @cite{SHM_GET}).
6593@end itemize
6594
6595The code generated is using the Ada 2005 syntax, which makes it
6596easier to interface with other languages than previous versions of Ada.
6597
6598@menu
6599* Running the binding generator:: 
6600* Generating bindings for C++ headers:: 
6601* Switches:: 
6602
6603@end menu
6604
6605@node Running the binding generator,Generating bindings for C++ headers,,Generating Ada Bindings for C and C++ headers
6606@anchor{gnat_ugn/the_gnat_compilation_model id71}@anchor{ca}@anchor{gnat_ugn/the_gnat_compilation_model running-the-binding-generator}@anchor{cb}
6607@subsubsection Running the binding generator
6608
6609
6610The binding generator is part of the @emph{gcc} compiler and can be
6611invoked via the @emph{-fdump-ada-spec} switch, which will generate Ada
6612spec files for the header files specified on the command line, and all
6613header files needed by these files transitively. For example:
6614
6615@example
6616$ g++ -c -fdump-ada-spec -C /usr/include/time.h
6617$ gcc -c -gnat05 *.ads
6618@end example
6619
6620will generate, under GNU/Linux, the following files: @code{time_h.ads},
6621@code{bits_time_h.ads}, @code{stddef_h.ads}, @code{bits_types_h.ads} which
6622correspond to the files @code{/usr/include/time.h},
6623@code{/usr/include/bits/time.h}, etc..., and will then compile in Ada 2005
6624mode these Ada specs.
6625
6626The @cite{-C} switch tells @emph{gcc} to extract comments from headers,
6627and will attempt to generate corresponding Ada comments.
6628
6629If you want to generate a single Ada file and not the transitive closure, you
6630can use instead the @emph{-fdump-ada-spec-slim} switch.
6631
6632You can optionally specify a parent unit, of which all generated units will
6633be children, using @cite{-fada-spec-parent=`@w{`}unit}.
6634
6635Note that we recommend when possible to use the @emph{g++} driver to
6636generate bindings, even for most C headers, since this will in general
6637generate better Ada specs. For generating bindings for C++ headers, it is
6638mandatory to use the @emph{g++} command, or @emph{gcc -x c++} which
6639is equivalent in this case. If @emph{g++} cannot work on your C headers
6640because of incompatibilities between C and C++, then you can fallback to
6641@emph{gcc} instead.
6642
6643For an example of better bindings generated from the C++ front-end,
6644the name of the parameters (when available) are actually ignored by the C
6645front-end. Consider the following C header:
6646
6647@example
6648extern void foo (int variable);
6649@end example
6650
6651with the C front-end, @cite{variable} is ignored, and the above is handled as:
6652
6653@example
6654extern void foo (int);
6655@end example
6656
6657generating a generic:
6658
6659@example
6660procedure foo (param1 : int);
6661@end example
6662
6663with the C++ front-end, the name is available, and we generate:
6664
6665@example
6666procedure foo (variable : int);
6667@end example
6668
6669In some cases, the generated bindings will be more complete or more meaningful
6670when defining some macros, which you can do via the @emph{-D} switch. This
6671is for example the case with @code{Xlib.h} under GNU/Linux:
6672
6673@example
6674$ g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
6675@end example
6676
6677The above will generate more complete bindings than a straight call without
6678the @emph{-DXLIB_ILLEGAL_ACCESS} switch.
6679
6680In other cases, it is not possible to parse a header file in a stand-alone
6681manner, because other include files need to be included first. In this
6682case, the solution is to create a small header file including the needed
6683@cite{#include} and possible @cite{#define} directives. For example, to
6684generate Ada bindings for @code{readline/readline.h}, you need to first
6685include @code{stdio.h}, so you can create a file with the following two
6686lines in e.g. @code{readline1.h}:
6687
6688@example
6689#include <stdio.h>
6690#include <readline/readline.h>
6691@end example
6692
6693and then generate Ada bindings from this file:
6694
6695@example
6696$ g++ -c -fdump-ada-spec readline1.h
6697@end example
6698
6699@node Generating bindings for C++ headers,Switches,Running the binding generator,Generating Ada Bindings for C and C++ headers
6700@anchor{gnat_ugn/the_gnat_compilation_model id72}@anchor{cc}@anchor{gnat_ugn/the_gnat_compilation_model generating-bindings-for-c-headers}@anchor{cd}
6701@subsubsection Generating bindings for C++ headers
6702
6703
6704Generating bindings for C++ headers is done using the same options, always
6705with the @emph{g++} compiler. Note that generating Ada spec from C++ headers is a
6706much more complex job and support for C++ headers is much more limited that
6707support for C headers. As a result, you will need to modify the resulting
6708bindings by hand more extensively when using C++ headers.
6709
6710In this mode, C++ classes will be mapped to Ada tagged types, constructors
6711will be mapped using the @cite{CPP_Constructor} pragma, and when possible,
6712multiple inheritance of abstract classes will be mapped to Ada interfaces
6713(see the @emph{Interfacing to C++} section in the @cite{GNAT Reference Manual}
6714for additional information on interfacing to C++).
6715
6716For example, given the following C++ header file:
6717
6718@example
6719class Carnivore @{
6720public:
6721   virtual int Number_Of_Teeth () = 0;
6722@};
6723
6724class Domestic @{
6725public:
6726   virtual void Set_Owner (char* Name) = 0;
6727@};
6728
6729class Animal @{
6730public:
6731  int Age_Count;
6732  virtual void Set_Age (int New_Age);
6733@};
6734
6735class Dog : Animal, Carnivore, Domestic @{
6736 public:
6737  int  Tooth_Count;
6738  char *Owner;
6739
6740  virtual int  Number_Of_Teeth ();
6741  virtual void Set_Owner (char* Name);
6742
6743  Dog();
6744@};
6745@end example
6746
6747The corresponding Ada code is generated:
6748
6749@example
6750package Class_Carnivore is
6751  type Carnivore is limited interface;
6752  pragma Import (CPP, Carnivore);
6753
6754  function Number_Of_Teeth (this : access Carnivore) return int is abstract;
6755end;
6756use Class_Carnivore;
6757
6758package Class_Domestic is
6759  type Domestic is limited interface;
6760  pragma Import (CPP, Domestic);
6761
6762  procedure Set_Owner
6763    (this : access Domestic;
6764     Name : Interfaces.C.Strings.chars_ptr) is abstract;
6765end;
6766use Class_Domestic;
6767
6768package Class_Animal is
6769  type Animal is tagged limited record
6770    Age_Count : aliased int;
6771  end record;
6772  pragma Import (CPP, Animal);
6773
6774  procedure Set_Age (this : access Animal; New_Age : int);
6775  pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
6776end;
6777use Class_Animal;
6778
6779package Class_Dog is
6780  type Dog is new Animal and Carnivore and Domestic with record
6781    Tooth_Count : aliased int;
6782    Owner : Interfaces.C.Strings.chars_ptr;
6783  end record;
6784  pragma Import (CPP, Dog);
6785
6786  function Number_Of_Teeth (this : access Dog) return int;
6787  pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
6788
6789  procedure Set_Owner
6790    (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
6791  pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
6792
6793  function New_Dog return Dog;
6794  pragma CPP_Constructor (New_Dog);
6795  pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
6796end;
6797use Class_Dog;
6798@end example
6799
6800@node Switches,,Generating bindings for C++ headers,Generating Ada Bindings for C and C++ headers
6801@anchor{gnat_ugn/the_gnat_compilation_model switches}@anchor{ce}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-ada-binding-generation}@anchor{cf}
6802@subsubsection Switches
6803
6804
6805@geindex -fdump-ada-spec (gcc)
6806
6807
6808@table @asis
6809
6810@item @code{-fdump-ada-spec}
6811
6812Generate Ada spec files for the given header files transitively (including
6813all header files that these headers depend upon).
6814@end table
6815
6816@geindex -fdump-ada-spec-slim (gcc)
6817
6818
6819@table @asis
6820
6821@item @code{-fdump-ada-spec-slim}
6822
6823Generate Ada spec files for the header files specified on the command line
6824only.
6825@end table
6826
6827@geindex -fada-spec-parent (gcc)
6828
6829
6830@table @asis
6831
6832@item @code{-fada-spec-parent=@emph{unit}}
6833
6834Specifies that all files generated by @emph{-fdump-ada-spec*} are
6835to be child units of the specified parent unit.
6836@end table
6837
6838@geindex -C (gcc)
6839
6840
6841@table @asis
6842
6843@item @code{-C}
6844
6845Extract comments from headers and generate Ada comments in the Ada spec files.
6846@end table
6847
6848@node GNAT and Other Compilation Models,Using GNAT Files with External Tools,Mixed Language Programming,The GNAT Compilation Model
6849@anchor{gnat_ugn/the_gnat_compilation_model id73}@anchor{d0}@anchor{gnat_ugn/the_gnat_compilation_model gnat-and-other-compilation-models}@anchor{47}
6850@section GNAT and Other Compilation Models
6851
6852
6853This section compares the GNAT model with the approaches taken in
6854other environents, first the C/C++ model and then the mechanism that
6855has been used in other Ada systems, in particular those traditionally
6856used for Ada 83.
6857
6858@menu
6859* Comparison between GNAT and C/C++ Compilation Models:: 
6860* Comparison between GNAT and Conventional Ada Library Models:: 
6861
6862@end menu
6863
6864@node Comparison between GNAT and C/C++ Compilation Models,Comparison between GNAT and Conventional Ada Library Models,,GNAT and Other Compilation Models
6865@anchor{gnat_ugn/the_gnat_compilation_model comparison-between-gnat-and-c-c-compilation-models}@anchor{d1}@anchor{gnat_ugn/the_gnat_compilation_model id74}@anchor{d2}
6866@subsection Comparison between GNAT and C/C++ Compilation Models
6867
6868
6869The GNAT model of compilation is close to the C and C++ models. You can
6870think of Ada specs as corresponding to header files in C. As in C, you
6871don't need to compile specs; they are compiled when they are used. The
6872Ada @emph{with} is similar in effect to the @cite{#include} of a C
6873header.
6874
6875One notable difference is that, in Ada, you may compile specs separately
6876to check them for semantic and syntactic accuracy. This is not always
6877possible with C headers because they are fragments of programs that have
6878less specific syntactic or semantic rules.
6879
6880The other major difference is the requirement for running the binder,
6881which performs two important functions. First, it checks for
6882consistency. In C or C++, the only defense against assembling
6883inconsistent programs lies outside the compiler, in a makefile, for
6884example. The binder satisfies the Ada requirement that it be impossible
6885to construct an inconsistent program when the compiler is used in normal
6886mode.
6887
6888@geindex Elaboration order control
6889
6890The other important function of the binder is to deal with elaboration
6891issues. There are also elaboration issues in C++ that are handled
6892automatically. This automatic handling has the advantage of being
6893simpler to use, but the C++ programmer has no control over elaboration.
6894Where @cite{gnatbind} might complain there was no valid order of
6895elaboration, a C++ compiler would simply construct a program that
6896malfunctioned at run time.
6897
6898@node Comparison between GNAT and Conventional Ada Library Models,,Comparison between GNAT and C/C++ Compilation Models,GNAT and Other Compilation Models
6899@anchor{gnat_ugn/the_gnat_compilation_model comparison-between-gnat-and-conventional-ada-library-models}@anchor{d3}@anchor{gnat_ugn/the_gnat_compilation_model id75}@anchor{d4}
6900@subsection Comparison between GNAT and Conventional Ada Library Models
6901
6902
6903This section is intended for Ada programmers who have
6904used an Ada compiler implementing the traditional Ada library
6905model, as described in the Ada Reference Manual.
6906
6907@geindex GNAT library
6908
6909In GNAT, there is no 'library' in the normal sense. Instead, the set of
6910source files themselves acts as the library. Compiling Ada programs does
6911not generate any centralized information, but rather an object file and
6912a ALI file, which are of interest only to the binder and linker.
6913In a traditional system, the compiler reads information not only from
6914the source file being compiled, but also from the centralized library.
6915This means that the effect of a compilation depends on what has been
6916previously compiled. In particular:
6917
6918
6919@itemize *
6920
6921@item 
6922When a unit is @emph{with}ed, the unit seen by the compiler corresponds
6923to the version of the unit most recently compiled into the library.
6924
6925@item 
6926Inlining is effective only if the necessary body has already been
6927compiled into the library.
6928
6929@item 
6930Compiling a unit may obsolete other units in the library.
6931@end itemize
6932
6933In GNAT, compiling one unit never affects the compilation of any other
6934units because the compiler reads only source files. Only changes to source
6935files can affect the results of a compilation. In particular:
6936
6937
6938@itemize *
6939
6940@item 
6941When a unit is @emph{with}ed, the unit seen by the compiler corresponds
6942to the source version of the unit that is currently accessible to the
6943compiler.
6944
6945@geindex Inlining
6946
6947@item 
6948Inlining requires the appropriate source files for the package or
6949subprogram bodies to be available to the compiler. Inlining is always
6950effective, independent of the order in which units are compiled.
6951
6952@item 
6953Compiling a unit never affects any other compilations. The editing of
6954sources may cause previous compilations to be out of date if they
6955depended on the source file being modified.
6956@end itemize
6957
6958The most important result of these differences is that order of compilation
6959is never significant in GNAT. There is no situation in which one is
6960required to do one compilation before another. What shows up as order of
6961compilation requirements in the traditional Ada library becomes, in
6962GNAT, simple source dependencies; in other words, there is only a set
6963of rules saying what source files must be present when a file is
6964compiled.
6965
6966@node Using GNAT Files with External Tools,,GNAT and Other Compilation Models,The GNAT Compilation Model
6967@anchor{gnat_ugn/the_gnat_compilation_model using-gnat-files-with-external-tools}@anchor{1c}@anchor{gnat_ugn/the_gnat_compilation_model id76}@anchor{d5}
6968@section Using GNAT Files with External Tools
6969
6970
6971This section explains how files that are produced by GNAT may be
6972used with tools designed for other languages.
6973
6974@menu
6975* Using Other Utility Programs with GNAT:: 
6976* The External Symbol Naming Scheme of GNAT:: 
6977
6978@end menu
6979
6980@node Using Other Utility Programs with GNAT,The External Symbol Naming Scheme of GNAT,,Using GNAT Files with External Tools
6981@anchor{gnat_ugn/the_gnat_compilation_model using-other-utility-programs-with-gnat}@anchor{d6}@anchor{gnat_ugn/the_gnat_compilation_model id77}@anchor{d7}
6982@subsection Using Other Utility Programs with GNAT
6983
6984
6985The object files generated by GNAT are in standard system format and in
6986particular the debugging information uses this format. This means
6987programs generated by GNAT can be used with existing utilities that
6988depend on these formats.
6989
6990In general, any utility program that works with C will also often work with
6991Ada programs generated by GNAT. This includes software utilities such as
6992gprof (a profiling program), gdb (the FSF debugger), and utilities such
6993as Purify.
6994
6995@node The External Symbol Naming Scheme of GNAT,,Using Other Utility Programs with GNAT,Using GNAT Files with External Tools
6996@anchor{gnat_ugn/the_gnat_compilation_model the-external-symbol-naming-scheme-of-gnat}@anchor{d8}@anchor{gnat_ugn/the_gnat_compilation_model id78}@anchor{d9}
6997@subsection The External Symbol Naming Scheme of GNAT
6998
6999
7000In order to interpret the output from GNAT, when using tools that are
7001originally intended for use with other languages, it is useful to
7002understand the conventions used to generate link names from the Ada
7003entity names.
7004
7005All link names are in all lowercase letters. With the exception of library
7006procedure names, the mechanism used is simply to use the full expanded
7007Ada name with dots replaced by double underscores. For example, suppose
7008we have the following package spec:
7009
7010@example
7011package QRS is
7012   MN : Integer;
7013end QRS;
7014@end example
7015
7016@geindex pragma Export
7017
7018The variable @cite{MN} has a full expanded Ada name of @cite{QRS.MN}, so
7019the corresponding link name is @cite{qrs__mn}.
7020Of course if a @cite{pragma Export} is used this may be overridden:
7021
7022@example
7023package Exports is
7024   Var1 : Integer;
7025   pragma Export (Var1, C, External_Name => "var1_name");
7026   Var2 : Integer;
7027   pragma Export (Var2, C, Link_Name => "var2_link_name");
7028end Exports;
7029@end example
7030
7031In this case, the link name for @cite{Var1} is whatever link name the
7032C compiler would assign for the C function @cite{var1_name}. This typically
7033would be either @cite{var1_name} or @cite{_var1_name}, depending on operating
7034system conventions, but other possibilities exist. The link name for
7035@cite{Var2} is @cite{var2_link_name}, and this is not operating system
7036dependent.
7037
7038One exception occurs for library level procedures. A potential ambiguity
7039arises between the required name @cite{_main} for the C main program,
7040and the name we would otherwise assign to an Ada library level procedure
7041called @cite{Main} (which might well not be the main program).
7042
7043To avoid this ambiguity, we attach the prefix @cite{_ada_} to such
7044names. So if we have a library level procedure such as:
7045
7046@example
7047procedure Hello (S : String);
7048@end example
7049
7050the external name of this procedure will be @cite{_ada_hello}.
7051
7052@c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
7053
7054@node Building Executable Programs with GNAT,GNAT Project Manager,The GNAT Compilation Model,Top
7055@anchor{gnat_ugn/building_executable_programs_with_gnat building-executable-programs-with-gnat}@anchor{a}@anchor{gnat_ugn/building_executable_programs_with_gnat doc}@anchor{da}@anchor{gnat_ugn/building_executable_programs_with_gnat id1}@anchor{db}
7056@chapter Building Executable Programs with GNAT
7057
7058
7059This chapter describes first the gnatmake tool
7060(@ref{1d,,Building with gnatmake}),
7061which automatically determines the set of sources
7062needed by an Ada compilation unit and executes the necessary
7063(re)compilations, binding and linking.
7064It also explains how to use each tool individually: the
7065compiler (gcc, see @ref{1e,,Compiling with gcc}),
7066binder (gnatbind, see @ref{1f,,Binding with gnatbind}),
7067and linker (gnatlink, see @ref{20,,Linking with gnatlink})
7068to build executable programs.
7069Finally, this chapter provides examples of
7070how to make use of the general GNU make mechanism
7071in a GNAT context (see @ref{21,,Using the GNU make Utility}).
7072
7073@menu
7074* Building with gnatmake:: 
7075* Compiling with gcc:: 
7076* Compiler Switches:: 
7077* Binding with gnatbind:: 
7078* Linking with gnatlink:: 
7079* Using the GNU make Utility:: 
7080
7081@end menu
7082
7083@node Building with gnatmake,Compiling with gcc,,Building Executable Programs with GNAT
7084@anchor{gnat_ugn/building_executable_programs_with_gnat the-gnat-make-program-gnatmake}@anchor{1d}@anchor{gnat_ugn/building_executable_programs_with_gnat building-with-gnatmake}@anchor{dc}
7085@section Building with @emph{gnatmake}
7086
7087
7088@geindex gnatmake
7089
7090A typical development cycle when working on an Ada program consists of
7091the following steps:
7092
7093
7094@enumerate 
7095
7096@item 
7097Edit some sources to fix bugs;
7098
7099@item 
7100Add enhancements;
7101
7102@item 
7103Compile all sources affected;
7104
7105@item 
7106Rebind and relink; and
7107
7108@item 
7109Test.
7110@end enumerate
7111
7112@geindex Dependency rules (compilation)
7113
7114The third step in particular can be tricky, because not only do the modified
7115files have to be compiled, but any files depending on these files must also be
7116recompiled. The dependency rules in Ada can be quite complex, especially
7117in the presence of overloading, @cite{use} clauses, generics and inlined
7118subprograms.
7119
7120@emph{gnatmake} automatically takes care of the third and fourth steps
7121of this process. It determines which sources need to be compiled,
7122compiles them, and binds and links the resulting object files.
7123
7124Unlike some other Ada make programs, the dependencies are always
7125accurately recomputed from the new sources. The source based approach of
7126the GNAT compilation model makes this possible. This means that if
7127changes to the source program cause corresponding changes in
7128dependencies, they will always be tracked exactly correctly by
7129@emph{gnatmake}.
7130
7131Note that for advanced description of project structure, we recommend creating
7132a project file as explained in @ref{b,,GNAT Project Manager} and use the
7133@emph{gprbuild} tool which supports building with project files and works similarly
7134to @emph{gnatmake}.
7135
7136@menu
7137* Running gnatmake:: 
7138* Switches for gnatmake:: 
7139* Mode Switches for gnatmake:: 
7140* Notes on the Command Line:: 
7141* How gnatmake Works:: 
7142* Examples of gnatmake Usage:: 
7143
7144@end menu
7145
7146@node Running gnatmake,Switches for gnatmake,,Building with gnatmake
7147@anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatmake}@anchor{dd}@anchor{gnat_ugn/building_executable_programs_with_gnat id2}@anchor{de}
7148@subsection Running @emph{gnatmake}
7149
7150
7151The usual form of the @emph{gnatmake} command is
7152
7153@example
7154$ gnatmake [<switches>] <file_name> [<file_names>] [<mode_switches>]
7155@end example
7156
7157The only required argument is one @cite{file_name}, which specifies
7158a compilation unit that is a main program. Several @cite{file_names} can be
7159specified: this will result in several executables being built.
7160If @cite{switches} are present, they can be placed before the first
7161@cite{file_name}, between @cite{file_names} or after the last @cite{file_name}.
7162If @cite{mode_switches} are present, they must always be placed after
7163the last @cite{file_name} and all @cite{switches}.
7164
7165If you are using standard file extensions (@code{.adb} and
7166@code{.ads}), then the
7167extension may be omitted from the @cite{file_name} arguments. However, if
7168you are using non-standard extensions, then it is required that the
7169extension be given. A relative or absolute directory path can be
7170specified in a @cite{file_name}, in which case, the input source file will
7171be searched for in the specified directory only. Otherwise, the input
7172source file will first be searched in the directory where
7173@emph{gnatmake} was invoked and if it is not found, it will be search on
7174the source path of the compiler as described in
7175@ref{8e,,Search Paths and the Run-Time Library (RTL)}.
7176
7177All @emph{gnatmake} output (except when you specify @emph{-M}) is sent to
7178@code{stderr}. The output produced by the
7179@emph{-M} switch is sent to @code{stdout}.
7180
7181@node Switches for gnatmake,Mode Switches for gnatmake,Running gnatmake,Building with gnatmake
7182@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatmake}@anchor{df}@anchor{gnat_ugn/building_executable_programs_with_gnat id3}@anchor{e0}
7183@subsection Switches for @emph{gnatmake}
7184
7185
7186You may specify any of the following switches to @emph{gnatmake}:
7187
7188@geindex --version (gnatmake)
7189
7190
7191@table @asis
7192
7193@item @code{--version}
7194
7195Display Copyright and version, then exit disregarding all other options.
7196@end table
7197
7198@geindex --help (gnatmake)
7199
7200
7201@table @asis
7202
7203@item @code{--help}
7204
7205If @code{--version} was not used, display usage, then exit disregarding
7206all other options.
7207@end table
7208
7209@geindex --GCC=compiler_name (gnatmake)
7210
7211
7212@table @asis
7213
7214@item @code{--GCC=@emph{compiler_name}}
7215
7216Program used for compiling. The default is @code{gcc}. You need to use
7217quotes around @cite{compiler_name} if @cite{compiler_name} contains
7218spaces or other separator characters.
7219As an example @code{--GCC="foo -x  -y"}
7220will instruct @emph{gnatmake} to use @code{foo -x -y} as your
7221compiler. A limitation of this syntax is that the name and path name of
7222the executable itself must not include any embedded spaces. Note that
7223switch @code{-c} is always inserted after your command name. Thus in the
7224above example the compiler command that will be used by @emph{gnatmake}
7225will be @code{foo -c -x -y}. If several @code{--GCC=compiler_name} are
7226used, only the last @cite{compiler_name} is taken into account. However,
7227all the additional switches are also taken into account. Thus,
7228@code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
7229@code{--GCC="bar -x -y -z -t"}.
7230@end table
7231
7232@geindex --GNATBIND=binder_name (gnatmake)
7233
7234
7235@table @asis
7236
7237@item @code{--GNATBIND=@emph{binder_name}}
7238
7239Program used for binding. The default is @code{gnatbind}. You need to
7240use quotes around @cite{binder_name} if @cite{binder_name} contains spaces
7241or other separator characters.
7242As an example @code{--GNATBIND="bar -x  -y"}
7243will instruct @emph{gnatmake} to use @cite{bar -x -y} as your
7244binder. Binder switches that are normally appended by @emph{gnatmake}
7245to @code{gnatbind} are now appended to the end of @cite{bar -x -y}.
7246A limitation of this syntax is that the name and path name of the executable
7247itself must not include any embedded spaces.
7248@end table
7249
7250@geindex --GNATLINK=linker_name (gnatmake)
7251
7252
7253@table @asis
7254
7255@item @code{--GNATLINK=@emph{linker_name}}
7256
7257Program used for linking. The default is @code{gnatlink}. You need to
7258use quotes around @cite{linker_name} if @cite{linker_name} contains spaces
7259or other separator characters.
7260As an example @code{--GNATLINK="lan -x  -y"}
7261will instruct @emph{gnatmake} to use @code{lan -x -y} as your
7262linker. Linker switches that are normally appended by @code{gnatmake} to
7263@code{gnatlink} are now appended to the end of @code{lan -x -y}.
7264A limitation of this syntax is that the name and path name of the executable
7265itself must not include any embedded spaces.
7266
7267@item @code{--create-map-file}
7268
7269When linking an executable, create a map file. The name of the map file
7270has the same name as the executable with extension ".map".
7271
7272@item @code{--create-map-file=@emph{mapfile}}
7273
7274When linking an executable, create a map file with the specified name.
7275@end table
7276
7277@geindex --create-missing-dirs (gnatmake)
7278
7279
7280@table @asis
7281
7282@item @code{--create-missing-dirs}
7283
7284When using project files (@code{-P@emph{project}}), automatically create
7285missing object directories, library directories and exec
7286directories.
7287
7288@item @code{--single-compile-per-obj-dir}
7289
7290Disallow simultaneous compilations in the same object directory when
7291project files are used.
7292
7293@item @code{--subdirs=@emph{subdir}}
7294
7295Actual object directory of each project file is the subdirectory subdir of the
7296object directory specified or defaulted in the project file.
7297
7298@item @code{--unchecked-shared-lib-imports}
7299
7300By default, shared library projects are not allowed to import static library
7301projects. When this switch is used on the command line, this restriction is
7302relaxed.
7303
7304@item @code{--source-info=@emph{source info file}}
7305
7306Specify a source info file. This switch is active only when project files
7307are used. If the source info file is specified as a relative path, then it is
7308relative to the object directory of the main project. If the source info file
7309does not exist, then after the Project Manager has successfully parsed and
7310processed the project files and found the sources, it creates the source info
7311file. If the source info file already exists and can be read successfully,
7312then the Project Manager will get all the needed information about the sources
7313from the source info file and will not look for them. This reduces the time
7314to process the project files, especially when looking for sources that take a
7315long time. If the source info file exists but cannot be parsed successfully,
7316the Project Manager will attempt to recreate it. If the Project Manager fails
7317to create the source info file, a message is issued, but gnatmake does not
7318fail. @emph{gnatmake} "trusts" the source info file. This means that
7319if the source files have changed (addition, deletion, moving to a different
7320source directory), then the source info file need to be deleted and recreated.
7321@end table
7322
7323@geindex -a (gnatmake)
7324
7325
7326@table @asis
7327
7328@item @code{-a}
7329
7330Consider all files in the make process, even the GNAT internal system
7331files (for example, the predefined Ada library files), as well as any
7332locked files. Locked files are files whose ALI file is write-protected.
7333By default,
7334@emph{gnatmake} does not check these files,
7335because the assumption is that the GNAT internal files are properly up
7336to date, and also that any write protected ALI files have been properly
7337installed. Note that if there is an installation problem, such that one
7338of these files is not up to date, it will be properly caught by the
7339binder.
7340You may have to specify this switch if you are working on GNAT
7341itself. The switch @code{-a} is also useful
7342in conjunction with @code{-f}
7343if you need to recompile an entire application,
7344including run-time files, using special configuration pragmas,
7345such as a @cite{Normalize_Scalars} pragma.
7346
7347By default
7348@code{gnatmake -a} compiles all GNAT
7349internal files with
7350@code{gcc -c -gnatpg} rather than @code{gcc -c}.
7351@end table
7352
7353@geindex -b (gnatmake)
7354
7355
7356@table @asis
7357
7358@item @code{-b}
7359
7360Bind only. Can be combined with @emph{-c} to do
7361compilation and binding, but no link.
7362Can be combined with @emph{-l}
7363to do binding and linking. When not combined with
7364@emph{-c}
7365all the units in the closure of the main program must have been previously
7366compiled and must be up to date. The root unit specified by @cite{file_name}
7367may be given without extension, with the source extension or, if no GNAT
7368Project File is specified, with the ALI file extension.
7369@end table
7370
7371@geindex -c (gnatmake)
7372
7373
7374@table @asis
7375
7376@item @code{-c}
7377
7378Compile only. Do not perform binding, except when @emph{-b}
7379is also specified. Do not perform linking, except if both
7380@emph{-b} and
7381@emph{-l} are also specified.
7382If the root unit specified by @cite{file_name} is not a main unit, this is the
7383default. Otherwise @emph{gnatmake} will attempt binding and linking
7384unless all objects are up to date and the executable is more recent than
7385the objects.
7386@end table
7387
7388@geindex -C (gnatmake)
7389
7390
7391@table @asis
7392
7393@item @code{-C}
7394
7395Use a temporary mapping file. A mapping file is a way to communicate
7396to the compiler two mappings: from unit names to file names (without
7397any directory information) and from file names to path names (with
7398full directory information). A mapping file can make the compiler's
7399file searches faster, especially if there are many source directories,
7400or the sources are read over a slow network connection. If
7401@emph{-P} is used, a mapping file is always used, so
7402@emph{-C} is unnecessary; in this case the mapping file
7403is initially populated based on the project file. If
7404@emph{-C} is used without
7405@emph{-P},
7406the mapping file is initially empty. Each invocation of the compiler
7407will add any newly accessed sources to the mapping file.
7408@end table
7409
7410@geindex -C= (gnatmake)
7411
7412
7413@table @asis
7414
7415@item @code{-C=@emph{file}}
7416
7417Use a specific mapping file. The file, specified as a path name (absolute or
7418relative) by this switch, should already exist, otherwise the switch is
7419ineffective. The specified mapping file will be communicated to the compiler.
7420This switch is not compatible with a project file
7421(-P`file`) or with multiple compiling processes
7422(-jnnn, when nnn is greater than 1).
7423@end table
7424
7425@geindex -d (gnatmake)
7426
7427
7428@table @asis
7429
7430@item @code{-d}
7431
7432Display progress for each source, up to date or not, as a single line:
7433
7434@example
7435completed x out of y (zz%)
7436@end example
7437
7438If the file needs to be compiled this is displayed after the invocation of
7439the compiler. These lines are displayed even in quiet output mode.
7440@end table
7441
7442@geindex -D (gnatmake)
7443
7444
7445@table @asis
7446
7447@item @code{-D @emph{dir}}
7448
7449Put all object files and ALI file in directory @cite{dir}.
7450If the @emph{-D} switch is not used, all object files
7451and ALI files go in the current working directory.
7452
7453This switch cannot be used when using a project file.
7454@end table
7455
7456@geindex -eI (gnatmake)
7457
7458
7459@table @asis
7460
7461@item @code{-eI@emph{nnn}}
7462
7463Indicates that the main source is a multi-unit source and the rank of the unit
7464in the source file is nnn. nnn needs to be a positive number and a valid
7465index in the source. This switch cannot be used when @emph{gnatmake} is
7466invoked for several mains.
7467@end table
7468
7469@geindex -eL (gnatmake)
7470
7471@geindex symbolic links
7472
7473
7474@table @asis
7475
7476@item @code{-eL}
7477
7478Follow all symbolic links when processing project files.
7479This should be used if your project uses symbolic links for files or
7480directories, but is not needed in other cases.
7481
7482@geindex naming scheme
7483
7484This also assumes that no directory matches the naming scheme for files (for
7485instance that you do not have a directory called "sources.ads" when using the
7486default GNAT naming scheme).
7487
7488When you do not have to use this switch (i.e., by default), gnatmake is able to
7489save a lot of system calls (several per source file and object file), which
7490can result in a significant speed up to load and manipulate a project file,
7491especially when using source files from a remote system.
7492@end table
7493
7494@geindex -eS (gnatmake)
7495
7496
7497@table @asis
7498
7499@item @code{-eS}
7500
7501Output the commands for the compiler, the binder and the linker
7502on standard output,
7503instead of standard error.
7504@end table
7505
7506@geindex -f (gnatmake)
7507
7508
7509@table @asis
7510
7511@item @code{-f}
7512
7513Force recompilations. Recompile all sources, even though some object
7514files may be up to date, but don't recompile predefined or GNAT internal
7515files or locked files (files with a write-protected ALI file),
7516unless the @emph{-a} switch is also specified.
7517@end table
7518
7519@geindex -F (gnatmake)
7520
7521
7522@table @asis
7523
7524@item @code{-F}
7525
7526When using project files, if some errors or warnings are detected during
7527parsing and verbose mode is not in effect (no use of switch
7528-v), then error lines start with the full path name of the project
7529file, rather than its simple file name.
7530@end table
7531
7532@geindex -g (gnatmake)
7533
7534
7535@table @asis
7536
7537@item @code{-g}
7538
7539Enable debugging. This switch is simply passed to the compiler and to the
7540linker.
7541@end table
7542
7543@geindex -i (gnatmake)
7544
7545
7546@table @asis
7547
7548@item @code{-i}
7549
7550In normal mode, @emph{gnatmake} compiles all object files and ALI files
7551into the current directory. If the @emph{-i} switch is used,
7552then instead object files and ALI files that already exist are overwritten
7553in place. This means that once a large project is organized into separate
7554directories in the desired manner, then @emph{gnatmake} will automatically
7555maintain and update this organization. If no ALI files are found on the
7556Ada object path (see @ref{8e,,Search Paths and the Run-Time Library (RTL)}),
7557the new object and ALI files are created in the
7558directory containing the source being compiled. If another organization
7559is desired, where objects and sources are kept in different directories,
7560a useful technique is to create dummy ALI files in the desired directories.
7561When detecting such a dummy file, @emph{gnatmake} will be forced to
7562recompile the corresponding source file, and it will be put the resulting
7563object and ALI files in the directory where it found the dummy file.
7564@end table
7565
7566@geindex -j (gnatmake)
7567
7568@geindex Parallel make
7569
7570
7571@table @asis
7572
7573@item @code{-j@emph{n}}
7574
7575Use @cite{n} processes to carry out the (re)compilations. On a multiprocessor
7576machine compilations will occur in parallel. If @cite{n} is 0, then the
7577maximum number of parallel compilations is the number of core processors
7578on the platform. In the event of compilation errors, messages from various
7579compilations might get interspersed (but @emph{gnatmake} will give you the
7580full ordered list of failing compiles at the end). If this is problematic,
7581rerun the make process with n set to 1 to get a clean list of messages.
7582@end table
7583
7584@geindex -k (gnatmake)
7585
7586
7587@table @asis
7588
7589@item @code{-k}
7590
7591Keep going. Continue as much as possible after a compilation error. To
7592ease the programmer's task in case of compilation errors, the list of
7593sources for which the compile fails is given when @emph{gnatmake}
7594terminates.
7595
7596If @emph{gnatmake} is invoked with several @code{file_names} and with this
7597switch, if there are compilation errors when building an executable,
7598@emph{gnatmake} will not attempt to build the following executables.
7599@end table
7600
7601@geindex -l (gnatmake)
7602
7603
7604@table @asis
7605
7606@item @code{-l}
7607
7608Link only. Can be combined with @emph{-b} to binding
7609and linking. Linking will not be performed if combined with
7610@emph{-c}
7611but not with @emph{-b}.
7612When not combined with @emph{-b}
7613all the units in the closure of the main program must have been previously
7614compiled and must be up to date, and the main program needs to have been bound.
7615The root unit specified by @cite{file_name}
7616may be given without extension, with the source extension or, if no GNAT
7617Project File is specified, with the ALI file extension.
7618@end table
7619
7620@geindex -m (gnatmake)
7621
7622
7623@table @asis
7624
7625@item @code{-m}
7626
7627Specify that the minimum necessary amount of recompilations
7628be performed. In this mode @emph{gnatmake} ignores time
7629stamp differences when the only
7630modifications to a source file consist in adding/removing comments,
7631empty lines, spaces or tabs. This means that if you have changed the
7632comments in a source file or have simply reformatted it, using this
7633switch will tell @emph{gnatmake} not to recompile files that depend on it
7634(provided other sources on which these files depend have undergone no
7635semantic modifications). Note that the debugging information may be
7636out of date with respect to the sources if the @emph{-m} switch causes
7637a compilation to be switched, so the use of this switch represents a
7638trade-off between compilation time and accurate debugging information.
7639@end table
7640
7641@geindex Dependencies
7642@geindex producing list
7643
7644@geindex -M (gnatmake)
7645
7646
7647@table @asis
7648
7649@item @code{-M}
7650
7651Check if all objects are up to date. If they are, output the object
7652dependences to @code{stdout} in a form that can be directly exploited in
7653a @code{Makefile}. By default, each source file is prefixed with its
7654(relative or absolute) directory name. This name is whatever you
7655specified in the various @emph{-aI}
7656and @emph{-I} switches. If you use
7657@cite{gnatmake -M}  @emph{-q}
7658(see below), only the source file names,
7659without relative paths, are output. If you just specify the  @emph{-M}
7660switch, dependencies of the GNAT internal system files are omitted. This
7661is typically what you want. If you also specify
7662the @emph{-a} switch,
7663dependencies of the GNAT internal files are also listed. Note that
7664dependencies of the objects in external Ada libraries (see
7665switch  @code{-aL@emph{dir}} in the following list)
7666are never reported.
7667@end table
7668
7669@geindex -n (gnatmake)
7670
7671
7672@table @asis
7673
7674@item @code{-n}
7675
7676Don't compile, bind, or link. Checks if all objects are up to date.
7677If they are not, the full name of the first file that needs to be
7678recompiled is printed.
7679Repeated use of this option, followed by compiling the indicated source
7680file, will eventually result in recompiling all required units.
7681@end table
7682
7683@geindex -o (gnatmake)
7684
7685
7686@table @asis
7687
7688@item @code{-o @emph{exec_name}}
7689
7690Output executable name. The name of the final executable program will be
7691@cite{exec_name}. If the @emph{-o} switch is omitted the default
7692name for the executable will be the name of the input file in appropriate form
7693for an executable file on the host system.
7694
7695This switch cannot be used when invoking @emph{gnatmake} with several
7696@code{file_names}.
7697@end table
7698
7699@geindex -p (gnatmake)
7700
7701
7702@table @asis
7703
7704@item @code{-p}
7705
7706Same as @code{--create-missing-dirs}
7707@end table
7708
7709@geindex -P (gnatmake)
7710
7711
7712@table @asis
7713
7714@item @code{-P@emph{project}}
7715
7716Use project file @cite{project}. Only one such switch can be used.
7717@ref{e1,,gnatmake and Project Files}.
7718@end table
7719
7720@geindex -q (gnatmake)
7721
7722
7723@table @asis
7724
7725@item @code{-q}
7726
7727Quiet. When this flag is not set, the commands carried out by
7728@emph{gnatmake} are displayed.
7729@end table
7730
7731@geindex -s (gnatmake)
7732
7733
7734@table @asis
7735
7736@item @code{-s}
7737
7738Recompile if compiler switches have changed since last compilation.
7739All compiler switches but -I and -o are taken into account in the
7740following way:
7741orders between different 'first letter' switches are ignored, but
7742orders between same switches are taken into account. For example,
7743@emph{-O -O2} is different than @emph{-O2 -O}, but @emph{-g -O}
7744is equivalent to @emph{-O -g}.
7745
7746This switch is recommended when Integrated Preprocessing is used.
7747@end table
7748
7749@geindex -u (gnatmake)
7750
7751
7752@table @asis
7753
7754@item @code{-u}
7755
7756Unique. Recompile at most the main files. It implies -c. Combined with
7757-f, it is equivalent to calling the compiler directly. Note that using
7758-u with a project file and no main has a special meaning
7759(@ref{e2,,Project Files and Main Subprograms}).
7760@end table
7761
7762@geindex -U (gnatmake)
7763
7764
7765@table @asis
7766
7767@item @code{-U}
7768
7769When used without a project file or with one or several mains on the command
7770line, is equivalent to -u. When used with a project file and no main
7771on the command line, all sources of all project files are checked and compiled
7772if not up to date, and libraries are rebuilt, if necessary.
7773@end table
7774
7775@geindex -v (gnatmake)
7776
7777
7778@table @asis
7779
7780@item @code{-v}
7781
7782Verbose. Display the reason for all recompilations @emph{gnatmake}
7783decides are necessary, with the highest verbosity level.
7784@end table
7785
7786@geindex -vl (gnatmake)
7787
7788
7789@table @asis
7790
7791@item @code{-vl}
7792
7793Verbosity level Low. Display fewer lines than in verbosity Medium.
7794@end table
7795
7796@geindex -vm (gnatmake)
7797
7798
7799@table @asis
7800
7801@item @code{-vm}
7802
7803Verbosity level Medium. Potentially display fewer lines than in verbosity High.
7804@end table
7805
7806@geindex -vm (gnatmake)
7807
7808
7809@table @asis
7810
7811@item @code{-vh}
7812
7813Verbosity level High. Equivalent to -v.
7814
7815@item @code{-vP@emph{x}}
7816
7817Indicate the verbosity of the parsing of GNAT project files.
7818See @ref{e3,,Switches Related to Project Files}.
7819@end table
7820
7821@geindex -x (gnatmake)
7822
7823
7824@table @asis
7825
7826@item @code{-x}
7827
7828Indicate that sources that are not part of any Project File may be compiled.
7829Normally, when using Project Files, only sources that are part of a Project
7830File may be compile. When this switch is used, a source outside of all Project
7831Files may be compiled. The ALI file and the object file will be put in the
7832object directory of the main Project. The compilation switches used will only
7833be those specified on the command line. Even when
7834@emph{-x} is used, mains specified on the
7835command line need to be sources of a project file.
7836
7837@item @code{-X@emph{name}=@emph{value}}
7838
7839Indicate that external variable @cite{name} has the value @cite{value}.
7840The Project Manager will use this value for occurrences of
7841@cite{external(name)} when parsing the project file.
7842@ref{e3,,Switches Related to Project Files}.
7843@end table
7844
7845@geindex -z (gnatmake)
7846
7847
7848@table @asis
7849
7850@item @code{-z}
7851
7852No main subprogram. Bind and link the program even if the unit name
7853given on the command line is a package name. The resulting executable
7854will execute the elaboration routines of the package and its closure,
7855then the finalization routines.
7856@end table
7857
7858@subsubheading GCC switches
7859
7860
7861Any uppercase or multi-character switch that is not a @emph{gnatmake} switch
7862is passed to @emph{gcc} (e.g., @emph{-O}, @emph{-gnato,} etc.)
7863
7864@subsubheading Source and library search path switches
7865
7866
7867@geindex -aI (gnatmake)
7868
7869
7870@table @asis
7871
7872@item @code{-aI@emph{dir}}
7873
7874When looking for source files also look in directory @cite{dir}.
7875The order in which source files search is undertaken is
7876described in @ref{8e,,Search Paths and the Run-Time Library (RTL)}.
7877@end table
7878
7879@geindex -aL (gnatmake)
7880
7881
7882@table @asis
7883
7884@item @code{-aL@emph{dir}}
7885
7886Consider @cite{dir} as being an externally provided Ada library.
7887Instructs @emph{gnatmake} to skip compilation units whose @code{.ALI}
7888files have been located in directory @cite{dir}. This allows you to have
7889missing bodies for the units in @cite{dir} and to ignore out of date bodies
7890for the same units. You still need to specify
7891the location of the specs for these units by using the switches
7892@code{-aI@emph{dir}}  or @code{-I@emph{dir}}.
7893Note: this switch is provided for compatibility with previous versions
7894of @emph{gnatmake}. The easier method of causing standard libraries
7895to be excluded from consideration is to write-protect the corresponding
7896ALI files.
7897@end table
7898
7899@geindex -aO (gnatmake)
7900
7901
7902@table @asis
7903
7904@item @code{-aO@emph{dir}}
7905
7906When searching for library and object files, look in directory
7907@cite{dir}. The order in which library files are searched is described in
7908@ref{91,,Search Paths for gnatbind}.
7909@end table
7910
7911@geindex Search paths
7912@geindex for gnatmake
7913
7914@geindex -A (gnatmake)
7915
7916
7917@table @asis
7918
7919@item @code{-A@emph{dir}}
7920
7921Equivalent to @code{-aL@emph{dir}} @code{-aI@emph{dir}}.
7922
7923@geindex -I (gnatmake)
7924
7925@item @code{-I@emph{dir}}
7926
7927Equivalent to @code{-aO@emph{dir} -aI@emph{dir}}.
7928@end table
7929
7930@geindex -I- (gnatmake)
7931
7932@geindex Source files
7933@geindex suppressing search
7934
7935
7936@table @asis
7937
7938@item @code{-I-}
7939
7940Do not look for source files in the directory containing the source
7941file named in the command line.
7942Do not look for ALI or object files in the directory
7943where @emph{gnatmake} was invoked.
7944@end table
7945
7946@geindex -L (gnatmake)
7947
7948@geindex Linker libraries
7949
7950
7951@table @asis
7952
7953@item @code{-L@emph{dir}}
7954
7955Add directory @cite{dir} to the list of directories in which the linker
7956will search for libraries. This is equivalent to
7957@code{-largs} @code{-L@emph{dir}}.
7958Furthermore, under Windows, the sources pointed to by the libraries path
7959set in the registry are not searched for.
7960@end table
7961
7962@geindex -nostdinc (gnatmake)
7963
7964
7965@table @asis
7966
7967@item @code{-nostdinc}
7968
7969Do not look for source files in the system default directory.
7970@end table
7971
7972@geindex -nostdlib (gnatmake)
7973
7974
7975@table @asis
7976
7977@item @code{-nostdlib}
7978
7979Do not look for library files in the system default directory.
7980@end table
7981
7982@geindex --RTS (gnatmake)
7983
7984
7985@table @asis
7986
7987@item @code{--RTS=@emph{rts-path}}
7988
7989Specifies the default location of the runtime library. GNAT looks for the
7990runtime
7991in the following directories, and stops as soon as a valid runtime is found
7992(@code{adainclude} or @code{ada_source_path}, and @code{adalib} or
7993@code{ada_object_path} present):
7994
7995
7996@itemize *
7997
7998@item 
7999@emph{<current directory>/$rts_path}
8000
8001@item 
8002@emph{<default-search-dir>/$rts_path}
8003
8004@item 
8005@emph{<default-search-dir>/rts-$rts_path}
8006
8007@item 
8008The selected path is handled like a normal RTS path.
8009@end itemize
8010@end table
8011
8012@node Mode Switches for gnatmake,Notes on the Command Line,Switches for gnatmake,Building with gnatmake
8013@anchor{gnat_ugn/building_executable_programs_with_gnat id4}@anchor{e4}@anchor{gnat_ugn/building_executable_programs_with_gnat mode-switches-for-gnatmake}@anchor{e5}
8014@subsection Mode Switches for @emph{gnatmake}
8015
8016
8017The mode switches (referred to as @cite{mode_switches}) allow the
8018inclusion of switches that are to be passed to the compiler itself, the
8019binder or the linker. The effect of a mode switch is to cause all
8020subsequent switches up to the end of the switch list, or up to the next
8021mode switch, to be interpreted as switches to be passed on to the
8022designated component of GNAT.
8023
8024@geindex -cargs (gnatmake)
8025
8026
8027@table @asis
8028
8029@item @code{-cargs @emph{switches}}
8030
8031Compiler switches. Here @cite{switches} is a list of switches
8032that are valid switches for @emph{gcc}. They will be passed on to
8033all compile steps performed by @emph{gnatmake}.
8034@end table
8035
8036@geindex -bargs (gnatmake)
8037
8038
8039@table @asis
8040
8041@item @code{-bargs @emph{switches}}
8042
8043Binder switches. Here @cite{switches} is a list of switches
8044that are valid switches for @cite{gnatbind}. They will be passed on to
8045all bind steps performed by @emph{gnatmake}.
8046@end table
8047
8048@geindex -largs (gnatmake)
8049
8050
8051@table @asis
8052
8053@item @code{-largs @emph{switches}}
8054
8055Linker switches. Here @cite{switches} is a list of switches
8056that are valid switches for @emph{gnatlink}. They will be passed on to
8057all link steps performed by @emph{gnatmake}.
8058@end table
8059
8060@geindex -margs (gnatmake)
8061
8062
8063@table @asis
8064
8065@item @code{-margs @emph{switches}}
8066
8067Make switches. The switches are directly interpreted by @emph{gnatmake},
8068regardless of any previous occurrence of @emph{-cargs}, @emph{-bargs}
8069or @emph{-largs}.
8070@end table
8071
8072@node Notes on the Command Line,How gnatmake Works,Mode Switches for gnatmake,Building with gnatmake
8073@anchor{gnat_ugn/building_executable_programs_with_gnat id5}@anchor{e6}@anchor{gnat_ugn/building_executable_programs_with_gnat notes-on-the-command-line}@anchor{e7}
8074@subsection Notes on the Command Line
8075
8076
8077This section contains some additional useful notes on the operation
8078of the @emph{gnatmake} command.
8079
8080@geindex Recompilation (by gnatmake)
8081
8082
8083@itemize *
8084
8085@item 
8086If @emph{gnatmake} finds no ALI files, it recompiles the main program
8087and all other units required by the main program.
8088This means that @emph{gnatmake}
8089can be used for the initial compile, as well as during subsequent steps of
8090the development cycle.
8091
8092@item 
8093If you enter @code{gnatmake foo.adb}, where @code{foo}
8094is a subunit or body of a generic unit, @emph{gnatmake} recompiles
8095@code{foo.adb} (because it finds no ALI) and stops, issuing a
8096warning.
8097
8098@item 
8099In @emph{gnatmake} the switch @emph{-I}
8100is used to specify both source and
8101library file paths. Use @emph{-aI}
8102instead if you just want to specify
8103source paths only and @emph{-aO}
8104if you want to specify library paths
8105only.
8106
8107@item 
8108@emph{gnatmake} will ignore any files whose ALI file is write-protected.
8109This may conveniently be used to exclude standard libraries from
8110consideration and in particular it means that the use of the
8111@emph{-f} switch will not recompile these files
8112unless @emph{-a} is also specified.
8113
8114@item 
8115@emph{gnatmake} has been designed to make the use of Ada libraries
8116particularly convenient. Assume you have an Ada library organized
8117as follows: @emph{obj-dir} contains the objects and ALI files for
8118of your Ada compilation units,
8119whereas @emph{include-dir} contains the
8120specs of these units, but no bodies. Then to compile a unit
8121stored in @cite{main.adb}, which uses this Ada library you would just type:
8122
8123@example
8124$ gnatmake -aI`include-dir`  -aL`obj-dir`  main
8125@end example
8126
8127@item 
8128Using @emph{gnatmake} along with the @emph{-m (minimal recompilation)}
8129switch provides a mechanism for avoiding unnecessary recompilations. Using
8130this switch,
8131you can update the comments/format of your
8132source files without having to recompile everything. Note, however, that
8133adding or deleting lines in a source files may render its debugging
8134info obsolete. If the file in question is a spec, the impact is rather
8135limited, as that debugging info will only be useful during the
8136elaboration phase of your program. For bodies the impact can be more
8137significant. In all events, your debugger will warn you if a source file
8138is more recent than the corresponding object, and alert you to the fact
8139that the debugging information may be out of date.
8140@end itemize
8141
8142@node How gnatmake Works,Examples of gnatmake Usage,Notes on the Command Line,Building with gnatmake
8143@anchor{gnat_ugn/building_executable_programs_with_gnat id6}@anchor{e8}@anchor{gnat_ugn/building_executable_programs_with_gnat how-gnatmake-works}@anchor{e9}
8144@subsection How @emph{gnatmake} Works
8145
8146
8147Generally @emph{gnatmake} automatically performs all necessary
8148recompilations and you don't need to worry about how it works. However,
8149it may be useful to have some basic understanding of the @emph{gnatmake}
8150approach and in particular to understand how it uses the results of
8151previous compilations without incorrectly depending on them.
8152
8153First a definition: an object file is considered @emph{up to date} if the
8154corresponding ALI file exists and if all the source files listed in the
8155dependency section of this ALI file have time stamps matching those in
8156the ALI file. This means that neither the source file itself nor any
8157files that it depends on have been modified, and hence there is no need
8158to recompile this file.
8159
8160@emph{gnatmake} works by first checking if the specified main unit is up
8161to date. If so, no compilations are required for the main unit. If not,
8162@emph{gnatmake} compiles the main program to build a new ALI file that
8163reflects the latest sources. Then the ALI file of the main unit is
8164examined to find all the source files on which the main program depends,
8165and @emph{gnatmake} recursively applies the above procedure on all these
8166files.
8167
8168This process ensures that @emph{gnatmake} only trusts the dependencies
8169in an existing ALI file if they are known to be correct. Otherwise it
8170always recompiles to determine a new, guaranteed accurate set of
8171dependencies. As a result the program is compiled 'upside down' from what may
8172be more familiar as the required order of compilation in some other Ada
8173systems. In particular, clients are compiled before the units on which
8174they depend. The ability of GNAT to compile in any order is critical in
8175allowing an order of compilation to be chosen that guarantees that
8176@emph{gnatmake} will recompute a correct set of new dependencies if
8177necessary.
8178
8179When invoking @emph{gnatmake} with several @cite{file_names}, if a unit is
8180imported by several of the executables, it will be recompiled at most once.
8181
8182Note: when using non-standard naming conventions
8183(@ref{37,,Using Other File Names}), changing through a configuration pragmas
8184file the version of a source and invoking @emph{gnatmake} to recompile may
8185have no effect, if the previous version of the source is still accessible
8186by @emph{gnatmake}. It may be necessary to use the switch
8187-f.
8188
8189@node Examples of gnatmake Usage,,How gnatmake Works,Building with gnatmake
8190@anchor{gnat_ugn/building_executable_programs_with_gnat examples-of-gnatmake-usage}@anchor{ea}@anchor{gnat_ugn/building_executable_programs_with_gnat id7}@anchor{eb}
8191@subsection Examples of @emph{gnatmake} Usage
8192
8193
8194
8195@table @asis
8196
8197@item @emph{gnatmake hello.adb}
8198
8199Compile all files necessary to bind and link the main program
8200@code{hello.adb} (containing unit @cite{Hello}) and bind and link the
8201resulting object files to generate an executable file @code{hello}.
8202
8203@item @emph{gnatmake main1 main2 main3}
8204
8205Compile all files necessary to bind and link the main programs
8206@code{main1.adb} (containing unit @cite{Main1}), @code{main2.adb}
8207(containing unit @cite{Main2}) and @code{main3.adb}
8208(containing unit @cite{Main3}) and bind and link the resulting object files
8209to generate three executable files @code{main1},
8210@code{main2}  and @code{main3}.
8211
8212@item @emph{gnatmake -q Main_Unit -cargs -O2 -bargs -l}
8213
8214Compile all files necessary to bind and link the main program unit
8215@cite{Main_Unit} (from file @code{main_unit.adb}). All compilations will
8216be done with optimization level 2 and the order of elaboration will be
8217listed by the binder. @emph{gnatmake} will operate in quiet mode, not
8218displaying commands it is executing.
8219@end table
8220
8221@node Compiling with gcc,Compiler Switches,Building with gnatmake,Building Executable Programs with GNAT
8222@anchor{gnat_ugn/building_executable_programs_with_gnat compiling-with-gcc}@anchor{1e}@anchor{gnat_ugn/building_executable_programs_with_gnat id8}@anchor{ec}
8223@section Compiling with @emph{gcc}
8224
8225
8226This section discusses how to compile Ada programs using the @emph{gcc}
8227command. It also describes the set of switches
8228that can be used to control the behavior of the compiler.
8229
8230@menu
8231* Compiling Programs:: 
8232* Search Paths and the Run-Time Library (RTL): Search Paths and the Run-Time Library RTL. 
8233* Order of Compilation Issues:: 
8234* Examples:: 
8235
8236@end menu
8237
8238@node Compiling Programs,Search Paths and the Run-Time Library RTL,,Compiling with gcc
8239@anchor{gnat_ugn/building_executable_programs_with_gnat compiling-programs}@anchor{ed}@anchor{gnat_ugn/building_executable_programs_with_gnat id9}@anchor{ee}
8240@subsection Compiling Programs
8241
8242
8243The first step in creating an executable program is to compile the units
8244of the program using the @emph{gcc} command. You must compile the
8245following files:
8246
8247
8248@itemize *
8249
8250@item 
8251the body file (@code{.adb}) for a library level subprogram or generic
8252subprogram
8253
8254@item 
8255the spec file (@code{.ads}) for a library level package or generic
8256package that has no body
8257
8258@item 
8259the body file (@code{.adb}) for a library level package
8260or generic package that has a body
8261@end itemize
8262
8263You need @emph{not} compile the following files
8264
8265
8266@itemize *
8267
8268@item 
8269the spec of a library unit which has a body
8270
8271@item 
8272subunits
8273@end itemize
8274
8275because they are compiled as part of compiling related units. GNAT
8276package specs
8277when the corresponding body is compiled, and subunits when the parent is
8278compiled.
8279
8280@geindex cannot generate code
8281
8282If you attempt to compile any of these files, you will get one of the
8283following error messages (where @cite{fff} is the name of the file you
8284compiled):
8285
8286@quotation
8287
8288@example
8289cannot generate code for file `fff` (package spec)
8290to check package spec, use -gnatc
8291
8292cannot generate code for file `fff` (missing subunits)
8293to check parent unit, use -gnatc
8294
8295cannot generate code for file `fff` (subprogram spec)
8296to check subprogram spec, use -gnatc
8297
8298cannot generate code for file `fff` (subunit)
8299to check subunit, use -gnatc
8300@end example
8301@end quotation
8302
8303As indicated by the above error messages, if you want to submit
8304one of these files to the compiler to check for correct semantics
8305without generating code, then use the @emph{-gnatc} switch.
8306
8307The basic command for compiling a file containing an Ada unit is:
8308
8309@example
8310$ gcc -c [switches] <file name>
8311@end example
8312
8313where @cite{file name} is the name of the Ada file (usually
8314having an extension @code{.ads} for a spec or @code{.adb} for a body).
8315You specify the
8316@code{-c} switch to tell @emph{gcc} to compile, but not link, the file.
8317The result of a successful compilation is an object file, which has the
8318same name as the source file but an extension of @code{.o} and an Ada
8319Library Information (ALI) file, which also has the same name as the
8320source file, but with @code{.ali} as the extension. GNAT creates these
8321two output files in the current directory, but you may specify a source
8322file in any directory using an absolute or relative path specification
8323containing the directory information.
8324
8325@geindex gnat1
8326
8327@emph{gcc} is actually a driver program that looks at the extensions of
8328the file arguments and loads the appropriate compiler. For example, the
8329GNU C compiler is @code{cc1}, and the Ada compiler is @code{gnat1}.
8330These programs are in directories known to the driver program (in some
8331configurations via environment variables you set), but need not be in
8332your path. The @emph{gcc} driver also calls the assembler and any other
8333utilities needed to complete the generation of the required object
8334files.
8335
8336It is possible to supply several file names on the same @emph{gcc}
8337command. This causes @emph{gcc} to call the appropriate compiler for
8338each file. For example, the following command lists two separate
8339files to be compiled:
8340
8341@example
8342$ gcc -c x.adb y.adb
8343@end example
8344
8345calls @cite{gnat1} (the Ada compiler) twice to compile @code{x.adb} and
8346@code{y.adb}.
8347The compiler generates two object files @code{x.o} and @code{y.o}
8348and the two ALI files @code{x.ali} and @code{y.ali}.
8349
8350Any switches apply to all the files listed, see @ref{ef,,Compiler Switches} for a
8351list of available @emph{gcc} switches.
8352
8353@node Search Paths and the Run-Time Library RTL,Order of Compilation Issues,Compiling Programs,Compiling with gcc
8354@anchor{gnat_ugn/building_executable_programs_with_gnat id10}@anchor{f0}@anchor{gnat_ugn/building_executable_programs_with_gnat search-paths-and-the-run-time-library-rtl}@anchor{8e}
8355@subsection Search Paths and the Run-Time Library (RTL)
8356
8357
8358With the GNAT source-based library system, the compiler must be able to
8359find source files for units that are needed by the unit being compiled.
8360Search paths are used to guide this process.
8361
8362The compiler compiles one source file whose name must be given
8363explicitly on the command line. In other words, no searching is done
8364for this file. To find all other source files that are needed (the most
8365common being the specs of units), the compiler examines the following
8366directories, in the following order:
8367
8368
8369@itemize *
8370
8371@item 
8372The directory containing the source file of the main unit being compiled
8373(the file name on the command line).
8374
8375@item 
8376Each directory named by an @emph{-I} switch given on the @emph{gcc}
8377command line, in the order given.
8378
8379@geindex ADA_PRJ_INCLUDE_FILE
8380
8381@item 
8382Each of the directories listed in the text file whose name is given
8383by the 
8384@geindex ADA_PRJ_INCLUDE_FILE
8385@geindex environment variable; ADA_PRJ_INCLUDE_FILE
8386@code{ADA_PRJ_INCLUDE_FILE} environment variable.
8387@geindex ADA_PRJ_INCLUDE_FILE
8388@geindex environment variable; ADA_PRJ_INCLUDE_FILE
8389@code{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the gnat
8390driver when project files are used. It should not normally be set
8391by other means.
8392
8393@geindex ADA_INCLUDE_PATH
8394
8395@item 
8396Each of the directories listed in the value of the
8397@geindex ADA_INCLUDE_PATH
8398@geindex environment variable; ADA_INCLUDE_PATH
8399@code{ADA_INCLUDE_PATH} environment variable.
8400Construct this value
8401exactly as the 
8402@geindex PATH
8403@geindex environment variable; PATH
8404@code{PATH} environment variable: a list of directory
8405names separated by colons (semicolons when working with the NT version).
8406
8407@item 
8408The content of the @code{ada_source_path} file which is part of the GNAT
8409installation tree and is used to store standard libraries such as the
8410GNAT Run Time Library (RTL) source files.
8411@ref{8b,,Installing a library}
8412@end itemize
8413
8414Specifying the switch @emph{-I-}
8415inhibits the use of the directory
8416containing the source file named in the command line. You can still
8417have this directory on your search path, but in this case it must be
8418explicitly requested with a @emph{-I} switch.
8419
8420Specifying the switch @emph{-nostdinc}
8421inhibits the search of the default location for the GNAT Run Time
8422Library (RTL) source files.
8423
8424The compiler outputs its object files and ALI files in the current
8425working directory.
8426Caution: The object file can be redirected with the @emph{-o} switch;
8427however, @emph{gcc} and @cite{gnat1} have not been coordinated on this
8428so the @code{ALI} file will not go to the right place. Therefore, you should
8429avoid using the @emph{-o} switch.
8430
8431@geindex System.IO
8432
8433The packages @cite{Ada}, @cite{System}, and @cite{Interfaces} and their
8434children make up the GNAT RTL, together with the simple @cite{System.IO}
8435package used in the @cite{"Hello World"} example. The sources for these units
8436are needed by the compiler and are kept together in one directory. Not
8437all of the bodies are needed, but all of the sources are kept together
8438anyway. In a normal installation, you need not specify these directory
8439names when compiling or binding. Either the environment variables or
8440the built-in defaults cause these files to be found.
8441
8442In addition to the language-defined hierarchies (@cite{System}, @cite{Ada} and
8443@cite{Interfaces}), the GNAT distribution provides a fourth hierarchy,
8444consisting of child units of @cite{GNAT}. This is a collection of generally
8445useful types, subprograms, etc. See the @cite{GNAT_Reference_Manual}
8446for further details.
8447
8448Besides simplifying access to the RTL, a major use of search paths is
8449in compiling sources from multiple directories. This can make
8450development environments much more flexible.
8451
8452@node Order of Compilation Issues,Examples,Search Paths and the Run-Time Library RTL,Compiling with gcc
8453@anchor{gnat_ugn/building_executable_programs_with_gnat id11}@anchor{f1}@anchor{gnat_ugn/building_executable_programs_with_gnat order-of-compilation-issues}@anchor{f2}
8454@subsection Order of Compilation Issues
8455
8456
8457If, in our earlier example, there was a spec for the @cite{hello}
8458procedure, it would be contained in the file @code{hello.ads}; yet this
8459file would not have to be explicitly compiled. This is the result of the
8460model we chose to implement library management. Some of the consequences
8461of this model are as follows:
8462
8463
8464@itemize *
8465
8466@item 
8467There is no point in compiling specs (except for package
8468specs with no bodies) because these are compiled as needed by clients. If
8469you attempt a useless compilation, you will receive an error message.
8470It is also useless to compile subunits because they are compiled as needed
8471by the parent.
8472
8473@item 
8474There are no order of compilation requirements: performing a
8475compilation never obsoletes anything. The only way you can obsolete
8476something and require recompilations is to modify one of the
8477source files on which it depends.
8478
8479@item 
8480There is no library as such, apart from the ALI files
8481(@ref{44,,The Ada Library Information Files}, for information on the format
8482of these files). For now we find it convenient to create separate ALI files,
8483but eventually the information therein may be incorporated into the object
8484file directly.
8485
8486@item 
8487When you compile a unit, the source files for the specs of all units
8488that it @emph{with}s, all its subunits, and the bodies of any generics it
8489instantiates must be available (reachable by the search-paths mechanism
8490described above), or you will receive a fatal error message.
8491@end itemize
8492
8493@node Examples,,Order of Compilation Issues,Compiling with gcc
8494@anchor{gnat_ugn/building_executable_programs_with_gnat id12}@anchor{f3}@anchor{gnat_ugn/building_executable_programs_with_gnat examples}@anchor{f4}
8495@subsection Examples
8496
8497
8498The following are some typical Ada compilation command line examples:
8499
8500@example
8501$ gcc -c xyz.adb
8502@end example
8503
8504Compile body in file @code{xyz.adb} with all default options.
8505
8506@example
8507$ gcc -c -O2 -gnata xyz-def.adb
8508@end example
8509
8510Compile the child unit package in file @code{xyz-def.adb} with extensive
8511optimizations, and pragma @cite{Assert}/@cite{Debug} statements
8512enabled.
8513
8514@example
8515$ gcc -c -gnatc abc-def.adb
8516@end example
8517
8518Compile the subunit in file @code{abc-def.adb} in semantic-checking-only
8519mode.
8520
8521@node Compiler Switches,Binding with gnatbind,Compiling with gcc,Building Executable Programs with GNAT
8522@anchor{gnat_ugn/building_executable_programs_with_gnat compiler-switches}@anchor{f5}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gcc}@anchor{ef}
8523@section Compiler Switches
8524
8525
8526The @emph{gcc} command accepts switches that control the
8527compilation process. These switches are fully described in this section:
8528first an alphabetical listing of all switches with a brief description,
8529and then functionally grouped sets of switches with more detailed
8530information.
8531
8532More switches exist for GCC than those documented here, especially
8533for specific targets. However, their use is not recommended as
8534they may change code generation in ways that are incompatible with
8535the Ada run-time library, or can cause inconsistencies between
8536compilation units.
8537
8538@menu
8539* Alphabetical List of All Switches:: 
8540* Output and Error Message Control:: 
8541* Warning Message Control:: 
8542* Debugging and Assertion Control:: 
8543* Validity Checking:: 
8544* Style Checking:: 
8545* Run-Time Checks:: 
8546* Using gcc for Syntax Checking:: 
8547* Using gcc for Semantic Checking:: 
8548* Compiling Different Versions of Ada:: 
8549* Character Set Control:: 
8550* File Naming Control:: 
8551* Subprogram Inlining Control:: 
8552* Auxiliary Output Control:: 
8553* Debugging Control:: 
8554* Exception Handling Control:: 
8555* Units to Sources Mapping Files:: 
8556* Code Generation Control:: 
8557
8558@end menu
8559
8560@node Alphabetical List of All Switches,Output and Error Message Control,,Compiler Switches
8561@anchor{gnat_ugn/building_executable_programs_with_gnat id13}@anchor{f6}@anchor{gnat_ugn/building_executable_programs_with_gnat alphabetical-list-of-all-switches}@anchor{f7}
8562@subsection Alphabetical List of All Switches
8563
8564
8565@geindex -b (gcc)
8566
8567
8568@table @asis
8569
8570@item @code{-b @emph{target}}
8571
8572Compile your program to run on @cite{target}, which is the name of a
8573system configuration. You must have a GNAT cross-compiler built if
8574@cite{target} is not the same as your host system.
8575@end table
8576
8577@geindex -B (gcc)
8578
8579
8580@table @asis
8581
8582@item @code{-B@emph{dir}}
8583
8584Load compiler executables (for example, @cite{gnat1}, the Ada compiler)
8585from @cite{dir} instead of the default location. Only use this switch
8586when multiple versions of the GNAT compiler are available.
8587See the "Options for Directory Search" section in the
8588@cite{Using the GNU Compiler Collection (GCC)} manual for further details.
8589You would normally use the @emph{-b} or @emph{-V} switch instead.
8590@end table
8591
8592@geindex -c (gcc)
8593
8594
8595@table @asis
8596
8597@item @code{-c}
8598
8599Compile. Always use this switch when compiling Ada programs.
8600
8601Note: for some other languages when using @emph{gcc}, notably in
8602the case of C and C++, it is possible to use
8603use @emph{gcc} without a @emph{-c} switch to
8604compile and link in one step. In the case of GNAT, you
8605cannot use this approach, because the binder must be run
8606and @emph{gcc} cannot be used to run the GNAT binder.
8607@end table
8608
8609@geindex -fcallgraph-info (gcc)
8610
8611
8612@table @asis
8613
8614@item @code{-fcallgraph-info[=su,da]}
8615
8616Makes the compiler output callgraph information for the program, on a
8617per-file basis. The information is generated in the VCG format.  It can
8618be decorated with additional, per-node and/or per-edge information, if a
8619list of comma-separated markers is additionally specified. When the
8620@cite{su} marker is specified, the callgraph is decorated with stack usage
8621information; it is equivalent to @emph{-fstack-usage}. When the @cite{da}
8622marker is specified, the callgraph is decorated with information about
8623dynamically allocated objects.
8624@end table
8625
8626@geindex -fdump-scos (gcc)
8627
8628
8629@table @asis
8630
8631@item @code{-fdump-scos}
8632
8633Generates SCO (Source Coverage Obligation) information in the ALI file.
8634This information is used by advanced coverage tools. See unit @code{SCOs}
8635in the compiler sources for details in files @code{scos.ads} and
8636@code{scos.adb}.
8637@end table
8638
8639@geindex -fdump-xref (gcc)
8640
8641
8642@table @asis
8643
8644@item @code{-fdump-xref}
8645
8646Generates cross reference information in GLI files for C and C++ sources.
8647The GLI files have the same syntax as the ALI files for Ada, and can be used
8648for source navigation in IDEs and on the command line using e.g. gnatxref
8649and the @emph{--ext=gli} switch.
8650@end table
8651
8652@geindex -flto (gcc)
8653
8654
8655@table @asis
8656
8657@item @code{-flto[=@emph{n}]}
8658
8659Enables Link Time Optimization. This switch must be used in conjunction
8660with the traditional @emph{-Ox} switches and instructs the compiler to
8661defer most optimizations until the link stage. The advantage of this
8662approach is that the compiler can do a whole-program analysis and choose
8663the best interprocedural optimization strategy based on a complete view
8664of the program, instead of a fragmentary view with the usual approach.
8665This can also speed up the compilation of big programs and reduce the
8666size of the executable, compared with a traditional per-unit compilation
8667with inlining across modules enabled by the @emph{-gnatn} switch.
8668The drawback of this approach is that it may require more memory and that
8669the debugging information generated by -g with it might be hardly usable.
8670The switch, as well as the accompanying @emph{-Ox} switches, must be
8671specified both for the compilation and the link phases.
8672If the @cite{n} parameter is specified, the optimization and final code
8673generation at link time are executed using @cite{n} parallel jobs by
8674means of an installed @emph{make} program.
8675@end table
8676
8677@geindex -fno-inline (gcc)
8678
8679
8680@table @asis
8681
8682@item @code{-fno-inline}
8683
8684Suppresses all inlining, unless requested with pragma @cite{Inline_Always}. The
8685effect is enforced regardless of other optimization or inlining switches.
8686Note that inlining can also be suppressed on a finer-grained basis with
8687pragma @cite{No_Inline}.
8688@end table
8689
8690@geindex -fno-inline-functions (gcc)
8691
8692
8693@table @asis
8694
8695@item @code{-fno-inline-functions}
8696
8697Suppresses automatic inlining of subprograms, which is enabled
8698if @emph{-O3} is used.
8699@end table
8700
8701@geindex -fno-inline-small-functions (gcc)
8702
8703
8704@table @asis
8705
8706@item @code{-fno-inline-small-functions}
8707
8708Suppresses automatic inlining of small subprograms, which is enabled
8709if @emph{-O2} is used.
8710@end table
8711
8712@geindex -fno-inline-functions-called-once (gcc)
8713
8714
8715@table @asis
8716
8717@item @code{-fno-inline-functions-called-once}
8718
8719Suppresses inlining of subprograms local to the unit and called once
8720from within it, which is enabled if @emph{-O1} is used.
8721@end table
8722
8723@geindex -fno-ivopts (gcc)
8724
8725
8726@table @asis
8727
8728@item @code{-fno-ivopts}
8729
8730Suppresses high-level loop induction variable optimizations, which are
8731enabled if @emph{-O1} is used. These optimizations are generally
8732profitable but, for some specific cases of loops with numerous uses
8733of the iteration variable that follow a common pattern, they may end
8734up destroying the regularity that could be exploited at a lower level
8735and thus producing inferior code.
8736@end table
8737
8738@geindex -fno-strict-aliasing (gcc)
8739
8740
8741@table @asis
8742
8743@item @code{-fno-strict-aliasing}
8744
8745Causes the compiler to avoid assumptions regarding non-aliasing
8746of objects of different types. See
8747@ref{f8,,Optimization and Strict Aliasing} for details.
8748@end table
8749
8750@geindex -fstack-check (gcc)
8751
8752
8753@table @asis
8754
8755@item @code{-fstack-check}
8756
8757Activates stack checking.
8758See @ref{f9,,Stack Overflow Checking} for details.
8759@end table
8760
8761@geindex -fstack-usage (gcc)
8762
8763
8764@table @asis
8765
8766@item @code{-fstack-usage}
8767
8768Makes the compiler output stack usage information for the program, on a
8769per-subprogram basis. See @ref{fa,,Static Stack Usage Analysis} for details.
8770@end table
8771
8772@geindex -g (gcc)
8773
8774
8775@table @asis
8776
8777@item @code{-g}
8778
8779Generate debugging information. This information is stored in the object
8780file and copied from there to the final executable file by the linker,
8781where it can be read by the debugger. You must use the
8782@emph{-g} switch if you plan on using the debugger.
8783@end table
8784
8785@geindex -gnat05 (gcc)
8786
8787
8788@table @asis
8789
8790@item @code{-gnat05}
8791
8792Allow full Ada 2005 features.
8793@end table
8794
8795@geindex -gnat12 (gcc)
8796
8797
8798@table @asis
8799
8800@item @code{-gnat12}
8801
8802Allow full Ada 2012 features.
8803@end table
8804
8805@geindex -gnat83 (gcc)
8806
8807@geindex -gnat2005 (gcc)
8808
8809
8810@table @asis
8811
8812@item @code{-gnat2005}
8813
8814Allow full Ada 2005 features (same as @emph{-gnat05})
8815@end table
8816
8817@geindex -gnat2012 (gcc)
8818
8819
8820@table @asis
8821
8822@item @code{-gnat2012}
8823
8824Allow full Ada 2012 features (same as @emph{-gnat12})
8825
8826@item @code{-gnat83}
8827
8828Enforce Ada 83 restrictions.
8829@end table
8830
8831@geindex -gnat95 (gcc)
8832
8833
8834@table @asis
8835
8836@item @code{-gnat95}
8837
8838Enforce Ada 95 restrictions.
8839
8840Note: for compatibility with some Ada 95 compilers which support only
8841the @cite{overriding} keyword of Ada 2005, the @emph{-gnatd.D} switch can
8842be used along with @emph{-gnat95} to achieve a similar effect with GNAT.
8843
8844@emph{-gnatd.D} instructs GNAT to consider @cite{overriding} as a keyword
8845and handle its associated semantic checks, even in Ada 95 mode.
8846@end table
8847
8848@geindex -gnata (gcc)
8849
8850
8851@table @asis
8852
8853@item @code{-gnata}
8854
8855Assertions enabled. @cite{Pragma Assert} and @cite{pragma Debug} to be
8856activated. Note that these pragmas can also be controlled using the
8857configuration pragmas @cite{Assertion_Policy} and @cite{Debug_Policy}.
8858It also activates pragmas @cite{Check}, @cite{Precondition}, and
8859@cite{Postcondition}. Note that these pragmas can also be controlled
8860using the configuration pragma @cite{Check_Policy}. In Ada 2012, it
8861also activates all assertions defined in the RM as aspects: preconditions,
8862postconditions, type invariants and (sub)type predicates. In all Ada modes,
8863corresponding pragmas for type invariants and (sub)type predicates are
8864also activated. The default is that all these assertions are disabled,
8865and have no effect, other than being checked for syntactic validity, and
8866in the case of subtype predicates, constructions such as membership tests
8867still test predicates even if assertions are turned off.
8868@end table
8869
8870@geindex -gnatA (gcc)
8871
8872
8873@table @asis
8874
8875@item @code{-gnatA}
8876
8877Avoid processing @code{gnat.adc}. If a @code{gnat.adc} file is present,
8878it will be ignored.
8879@end table
8880
8881@geindex -gnatb (gcc)
8882
8883
8884@table @asis
8885
8886@item @code{-gnatb}
8887
8888Generate brief messages to @code{stderr} even if verbose mode set.
8889@end table
8890
8891@geindex -gnatB (gcc)
8892
8893
8894@table @asis
8895
8896@item @code{-gnatB}
8897
8898Assume no invalid (bad) values except for 'Valid attribute use
8899(@ref{fb,,Validity Checking}).
8900@end table
8901
8902@geindex -gnatc (gcc)
8903
8904
8905@table @asis
8906
8907@item @code{-gnatc}
8908
8909Check syntax and semantics only (no code generation attempted). When the
8910compiler is invoked by @emph{gnatmake}, if the switch @emph{-gnatc} is
8911only given to the compiler (after @emph{-cargs} or in package Compiler of
8912the project file, @emph{gnatmake} will fail because it will not find the
8913object file after compilation. If @emph{gnatmake} is called with
8914@emph{-gnatc} as a builder switch (before @emph{-cargs} or in package
8915Builder of the project file) then @emph{gnatmake} will not fail because
8916it will not look for the object files after compilation, and it will not try
8917to build and link. This switch may not be given if a previous @cite{-gnatR}
8918switch has been given, since @cite{-gnatR} requires that the code generator
8919be called to complete determination of representation information.
8920@end table
8921
8922@geindex -gnatC (gcc)
8923
8924
8925@table @asis
8926
8927@item @code{-gnatC}
8928
8929Generate CodePeer intermediate format (no code generation attempted).
8930This switch will generate an intermediate representation suitable for
8931use by CodePeer (@code{.scil} files). This switch is not compatible with
8932code generation (it will, among other things, disable some switches such
8933as -gnatn, and enable others such as -gnata).
8934@end table
8935
8936@geindex -gnatd (gcc)
8937
8938
8939@table @asis
8940
8941@item @code{-gnatd}
8942
8943Specify debug options for the compiler. The string of characters after
8944the @emph{-gnatd} specify the specific debug options. The possible
8945characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
8946compiler source file @code{debug.adb} for details of the implemented
8947debug options. Certain debug options are relevant to applications
8948programmers, and these are documented at appropriate points in this
8949users guide.
8950@end table
8951
8952@geindex -gnatD[nn] (gcc)
8953
8954
8955@table @asis
8956
8957@item @code{-gnatD}
8958
8959Create expanded source files for source level debugging. This switch
8960also suppress generation of cross-reference information
8961(see @emph{-gnatx}). Note that this switch is not allowed if a previous
8962-gnatR switch has been given, since these two switches are not compatible.
8963@end table
8964
8965@geindex -gnateA (gcc)
8966
8967
8968@table @asis
8969
8970@item @code{-gnateA}
8971
8972Check that the actual parameters of a subprogram call are not aliases of one
8973another. To qualify as aliasing, the actuals must denote objects of a composite
8974type, their memory locations must be identical or overlapping, and at least one
8975of the corresponding formal parameters must be of mode OUT or IN OUT.
8976
8977@example
8978type Rec_Typ is record
8979   Data : Integer := 0;
8980end record;
8981
8982function Self (Val : Rec_Typ) return Rec_Typ is
8983begin
8984   return Val;
8985end Self;
8986
8987procedure Detect_Aliasing (Val_1 : in out Rec_Typ; Val_2 : Rec_Typ) is
8988begin
8989   null;
8990end Detect_Aliasing;
8991
8992Obj : Rec_Typ;
8993
8994Detect_Aliasing (Obj, Obj);
8995Detect_Aliasing (Obj, Self (Obj));
8996@end example
8997
8998In the example above, the first call to @cite{Detect_Aliasing} fails with a
8999@cite{Program_Error} at runtime because the actuals for @cite{Val_1} and
9000@cite{Val_2} denote the same object. The second call executes without raising
9001an exception because @cite{Self(Obj)} produces an anonymous object which does
9002not share the memory location of @cite{Obj}.
9003@end table
9004
9005@geindex -gnatec (gcc)
9006
9007
9008@table @asis
9009
9010@item @code{-gnatec=@emph{path}}
9011
9012Specify a configuration pragma file
9013(the equal sign is optional)
9014(@ref{7b,,The Configuration Pragmas Files}).
9015@end table
9016
9017@geindex -gnateC (gcc)
9018
9019
9020@table @asis
9021
9022@item @code{-gnateC}
9023
9024Generate CodePeer messages in a compiler-like format. This switch is only
9025effective if @emph{-gnatcC} is also specified and requires an installation
9026of CodePeer.
9027@end table
9028
9029@geindex -gnated (gcc)
9030
9031
9032@table @asis
9033
9034@item @code{-gnated}
9035
9036Disable atomic synchronization
9037@end table
9038
9039@geindex -gnateD (gcc)
9040
9041
9042@table @asis
9043
9044@item @code{-gnateDsymbol[=@emph{value}]}
9045
9046Defines a symbol, associated with @cite{value}, for preprocessing.
9047(@ref{1a,,Integrated Preprocessing}).
9048@end table
9049
9050@geindex -gnateE (gcc)
9051
9052
9053@table @asis
9054
9055@item @code{-gnateE}
9056
9057Generate extra information in exception messages. In particular, display
9058extra column information and the value and range associated with index and
9059range check failures, and extra column information for access checks.
9060In cases where the compiler is able to determine at compile time that
9061a check will fail, it gives a warning, and the extra information is not
9062produced at run time.
9063@end table
9064
9065@geindex -gnatef (gcc)
9066
9067
9068@table @asis
9069
9070@item @code{-gnatef}
9071
9072Display full source path name in brief error messages.
9073@end table
9074
9075@geindex -gnateF (gcc)
9076
9077
9078@table @asis
9079
9080@item @code{-gnateF}
9081
9082Check for overflow on all floating-point operations, including those
9083for unconstrained predefined types. See description of pragma
9084@cite{Check_Float_Overflow} in GNAT RM.
9085@end table
9086
9087@geindex -gnateG (gcc)
9088
9089
9090@table @asis
9091
9092@item @code{-gnateG}
9093
9094Save result of preprocessing in a text file.
9095@end table
9096
9097@geindex -gnatei (gcc)
9098
9099
9100@table @asis
9101
9102@item @code{-gnatei@emph{nnn}}
9103
9104Set maximum number of instantiations during compilation of a single unit to
9105@cite{nnn}. This may be useful in increasing the default maximum of 8000 for
9106the rare case when a single unit legitimately exceeds this limit.
9107@end table
9108
9109@geindex -gnateI (gcc)
9110
9111
9112@table @asis
9113
9114@item @code{-gnateI@emph{nnn}}
9115
9116Indicates that the source is a multi-unit source and that the index of the
9117unit to compile is @cite{nnn}. @cite{nnn} needs to be a positive number and need
9118to be a valid index in the multi-unit source.
9119@end table
9120
9121@geindex -gnatel (gcc)
9122
9123
9124@table @asis
9125
9126@item @code{-gnatel}
9127
9128This switch can be used with the static elaboration model to issue info
9129messages showing
9130where implicit @cite{pragma Elaborate} and @cite{pragma Elaborate_All}
9131are generated. This is useful in diagnosing elaboration circularities
9132caused by these implicit pragmas when using the static elaboration
9133model. See See the section in this guide on elaboration checking for
9134further details. These messages are not generated by default, and are
9135intended only for temporary use when debugging circularity problems.
9136@end table
9137
9138@geindex -gnatel (gcc)
9139
9140
9141@table @asis
9142
9143@item @code{-gnateL}
9144
9145This switch turns off the info messages about implicit elaboration pragmas.
9146@end table
9147
9148@geindex -gnatem (gcc)
9149
9150
9151@table @asis
9152
9153@item @code{-gnatem=@emph{path}}
9154
9155Specify a mapping file
9156(the equal sign is optional)
9157(@ref{fc,,Units to Sources Mapping Files}).
9158@end table
9159
9160@geindex -gnatep (gcc)
9161
9162
9163@table @asis
9164
9165@item @code{-gnatep=@emph{file}}
9166
9167Specify a preprocessing data file
9168(the equal sign is optional)
9169(@ref{1a,,Integrated Preprocessing}).
9170@end table
9171
9172@geindex -gnateP (gcc)
9173
9174
9175@table @asis
9176
9177@item @code{-gnateP}
9178
9179Turn categorization dependency errors into warnings.
9180Ada requires that units that WITH one another have compatible categories, for
9181example a Pure unit cannot WITH a Preelaborate unit. If this switch is used,
9182these errors become warnings (which can be ignored, or suppressed in the usual
9183manner). This can be useful in some specialized circumstances such as the
9184temporary use of special test software.
9185@end table
9186
9187@geindex -gnateS (gcc)
9188
9189
9190@table @asis
9191
9192@item @code{-gnateS}
9193
9194Synonym of @emph{-fdump-scos}, kept for backwards compatibility.
9195@end table
9196
9197@geindex -gnatet=file (gcc)
9198
9199
9200@table @asis
9201
9202@item @code{-gnatet=@emph{path}}
9203
9204Generate target dependent information. The format of the output file is
9205described in the section about switch @emph{-gnateT}.
9206@end table
9207
9208@geindex -gnateT (gcc)
9209
9210
9211@table @asis
9212
9213@item @code{-gnateT=@emph{path}}
9214
9215Read target dependent information, such as endianness or sizes and alignments
9216of base type. If this switch is passed, the default target dependent
9217information of the compiler is replaced by the one read from the input file.
9218This is used by tools other than the compiler, e.g. to do
9219semantic analysis of programs that will run on some other target than
9220the machine on which the tool is run.
9221
9222The following target dependent values should be defined,
9223where @cite{Nat} denotes a natural integer value, @cite{Pos} denotes a
9224positive integer value, and fields marked with a question mark are
9225boolean fields, where a value of 0 is False, and a value of 1 is True:
9226
9227@example
9228Bits_BE                    : Nat; -- Bits stored big-endian?
9229Bits_Per_Unit              : Pos; -- Bits in a storage unit
9230Bits_Per_Word              : Pos; -- Bits in a word
9231Bytes_BE                   : Nat; -- Bytes stored big-endian?
9232Char_Size                  : Pos; -- Standard.Character'Size
9233Double_Float_Alignment     : Nat; -- Alignment of double float
9234Double_Scalar_Alignment    : Nat; -- Alignment of double length scalar
9235Double_Size                : Pos; -- Standard.Long_Float'Size
9236Float_Size                 : Pos; -- Standard.Float'Size
9237Float_Words_BE             : Nat; -- Float words stored big-endian?
9238Int_Size                   : Pos; -- Standard.Integer'Size
9239Long_Double_Size           : Pos; -- Standard.Long_Long_Float'Size
9240Long_Long_Size             : Pos; -- Standard.Long_Long_Integer'Size
9241Long_Size                  : Pos; -- Standard.Long_Integer'Size
9242Maximum_Alignment          : Pos; -- Maximum permitted alignment
9243Max_Unaligned_Field        : Pos; -- Maximum size for unaligned bit field
9244Pointer_Size               : Pos; -- System.Address'Size
9245Short_Enums                : Nat; -- Short foreign convention enums?
9246Short_Size                 : Pos; -- Standard.Short_Integer'Size
9247Strict_Alignment           : Nat; -- Strict alignment?
9248System_Allocator_Alignment : Nat; -- Alignment for malloc calls
9249Wchar_T_Size               : Pos; -- Interfaces.C.wchar_t'Size
9250Words_BE                   : Nat; -- Words stored big-endian?
9251@end example
9252
9253The format of the input file is as follows. First come the values of
9254the variables defined above, with one line per value:
9255
9256@example
9257name  value
9258@end example
9259
9260where @cite{name} is the name of the parameter, spelled out in full,
9261and cased as in the above list, and @cite{value} is an unsigned decimal
9262integer. Two or more blanks separates the name from the value.
9263
9264All the variables must be present, in alphabetical order (i.e. the
9265same order as the list above).
9266
9267Then there is a blank line to separate the two parts of the file. Then
9268come the lines showing the floating-point types to be registered, with
9269one line per registered mode:
9270
9271@example
9272name  digs float_rep size alignment
9273@end example
9274
9275where @cite{name} is the string name of the type (which can have
9276single spaces embedded in the name (e.g. long double), @cite{digs} is
9277the number of digits for the floating-point type, @cite{float_rep} is
9278the float representation (I/V/A for IEEE-754-Binary, Vax_Native,
9279AAMP), @cite{size} is the size in bits, @cite{alignment} is the
9280alignment in bits. The name is followed by at least two blanks, fields
9281are separated by at least one blank, and a LF character immediately
9282follows the alignment field.
9283
9284Here is an example of a target parameterization file:
9285
9286@example
9287Bits_BE                       0
9288Bits_Per_Unit                 8
9289Bits_Per_Word                64
9290Bytes_BE                      0
9291Char_Size                     8
9292Double_Float_Alignment        0
9293Double_Scalar_Alignment       0
9294Double_Size                  64
9295Float_Size                   32
9296Float_Words_BE                0
9297Int_Size                     64
9298Long_Double_Size            128
9299Long_Long_Size               64
9300Long_Size                    64
9301Maximum_Alignment            16
9302Max_Unaligned_Field          64
9303Pointer_Size                 64
9304Short_Size                   16
9305Strict_Alignment              0
9306System_Allocator_Alignment   16
9307Wchar_T_Size                 32
9308Words_BE                      0
9309
9310float         15  I  64  64
9311double        15  I  64  64
9312long double   18  I  80 128
9313TF            33  I 128 128
9314@end example
9315@end table
9316
9317@geindex -gnateu (gcc)
9318
9319
9320@table @asis
9321
9322@item @code{-gnateu}
9323
9324Ignore unrecognized validity, warning, and style switches that
9325appear after this switch is given. This may be useful when
9326compiling sources developed on a later version of the compiler
9327with an earlier version. Of course the earlier version must
9328support this switch.
9329@end table
9330
9331@geindex -gnateV (gcc)
9332
9333
9334@table @asis
9335
9336@item @code{-gnateV}
9337
9338Check that all actual parameters of a subprogram call are valid according to
9339the rules of validity checking (@ref{fb,,Validity Checking}).
9340@end table
9341
9342@geindex -gnateY (gcc)
9343
9344
9345@table @asis
9346
9347@item @code{-gnateY}
9348
9349Ignore all STYLE_CHECKS pragmas. Full legality checks
9350are still carried out, but the pragmas have no effect
9351on what style checks are active. This allows all style
9352checking options to be controlled from the command line.
9353@end table
9354
9355@geindex -gnatE (gcc)
9356
9357
9358@table @asis
9359
9360@item @code{-gnatE}
9361
9362Full dynamic elaboration checks.
9363@end table
9364
9365@geindex -gnatf (gcc)
9366
9367
9368@table @asis
9369
9370@item @code{-gnatf}
9371
9372Full errors. Multiple errors per line, all undefined references, do not
9373attempt to suppress cascaded errors.
9374@end table
9375
9376@geindex -gnatF (gcc)
9377
9378
9379@table @asis
9380
9381@item @code{-gnatF}
9382
9383Externals names are folded to all uppercase.
9384@end table
9385
9386@geindex -gnatg (gcc)
9387
9388
9389@table @asis
9390
9391@item @code{-gnatg}
9392
9393Internal GNAT implementation mode. This should not be used for
9394applications programs, it is intended only for use by the compiler
9395and its run-time library. For documentation, see the GNAT sources.
9396Note that @emph{-gnatg} implies
9397@emph{-gnatw.ge} and
9398@emph{-gnatyg}
9399so that all standard warnings and all standard style options are turned on.
9400All warnings and style messages are treated as errors.
9401@end table
9402
9403@geindex -gnatG[nn] (gcc)
9404
9405
9406@table @asis
9407
9408@item @code{-gnatG=nn}
9409
9410List generated expanded code in source form.
9411@end table
9412
9413@geindex -gnath (gcc)
9414
9415
9416@table @asis
9417
9418@item @code{-gnath}
9419
9420Output usage information. The output is written to @code{stdout}.
9421@end table
9422
9423@geindex -gnati (gcc)
9424
9425
9426@table @asis
9427
9428@item @code{-gnati@emph{c}}
9429
9430Identifier character set (@cite{c} = 1/2/3/4/8/9/p/f/n/w).
9431For details of the possible selections for @cite{c},
9432see @ref{4a,,Character Set Control}.
9433@end table
9434
9435@geindex -gnatI (gcc)
9436
9437
9438@table @asis
9439
9440@item @code{-gnatI}
9441
9442Ignore representation clauses. When this switch is used,
9443representation clauses are treated as comments. This is useful
9444when initially porting code where you want to ignore rep clause
9445problems, and also for compiling foreign code (particularly
9446for use with ASIS). The representation clauses that are ignored
9447are: enumeration_representation_clause, record_representation_clause,
9448and attribute_definition_clause for the following attributes:
9449Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
9450Object_Size, Size, Small, Stream_Size, and Value_Size.
9451Note that this option should be used only for compiling -- the
9452code is likely to malfunction at run time.
9453
9454Note that when @cite{-gnatct} is used to generate trees for input
9455into @cite{ASIS} tools, these representation clauses are removed
9456from the tree and ignored. This means that the tool will not see them.
9457@end table
9458
9459@geindex -gnatjnn (gcc)
9460
9461
9462@table @asis
9463
9464@item @code{-gnatj@emph{nn}}
9465
9466Reformat error messages to fit on @cite{nn} character lines
9467@end table
9468
9469@geindex -gnatk (gcc)
9470
9471
9472@table @asis
9473
9474@item @code{-gnatk=@emph{n}}
9475
9476Limit file names to @cite{n} (1-999) characters (@cite{k} = krunch).
9477@end table
9478
9479@geindex -gnatl (gcc)
9480
9481
9482@table @asis
9483
9484@item @code{-gnatl}
9485
9486Output full source listing with embedded error messages.
9487@end table
9488
9489@geindex -gnatL (gcc)
9490
9491
9492@table @asis
9493
9494@item @code{-gnatL}
9495
9496Used in conjunction with -gnatG or -gnatD to intersperse original
9497source lines (as comment lines with line numbers) in the expanded
9498source output.
9499@end table
9500
9501@geindex -gnatm (gcc)
9502
9503
9504@table @asis
9505
9506@item @code{-gnatm=@emph{n}}
9507
9508Limit number of detected error or warning messages to @cite{n}
9509where @cite{n} is in the range 1..999999. The default setting if
9510no switch is given is 9999. If the number of warnings reaches this
9511limit, then a message is output and further warnings are suppressed,
9512but the compilation is continued. If the number of error messages
9513reaches this limit, then a message is output and the compilation
9514is abandoned. The equal sign here is optional. A value of zero
9515means that no limit applies.
9516@end table
9517
9518@geindex -gnatn (gcc)
9519
9520
9521@table @asis
9522
9523@item @code{-gnatn[12]}
9524
9525Activate inlining for subprograms for which pragma @cite{Inline} is
9526specified. This inlining is performed by the GCC back-end. An optional
9527digit sets the inlining level: 1 for moderate inlining across modules
9528or 2 for full inlining across modules. If no inlining level is specified,
9529the compiler will pick it based on the optimization level.
9530@end table
9531
9532@geindex -gnatN (gcc)
9533
9534
9535@table @asis
9536
9537@item @code{-gnatN}
9538
9539Activate front end inlining for subprograms for which
9540pragma @cite{Inline} is specified. This inlining is performed
9541by the front end and will be visible in the
9542@emph{-gnatG} output.
9543
9544When using a gcc-based back end (in practice this means using any version
9545of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
9546@emph{-gnatN} is deprecated, and the use of @emph{-gnatn} is preferred.
9547Historically front end inlining was more extensive than the gcc back end
9548inlining, but that is no longer the case.
9549@end table
9550
9551@geindex -gnato0 (gcc)
9552
9553
9554@table @asis
9555
9556@item @code{-gnato0}
9557
9558Suppresses overflow checking. This causes the behavior of the compiler to
9559match the default for older versions where overflow checking was suppressed
9560by default. This is equivalent to having
9561@cite{pragma Suppress (Overflow_Mode)} in a configuration pragma file.
9562@end table
9563
9564@geindex -gnato?? (gcc)
9565
9566
9567@table @asis
9568
9569@item @code{-gnato??}
9570
9571Set default mode for handling generation of code to avoid intermediate
9572arithmetic overflow. Here @cite{??} is two digits, a
9573single digit, or nothing. Each digit is one of the digits @cite{1}
9574through @cite{3}:
9575
9576
9577@multitable {xxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
9578@item
9579
9580Digit
9581
9582@tab
9583
9584Interpretation
9585
9586@item
9587
9588@emph{1}
9589
9590@tab
9591
9592All intermediate overflows checked against base type (@cite{STRICT})
9593
9594@item
9595
9596@emph{2}
9597
9598@tab
9599
9600Minimize intermediate overflows (@cite{MINIMIZED})
9601
9602@item
9603
9604@emph{3}
9605
9606@tab
9607
9608Eliminate intermediate overflows (@cite{ELIMINATED})
9609
9610@end multitable
9611
9612
9613If only one digit appears then it applies to all
9614cases; if two digits are given, then the first applies outside
9615assertions, and the second within assertions.
9616
9617If no digits follow the @emph{-gnato}, then it is equivalent to
9618@emph{-gnato11},
9619causing all intermediate overflows to be handled in strict mode.
9620
9621This switch also causes arithmetic overflow checking to be performed
9622(as though @cite{pragma Unsuppress (Overflow_Mode)} had been specified.
9623
9624The default if no option @emph{-gnato} is given is that overflow handling
9625is in @cite{STRICT} mode (computations done using the base type), and that
9626overflow checking is enabled.
9627
9628Note that division by zero is a separate check that is not
9629controlled by this switch (division by zero checking is on by default).
9630
9631See also @ref{fd,,Specifying the Desired Mode}.
9632@end table
9633
9634@geindex -gnatp (gcc)
9635
9636
9637@table @asis
9638
9639@item @code{-gnatp}
9640
9641Suppress all checks. See @ref{fe,,Run-Time Checks} for details. This switch
9642has no effect if cancelled by a subsequent @emph{-gnat-p} switch.
9643@end table
9644
9645@geindex -gnat-p (gcc)
9646
9647
9648@table @asis
9649
9650@item @code{-gnat-p}
9651
9652Cancel effect of previous @emph{-gnatp} switch.
9653@end table
9654
9655@geindex -gnatP (gcc)
9656
9657
9658@table @asis
9659
9660@item @code{-gnatP}
9661
9662Enable polling. This is required on some systems (notably Windows NT) to
9663obtain asynchronous abort and asynchronous transfer of control capability.
9664See @cite{Pragma_Polling} in the @cite{GNAT_Reference_Manual} for full
9665details.
9666@end table
9667
9668@geindex -gnatq (gcc)
9669
9670
9671@table @asis
9672
9673@item @code{-gnatq}
9674
9675Don't quit. Try semantics, even if parse errors.
9676@end table
9677
9678@geindex -gnatQ (gcc)
9679
9680
9681@table @asis
9682
9683@item @code{-gnatQ}
9684
9685Don't quit. Generate @code{ALI} and tree files even if illegalities.
9686Note that code generation is still suppressed in the presence of any
9687errors, so even with @emph{-gnatQ} no object file is generated.
9688@end table
9689
9690@geindex -gnatr (gcc)
9691
9692
9693@table @asis
9694
9695@item @code{-gnatr}
9696
9697Treat pragma Restrictions as Restriction_Warnings.
9698@end table
9699
9700@geindex -gnatR (gcc)
9701
9702
9703@table @asis
9704
9705@item @code{-gnatR[0/1/2/3[s]]}
9706
9707Output representation information for declared types and objects.
9708Note that this switch is not allowed if a previous @cite{-gnatD} switch has
9709been given, since these two switches are not compatible.
9710
9711@item @code{-gnatRm[s]}
9712
9713Output convention and parameter passing mechanisms for all subprograms.
9714@end table
9715
9716@geindex -gnats (gcc)
9717
9718
9719@table @asis
9720
9721@item @code{-gnats}
9722
9723Syntax check only.
9724@end table
9725
9726@geindex -gnatS (gcc)
9727
9728
9729@table @asis
9730
9731@item @code{-gnatS}
9732
9733Print package Standard.
9734@end table
9735
9736@geindex -gnatt (gcc)
9737
9738
9739@table @asis
9740
9741@item @code{-gnatt}
9742
9743Generate tree output file.
9744@end table
9745
9746@geindex -gnatT (gcc)
9747
9748
9749@table @asis
9750
9751@item @code{-gnatT@emph{nnn}}
9752
9753All compiler tables start at @cite{nnn} times usual starting size.
9754@end table
9755
9756@geindex -gnatu (gcc)
9757
9758
9759@table @asis
9760
9761@item @code{-gnatu}
9762
9763List units for this compilation.
9764@end table
9765
9766@geindex -gnatU (gcc)
9767
9768
9769@table @asis
9770
9771@item @code{-gnatU}
9772
9773Tag all error messages with the unique string 'error:'
9774@end table
9775
9776@geindex -gnatv (gcc)
9777
9778
9779@table @asis
9780
9781@item @code{-gnatv}
9782
9783Verbose mode. Full error output with source lines to @code{stdout}.
9784@end table
9785
9786@geindex -gnatV (gcc)
9787
9788
9789@table @asis
9790
9791@item @code{-gnatV}
9792
9793Control level of validity checking (@ref{fb,,Validity Checking}).
9794@end table
9795
9796@geindex -gnatw (gcc)
9797
9798
9799@table @asis
9800
9801@item @code{-gnatw@emph{xxx}}
9802
9803Warning mode where
9804@cite{xxx} is a string of option letters that denotes
9805the exact warnings that
9806are enabled or disabled (@ref{ff,,Warning Message Control}).
9807@end table
9808
9809@geindex -gnatW (gcc)
9810
9811
9812@table @asis
9813
9814@item @code{-gnatW@emph{e}}
9815
9816Wide character encoding method
9817(@cite{e}=n/h/u/s/e/8).
9818@end table
9819
9820@geindex -gnatx (gcc)
9821
9822
9823@table @asis
9824
9825@item @code{-gnatx}
9826
9827Suppress generation of cross-reference information.
9828@end table
9829
9830@geindex -gnatX (gcc)
9831
9832
9833@table @asis
9834
9835@item @code{-gnatX}
9836
9837Enable GNAT implementation extensions and latest Ada version.
9838@end table
9839
9840@geindex -gnaty (gcc)
9841
9842
9843@table @asis
9844
9845@item @code{-gnaty}
9846
9847Enable built-in style checks (@ref{100,,Style Checking}).
9848@end table
9849
9850@geindex -gnatz (gcc)
9851
9852
9853@table @asis
9854
9855@item @code{-gnatz@emph{m}}
9856
9857Distribution stub generation and compilation
9858(@cite{m}=r/c for receiver/caller stubs).
9859@end table
9860
9861@geindex -I (gcc)
9862
9863
9864@table @asis
9865
9866@item @code{-I@emph{dir}}
9867
9868@geindex RTL
9869
9870Direct GNAT to search the @cite{dir} directory for source files needed by
9871the current compilation
9872(see @ref{8e,,Search Paths and the Run-Time Library (RTL)}).
9873@end table
9874
9875@geindex -I- (gcc)
9876
9877
9878@table @asis
9879
9880@item @code{-I-}
9881
9882@geindex RTL
9883
9884Except for the source file named in the command line, do not look for source
9885files in the directory containing the source file named in the command line
9886(see @ref{8e,,Search Paths and the Run-Time Library (RTL)}).
9887@end table
9888
9889@geindex -o (gcc)
9890
9891
9892@table @asis
9893
9894@item @code{-o @emph{file}}
9895
9896This switch is used in @emph{gcc} to redirect the generated object file
9897and its associated ALI file. Beware of this switch with GNAT, because it may
9898cause the object file and ALI file to have different names which in turn
9899may confuse the binder and the linker.
9900@end table
9901
9902@geindex -nostdinc (gcc)
9903
9904
9905@table @asis
9906
9907@item @code{-nostdinc}
9908
9909Inhibit the search of the default location for the GNAT Run Time
9910Library (RTL) source files.
9911@end table
9912
9913@geindex -nostdlib (gcc)
9914
9915
9916@table @asis
9917
9918@item @code{-nostdlib}
9919
9920Inhibit the search of the default location for the GNAT Run Time
9921Library (RTL) ALI files.
9922@end table
9923
9924@geindex -O (gcc)
9925
9926
9927@table @asis
9928
9929@item @code{-O[@emph{n}]}
9930
9931@cite{n} controls the optimization level:
9932
9933
9934@multitable {xxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
9935@item
9936
9937@emph{n}
9938
9939@tab
9940
9941Effect
9942
9943@item
9944
9945@emph{0}
9946
9947@tab
9948
9949No optimization, the default setting if no @emph{-O} appears
9950
9951@item
9952
9953@emph{1}
9954
9955@tab
9956
9957Normal optimization, the default if you specify @emph{-O} without an
9958operand. A good compromise between code quality and compilation
9959time.
9960
9961@item
9962
9963@emph{2}
9964
9965@tab
9966
9967Extensive optimization, may improve execution time, possibly at
9968the cost of substantially increased compilation time.
9969
9970@item
9971
9972@emph{3}
9973
9974@tab
9975
9976Same as @emph{-O2}, and also includes inline expansion for small
9977subprograms in the same unit.
9978
9979@item
9980
9981@emph{s}
9982
9983@tab
9984
9985Optimize space usage
9986
9987@end multitable
9988
9989
9990See also @ref{101,,Optimization Levels}.
9991@end table
9992
9993@geindex -pass-exit-codes (gcc)
9994
9995
9996@table @asis
9997
9998@item @code{-pass-exit-codes}
9999
10000Catch exit codes from the compiler and use the most meaningful as
10001exit status.
10002@end table
10003
10004@geindex --RTS (gcc)
10005
10006
10007@table @asis
10008
10009@item @code{--RTS=@emph{rts-path}}
10010
10011Specifies the default location of the runtime library. Same meaning as the
10012equivalent @emph{gnatmake} flag (@ref{df,,Switches for gnatmake}).
10013@end table
10014
10015@geindex -S (gcc)
10016
10017
10018@table @asis
10019
10020@item @code{-S}
10021
10022Used in place of @emph{-c} to
10023cause the assembler source file to be
10024generated, using @code{.s} as the extension,
10025instead of the object file.
10026This may be useful if you need to examine the generated assembly code.
10027@end table
10028
10029@geindex -fverbose-asm (gcc)
10030
10031
10032@table @asis
10033
10034@item @code{-fverbose-asm}
10035
10036Used in conjunction with @emph{-S}
10037to cause the generated assembly code file to be annotated with variable
10038names, making it significantly easier to follow.
10039@end table
10040
10041@geindex -v (gcc)
10042
10043
10044@table @asis
10045
10046@item @code{-v}
10047
10048Show commands generated by the @emph{gcc} driver. Normally used only for
10049debugging purposes or if you need to be sure what version of the
10050compiler you are executing.
10051@end table
10052
10053@geindex -V (gcc)
10054
10055
10056@table @asis
10057
10058@item @code{-V @emph{ver}}
10059
10060Execute @cite{ver} version of the compiler. This is the @emph{gcc}
10061version, not the GNAT version.
10062@end table
10063
10064@geindex -w (gcc)
10065
10066
10067@table @asis
10068
10069@item @code{-w}
10070
10071Turn off warnings generated by the back end of the compiler. Use of
10072this switch also causes the default for front end warnings to be set
10073to suppress (as though @emph{-gnatws} had appeared at the start of
10074the options).
10075@end table
10076
10077@geindex Combining GNAT switches
10078
10079You may combine a sequence of GNAT switches into a single switch. For
10080example, the combined switch
10081
10082@quotation
10083
10084@example
10085-gnatofi3
10086@end example
10087@end quotation
10088
10089is equivalent to specifying the following sequence of switches:
10090
10091@quotation
10092
10093@example
10094-gnato -gnatf -gnati3
10095@end example
10096@end quotation
10097
10098The following restrictions apply to the combination of switches
10099in this manner:
10100
10101
10102@itemize *
10103
10104@item 
10105The switch @emph{-gnatc} if combined with other switches must come
10106first in the string.
10107
10108@item 
10109The switch @emph{-gnats} if combined with other switches must come
10110first in the string.
10111
10112@item 
10113The switches
10114@emph{-gnatzc} and @emph{-gnatzr} may not be combined with any other
10115switches, and only one of them may appear in the command line.
10116
10117@item 
10118The switch @emph{-gnat-p} may not be combined with any other switch.
10119
10120@item 
10121Once a 'y' appears in the string (that is a use of the @emph{-gnaty}
10122switch), then all further characters in the switch are interpreted
10123as style modifiers (see description of @emph{-gnaty}).
10124
10125@item 
10126Once a 'd' appears in the string (that is a use of the @emph{-gnatd}
10127switch), then all further characters in the switch are interpreted
10128as debug flags (see description of @emph{-gnatd}).
10129
10130@item 
10131Once a 'w' appears in the string (that is a use of the @emph{-gnatw}
10132switch), then all further characters in the switch are interpreted
10133as warning mode modifiers (see description of @emph{-gnatw}).
10134
10135@item 
10136Once a 'V' appears in the string (that is a use of the @emph{-gnatV}
10137switch), then all further characters in the switch are interpreted
10138as validity checking options (@ref{fb,,Validity Checking}).
10139
10140@item 
10141Option 'em', 'ec', 'ep', 'l=' and 'R' must be the last options in
10142a combined list of options.
10143@end itemize
10144
10145@node Output and Error Message Control,Warning Message Control,Alphabetical List of All Switches,Compiler Switches
10146@anchor{gnat_ugn/building_executable_programs_with_gnat id14}@anchor{102}@anchor{gnat_ugn/building_executable_programs_with_gnat output-and-error-message-control}@anchor{103}
10147@subsection Output and Error Message Control
10148
10149
10150@geindex stderr
10151
10152The standard default format for error messages is called 'brief format'.
10153Brief format messages are written to @code{stderr} (the standard error
10154file) and have the following form:
10155
10156@example
10157e.adb:3:04: Incorrect spelling of keyword "function"
10158e.adb:4:20: ";" should be "is"
10159@end example
10160
10161The first integer after the file name is the line number in the file,
10162and the second integer is the column number within the line.
10163@cite{GPS} can parse the error messages
10164and point to the referenced character.
10165The following switches provide control over the error message
10166format:
10167
10168@geindex -gnatv (gcc)
10169
10170
10171@table @asis
10172
10173@item @code{-gnatv}
10174
10175The @cite{v} stands for verbose.
10176The effect of this setting is to write long-format error
10177messages to @code{stdout} (the standard output file.
10178The same program compiled with the
10179@emph{-gnatv} switch would generate:
10180
10181@example
101823. funcion X (Q : Integer)
10183   |
10184>>> Incorrect spelling of keyword "function"
101854. return Integer;
10186                 |
10187>>> ";" should be "is"
10188@end example
10189
10190The vertical bar indicates the location of the error, and the @code{>>>}
10191prefix can be used to search for error messages. When this switch is
10192used the only source lines output are those with errors.
10193@end table
10194
10195@geindex -gnatl (gcc)
10196
10197
10198@table @asis
10199
10200@item @code{-gnatl}
10201
10202The @cite{l} stands for list.
10203This switch causes a full listing of
10204the file to be generated. In the case where a body is
10205compiled, the corresponding spec is also listed, along
10206with any subunits. Typical output from compiling a package
10207body @code{p.adb} might look like:
10208
10209@example
10210Compiling: p.adb
10211
10212     1. package body p is
10213     2.    procedure a;
10214     3.    procedure a is separate;
10215     4. begin
10216     5.    null
10217               |
10218        >>> missing ";"
10219
10220     6. end;
10221
10222Compiling: p.ads
10223
10224     1. package p is
10225     2.    pragma Elaborate_Body
10226                                |
10227        >>> missing ";"
10228
10229     3. end p;
10230
10231Compiling: p-a.adb
10232
10233     1. separate p
10234                |
10235        >>> missing "("
10236
10237     2. procedure a is
10238     3. begin
10239     4.    null
10240               |
10241        >>> missing ";"
10242
10243     5. end;
10244@end example
10245
10246When you specify the @emph{-gnatv} or @emph{-gnatl} switches and
10247standard output is redirected, a brief summary is written to
10248@code{stderr} (standard error) giving the number of error messages and
10249warning messages generated.
10250@end table
10251
10252@geindex -gnatl=fname (gcc)
10253
10254
10255@table @asis
10256
10257@item @code{-gnatl=@emph{fname}}
10258
10259This has the same effect as @emph{-gnatl} except that the output is
10260written to a file instead of to standard output. If the given name
10261@code{fname} does not start with a period, then it is the full name
10262of the file to be written. If @code{fname} is an extension, it is
10263appended to the name of the file being compiled. For example, if
10264file @code{xyz.adb} is compiled with @emph{-gnatl=.lst},
10265then the output is written to file xyz.adb.lst.
10266@end table
10267
10268@geindex -gnatU (gcc)
10269
10270
10271@table @asis
10272
10273@item @code{-gnatU}
10274
10275This switch forces all error messages to be preceded by the unique
10276string 'error:'. This means that error messages take a few more
10277characters in space, but allows easy searching for and identification
10278of error messages.
10279@end table
10280
10281@geindex -gnatb (gcc)
10282
10283
10284@table @asis
10285
10286@item @code{-gnatb}
10287
10288The @cite{b} stands for brief.
10289This switch causes GNAT to generate the
10290brief format error messages to @code{stderr} (the standard error
10291file) as well as the verbose
10292format message or full listing (which as usual is written to
10293@code{stdout} (the standard output file).
10294@end table
10295
10296@geindex -gnatm (gcc)
10297
10298
10299@table @asis
10300
10301@item @code{-gnatm=@emph{n}}
10302
10303The @cite{m} stands for maximum.
10304@cite{n} is a decimal integer in the
10305range of 1 to 999999 and limits the number of error or warning
10306messages to be generated. For example, using
10307@emph{-gnatm2} might yield
10308
10309@example
10310e.adb:3:04: Incorrect spelling of keyword "function"
10311e.adb:5:35: missing ".."
10312fatal error: maximum number of errors detected
10313compilation abandoned
10314@end example
10315
10316The default setting if
10317no switch is given is 9999. If the number of warnings reaches this
10318limit, then a message is output and further warnings are suppressed,
10319but the compilation is continued. If the number of error messages
10320reaches this limit, then a message is output and the compilation
10321is abandoned. A value of zero means that no limit applies.
10322
10323Note that the equal sign is optional, so the switches
10324@emph{-gnatm2} and @emph{-gnatm=2} are equivalent.
10325@end table
10326
10327@geindex -gnatf (gcc)
10328
10329
10330@table @asis
10331
10332@item @code{-gnatf}
10333
10334@geindex Error messages
10335@geindex suppressing
10336
10337The @cite{f} stands for full.
10338Normally, the compiler suppresses error messages that are likely to be
10339redundant. This switch causes all error
10340messages to be generated. In particular, in the case of
10341references to undefined variables. If a given variable is referenced
10342several times, the normal format of messages is
10343
10344@example
10345e.adb:7:07: "V" is undefined (more references follow)
10346@end example
10347
10348where the parenthetical comment warns that there are additional
10349references to the variable @cite{V}. Compiling the same program with the
10350@emph{-gnatf} switch yields
10351
10352@example
10353e.adb:7:07: "V" is undefined
10354e.adb:8:07: "V" is undefined
10355e.adb:8:12: "V" is undefined
10356e.adb:8:16: "V" is undefined
10357e.adb:9:07: "V" is undefined
10358e.adb:9:12: "V" is undefined
10359@end example
10360
10361The @emph{-gnatf} switch also generates additional information for
10362some error messages.  Some examples are:
10363
10364
10365@itemize *
10366
10367@item 
10368Details on possibly non-portable unchecked conversion
10369
10370@item 
10371List possible interpretations for ambiguous calls
10372
10373@item 
10374Additional details on incorrect parameters
10375@end itemize
10376@end table
10377
10378@geindex -gnatjnn (gcc)
10379
10380
10381@table @asis
10382
10383@item @code{-gnatjnn}
10384
10385In normal operation mode (or if @emph{-gnatj0} is used), then error messages
10386with continuation lines are treated as though the continuation lines were
10387separate messages (and so a warning with two continuation lines counts as
10388three warnings, and is listed as three separate messages).
10389
10390If the @emph{-gnatjnn} switch is used with a positive value for nn, then
10391messages are output in a different manner. A message and all its continuation
10392lines are treated as a unit, and count as only one warning or message in the
10393statistics totals. Furthermore, the message is reformatted so that no line
10394is longer than nn characters.
10395@end table
10396
10397@geindex -gnatq (gcc)
10398
10399
10400@table @asis
10401
10402@item @code{-gnatq}
10403
10404The @cite{q} stands for quit (really 'don't quit').
10405In normal operation mode, the compiler first parses the program and
10406determines if there are any syntax errors. If there are, appropriate
10407error messages are generated and compilation is immediately terminated.
10408This switch tells
10409GNAT to continue with semantic analysis even if syntax errors have been
10410found. This may enable the detection of more errors in a single run. On
10411the other hand, the semantic analyzer is more likely to encounter some
10412internal fatal error when given a syntactically invalid tree.
10413@end table
10414
10415@geindex -gnatQ (gcc)
10416
10417
10418@table @asis
10419
10420@item @code{-gnatQ}
10421
10422In normal operation mode, the @code{ALI} file is not generated if any
10423illegalities are detected in the program. The use of @emph{-gnatQ} forces
10424generation of the @code{ALI} file. This file is marked as being in
10425error, so it cannot be used for binding purposes, but it does contain
10426reasonably complete cross-reference information, and thus may be useful
10427for use by tools (e.g., semantic browsing tools or integrated development
10428environments) that are driven from the @code{ALI} file. This switch
10429implies @emph{-gnatq}, since the semantic phase must be run to get a
10430meaningful ALI file.
10431
10432In addition, if @emph{-gnatt} is also specified, then the tree file is
10433generated even if there are illegalities. It may be useful in this case
10434to also specify @emph{-gnatq} to ensure that full semantic processing
10435occurs. The resulting tree file can be processed by ASIS, for the purpose
10436of providing partial information about illegal units, but if the error
10437causes the tree to be badly malformed, then ASIS may crash during the
10438analysis.
10439
10440When @emph{-gnatQ} is used and the generated @code{ALI} file is marked as
10441being in error, @emph{gnatmake} will attempt to recompile the source when it
10442finds such an @code{ALI} file, including with switch @emph{-gnatc}.
10443
10444Note that @emph{-gnatQ} has no effect if @emph{-gnats} is specified,
10445since ALI files are never generated if @emph{-gnats} is set.
10446@end table
10447
10448@node Warning Message Control,Debugging and Assertion Control,Output and Error Message Control,Compiler Switches
10449@anchor{gnat_ugn/building_executable_programs_with_gnat warning-message-control}@anchor{ff}@anchor{gnat_ugn/building_executable_programs_with_gnat id15}@anchor{104}
10450@subsection Warning Message Control
10451
10452
10453@geindex Warning messages
10454
10455In addition to error messages, which correspond to illegalities as defined
10456in the Ada Reference Manual, the compiler detects two kinds of warning
10457situations.
10458
10459First, the compiler considers some constructs suspicious and generates a
10460warning message to alert you to a possible error. Second, if the
10461compiler detects a situation that is sure to raise an exception at
10462run time, it generates a warning message. The following shows an example
10463of warning messages:
10464
10465@example
10466e.adb:4:24: warning: creation of object may raise Storage_Error
10467e.adb:10:17: warning: static value out of range
10468e.adb:10:17: warning: "Constraint_Error" will be raised at run time
10469@end example
10470
10471GNAT considers a large number of situations as appropriate
10472for the generation of warning messages. As always, warnings are not
10473definite indications of errors. For example, if you do an out-of-range
10474assignment with the deliberate intention of raising a
10475@cite{Constraint_Error} exception, then the warning that may be
10476issued does not indicate an error. Some of the situations for which GNAT
10477issues warnings (at least some of the time) are given in the following
10478list. This list is not complete, and new warnings are often added to
10479subsequent versions of GNAT. The list is intended to give a general idea
10480of the kinds of warnings that are generated.
10481
10482
10483@itemize *
10484
10485@item 
10486Possible infinitely recursive calls
10487
10488@item 
10489Out-of-range values being assigned
10490
10491@item 
10492Possible order of elaboration problems
10493
10494@item 
10495Size not a multiple of alignment for a record type
10496
10497@item 
10498Assertions (pragma Assert) that are sure to fail
10499
10500@item 
10501Unreachable code
10502
10503@item 
10504Address clauses with possibly unaligned values, or where an attempt is
10505made to overlay a smaller variable with a larger one.
10506
10507@item 
10508Fixed-point type declarations with a null range
10509
10510@item 
10511Direct_IO or Sequential_IO instantiated with a type that has access values
10512
10513@item 
10514Variables that are never assigned a value
10515
10516@item 
10517Variables that are referenced before being initialized
10518
10519@item 
10520Task entries with no corresponding @cite{accept} statement
10521
10522@item 
10523Duplicate accepts for the same task entry in a @cite{select}
10524
10525@item 
10526Objects that take too much storage
10527
10528@item 
10529Unchecked conversion between types of differing sizes
10530
10531@item 
10532Missing @cite{return} statement along some execution path in a function
10533
10534@item 
10535Incorrect (unrecognized) pragmas
10536
10537@item 
10538Incorrect external names
10539
10540@item 
10541Allocation from empty storage pool
10542
10543@item 
10544Potentially blocking operation in protected type
10545
10546@item 
10547Suspicious parenthesization of expressions
10548
10549@item 
10550Mismatching bounds in an aggregate
10551
10552@item 
10553Attempt to return local value by reference
10554
10555@item 
10556Premature instantiation of a generic body
10557
10558@item 
10559Attempt to pack aliased components
10560
10561@item 
10562Out of bounds array subscripts
10563
10564@item 
10565Wrong length on string assignment
10566
10567@item 
10568Violations of style rules if style checking is enabled
10569
10570@item 
10571Unused @emph{with} clauses
10572
10573@item 
10574@cite{Bit_Order} usage that does not have any effect
10575
10576@item 
10577@cite{Standard.Duration} used to resolve universal fixed expression
10578
10579@item 
10580Dereference of possibly null value
10581
10582@item 
10583Declaration that is likely to cause storage error
10584
10585@item 
10586Internal GNAT unit @emph{with}ed by application unit
10587
10588@item 
10589Values known to be out of range at compile time
10590
10591@item 
10592Unreferenced or unmodified variables. Note that a special
10593exemption applies to variables which contain any of the substrings
10594@cite{DISCARD@comma{} DUMMY@comma{} IGNORE@comma{} JUNK@comma{} UNUSED}, in any casing. Such variables
10595are considered likely to be intentionally used in a situation where
10596otherwise a warning would be given, so warnings of this kind are
10597always suppressed for such variables.
10598
10599@item 
10600Address overlays that could clobber memory
10601
10602@item 
10603Unexpected initialization when address clause present
10604
10605@item 
10606Bad alignment for address clause
10607
10608@item 
10609Useless type conversions
10610
10611@item 
10612Redundant assignment statements and other redundant constructs
10613
10614@item 
10615Useless exception handlers
10616
10617@item 
10618Accidental hiding of name by child unit
10619
10620@item 
10621Access before elaboration detected at compile time
10622
10623@item 
10624A range in a @cite{for} loop that is known to be null or might be null
10625@end itemize
10626
10627The following section lists compiler switches that are available
10628to control the handling of warning messages. It is also possible
10629to exercise much finer control over what warnings are issued and
10630suppressed using the GNAT pragma Warnings (see the description
10631of the pragma in the @cite{GNAT_Reference_manual}).
10632
10633@geindex -gnatwa (gcc)
10634
10635
10636@table @asis
10637
10638@item @code{-gnatwa}
10639
10640@emph{Activate most optional warnings.}
10641
10642This switch activates most optional warning messages.  See the remaining list
10643in this section for details on optional warning messages that can be
10644individually controlled.  The warnings that are not turned on by this
10645switch are:
10646
10647
10648@itemize *
10649
10650@item 
10651@code{-gnatwd} (implicit dereferencing)
10652
10653@item 
10654@code{-gnatw.d} (tag warnings with -gnatw switch)
10655
10656@item 
10657@code{-gnatwh} (hiding)
10658
10659@item 
10660@code{-gnatw.h} (holes in record layouts)
10661
10662@item 
10663@code{-gnatw.k} (redefinition of names in standard)
10664
10665@item 
10666@code{-gnatwl} (elaboration warnings)
10667
10668@item 
10669@code{-gnatw.l} (inherited aspects)
10670
10671@item 
10672@code{-gnatw.n} (atomic synchronization)
10673
10674@item 
10675@code{-gnatwo} (address clause overlay)
10676
10677@item 
10678@code{-gnatw.o} (values set by out parameters ignored)
10679
10680@item 
10681@code{-gnatw.s} (overridden size clause)
10682
10683@item 
10684@code{-gnatwt} (tracking of deleted conditional code)
10685
10686@item 
10687@code{-gnatw.u} (unordered enumeration)
10688
10689@item 
10690@code{-gnatw.w} (use of Warnings Off)
10691
10692@item 
10693@code{-gnatw.y} (reasons for package needing body)
10694@end itemize
10695
10696All other optional warnings are turned on.
10697@end table
10698
10699@geindex -gnatwA (gcc)
10700
10701
10702@table @asis
10703
10704@item @code{-gnatwA}
10705
10706@emph{Suppress all optional errors.}
10707
10708This switch suppresses all optional warning messages, see remaining list
10709in this section for details on optional warning messages that can be
10710individually controlled. Note that unlike switch @emph{-gnatws}, the
10711use of switch @emph{-gnatwA} does not suppress warnings that are
10712normally given unconditionally and cannot be individually controlled
10713(for example, the warning about a missing exit path in a function).
10714Also, again unlike switch @emph{-gnatws}, warnings suppressed by
10715the use of switch @emph{-gnatwA} can be individually turned back
10716on. For example the use of switch @emph{-gnatwA} followed by
10717switch @emph{-gnatwd} will suppress all optional warnings except
10718the warnings for implicit dereferencing.
10719@end table
10720
10721@geindex -gnatw.a (gcc)
10722
10723
10724@table @asis
10725
10726@item @code{-gnatw.a}
10727
10728@emph{Activate warnings on failing assertions.}
10729
10730@geindex Assert failures
10731
10732This switch activates warnings for assertions where the compiler can tell at
10733compile time that the assertion will fail. Note that this warning is given
10734even if assertions are disabled. The default is that such warnings are
10735generated.
10736@end table
10737
10738@geindex -gnatw.A (gcc)
10739
10740
10741@table @asis
10742
10743@item @code{-gnatw.A}
10744
10745@emph{Suppress warnings on failing assertions.}
10746
10747@geindex Assert failures
10748
10749This switch suppresses warnings for assertions where the compiler can tell at
10750compile time that the assertion will fail.
10751@end table
10752
10753@geindex -gnatwb (gcc)
10754
10755
10756@table @asis
10757
10758@item @code{-gnatwb}
10759
10760@emph{Activate warnings on bad fixed values.}
10761
10762@geindex Bad fixed values
10763
10764@geindex Fixed-point Small value
10765
10766@geindex Small value
10767
10768This switch activates warnings for static fixed-point expressions whose
10769value is not an exact multiple of Small. Such values are implementation
10770dependent, since an implementation is free to choose either of the multiples
10771that surround the value. GNAT always chooses the closer one, but this is not
10772required behavior, and it is better to specify a value that is an exact
10773multiple, ensuring predictable execution. The default is that such warnings
10774are not generated.
10775@end table
10776
10777@geindex -gnatwB (gcc)
10778
10779
10780@table @asis
10781
10782@item @code{-gnatwB}
10783
10784@emph{Suppress warnings on bad fixed values.}
10785
10786This switch suppresses warnings for static fixed-point expressions whose
10787value is not an exact multiple of Small.
10788@end table
10789
10790@geindex -gnatw.b (gcc)
10791
10792
10793@table @asis
10794
10795@item @code{-gnatw.b}
10796
10797@emph{Activate warnings on biased representation.}
10798
10799@geindex Biased representation
10800
10801This switch activates warnings when a size clause, value size clause, component
10802clause, or component size clause forces the use of biased representation for an
10803integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
10804to represent 10/11). The default is that such warnings are generated.
10805@end table
10806
10807@geindex -gnatwB (gcc)
10808
10809
10810@table @asis
10811
10812@item @code{-gnatw.B}
10813
10814@emph{Suppress warnings on biased representation.}
10815
10816This switch suppresses warnings for representation clauses that force the use
10817of biased representation.
10818@end table
10819
10820@geindex -gnatwc (gcc)
10821
10822
10823@table @asis
10824
10825@item @code{-gnatwc}
10826
10827@emph{Activate warnings on conditionals.}
10828
10829@geindex Conditionals
10830@geindex constant
10831
10832This switch activates warnings for conditional expressions used in
10833tests that are known to be True or False at compile time. The default
10834is that such warnings are not generated.
10835Note that this warning does
10836not get issued for the use of boolean variables or constants whose
10837values are known at compile time, since this is a standard technique
10838for conditional compilation in Ada, and this would generate too many
10839false positive warnings.
10840
10841This warning option also activates a special test for comparisons using
10842the operators '>=' and' <='.
10843If the compiler can tell that only the equality condition is possible,
10844then it will warn that the '>' or '<' part of the test
10845is useless and that the operator could be replaced by '='.
10846An example would be comparing a @cite{Natural} variable <= 0.
10847
10848This warning option also generates warnings if
10849one or both tests is optimized away in a membership test for integer
10850values if the result can be determined at compile time. Range tests on
10851enumeration types are not included, since it is common for such tests
10852to include an end point.
10853
10854This warning can also be turned on using @emph{-gnatwa}.
10855@end table
10856
10857@geindex -gnatwC (gcc)
10858
10859
10860@table @asis
10861
10862@item @code{-gnatwC}
10863
10864@emph{Suppress warnings on conditionals.}
10865
10866This switch suppresses warnings for conditional expressions used in
10867tests that are known to be True or False at compile time.
10868@end table
10869
10870@geindex -gnatw.c (gcc)
10871
10872
10873@table @asis
10874
10875@item @code{-gnatw.c}
10876
10877@emph{Activate warnings on missing component clauses.}
10878
10879@geindex Component clause
10880@geindex missing
10881
10882This switch activates warnings for record components where a record
10883representation clause is present and has component clauses for the
10884majority, but not all, of the components. A warning is given for each
10885component for which no component clause is present.
10886@end table
10887
10888@geindex -gnatwC (gcc)
10889
10890
10891@table @asis
10892
10893@item @code{-gnatw.C}
10894
10895@emph{Suppress warnings on missing component clauses.}
10896
10897This switch suppresses warnings for record components that are
10898missing a component clause in the situation described above.
10899@end table
10900
10901@geindex -gnatwd (gcc)
10902
10903
10904@table @asis
10905
10906@item @code{-gnatwd}
10907
10908@emph{Activate warnings on implicit dereferencing.}
10909
10910If this switch is set, then the use of a prefix of an access type
10911in an indexed component, slice, or selected component without an
10912explicit @cite{.all} will generate a warning. With this warning
10913enabled, access checks occur only at points where an explicit
10914@cite{.all} appears in the source code (assuming no warnings are
10915generated as a result of this switch). The default is that such
10916warnings are not generated.
10917@end table
10918
10919@geindex -gnatwD (gcc)
10920
10921
10922@table @asis
10923
10924@item @code{-gnatwD}
10925
10926@emph{Suppress warnings on implicit dereferencing.}
10927
10928@geindex Implicit dereferencing
10929
10930@geindex Dereferencing
10931@geindex implicit
10932
10933This switch suppresses warnings for implicit dereferences in
10934indexed components, slices, and selected components.
10935@end table
10936
10937@geindex -gnatw.d (gcc)
10938
10939
10940@table @asis
10941
10942@item @code{-gnatw.d}
10943
10944@emph{Activate tagging of warning and info messages.}
10945
10946If this switch is set, then warning messages are tagged, with one of the
10947following strings:
10948
10949@quotation
10950
10951
10952@itemize -
10953
10954@item 
10955@emph{[-gnatw?]}
10956Used to tag warnings controlled by the switch @emph{-gnatwx} where x
10957is a letter a-z.
10958
10959@item 
10960@emph{[-gnatw.?]}
10961Used to tag warnings controlled by the switch @emph{-gnatw.x} where x
10962is a letter a-z.
10963
10964@item 
10965@emph{[-gnatel]}
10966Used to tag elaboration information (info) messages generated when the
10967static model of elaboration is used and the @emph{-gnatel} switch is set.
10968
10969@item 
10970@emph{[restriction warning]}
10971Used to tag warning messages for restriction violations, activated by use
10972of the pragma @emph{Restriction_Warnings}.
10973
10974@item 
10975@emph{[warning-as-error]}
10976Used to tag warning messages that have been converted to error messages by
10977use of the pragma Warning_As_Error. Note that such warnings are prefixed by
10978the string "error: " rather than "warning: ".
10979
10980@item 
10981@emph{[enabled by default]}
10982Used to tag all other warnings that are always given by default, unless
10983warnings are completely suppressed using pragma @emph{Warnings(Off)} or
10984the switch @emph{-gnatws}.
10985@end itemize
10986@end quotation
10987@end table
10988
10989@geindex -gnatw.d (gcc)
10990
10991
10992@table @asis
10993
10994@item @code{-gnatw.D}
10995
10996@emph{Deactivate tagging of warning and info messages messages.}
10997
10998If this switch is set, then warning messages return to the default
10999mode in which warnings and info messages are not tagged as described above for
11000@cite{-gnatw.d}.
11001@end table
11002
11003@geindex -gnatwe (gcc)
11004
11005@geindex Warnings
11006@geindex treat as error
11007
11008
11009@table @asis
11010
11011@item @code{-gnatwe}
11012
11013@emph{Treat warnings and style checks as errors.}
11014
11015This switch causes warning messages and style check messages to be
11016treated as errors.
11017The warning string still appears, but the warning messages are counted
11018as errors, and prevent the generation of an object file. Note that this
11019is the only -gnatw switch that affects the handling of style check messages.
11020Note also that this switch has no effect on info (information) messages, which
11021are not treated as errors if this switch is present.
11022@end table
11023
11024@geindex -gnatw.e (gcc)
11025
11026
11027@table @asis
11028
11029@item @code{-gnatw.e}
11030
11031@emph{Activate every optional warning}
11032
11033@geindex Warnings
11034@geindex activate every optional warning
11035
11036This switch activates all optional warnings, including those which
11037are not activated by @cite{-gnatwa}. The use of this switch is not
11038recommended for normal use. If you turn this switch on, it is almost
11039certain that you will get large numbers of useless warnings. The
11040warnings that are excluded from @cite{-gnatwa} are typically highly
11041specialized warnings that are suitable for use only in code that has
11042been specifically designed according to specialized coding rules.
11043@end table
11044
11045@geindex -gnatwf (gcc)
11046
11047
11048@table @asis
11049
11050@item @code{-gnatwf}
11051
11052@emph{Activate warnings on unreferenced formals.}
11053
11054@geindex Formals
11055@geindex unreferenced
11056
11057This switch causes a warning to be generated if a formal parameter
11058is not referenced in the body of the subprogram. This warning can
11059also be turned on using @emph{-gnatwu}. The
11060default is that these warnings are not generated.
11061@end table
11062
11063@geindex -gnatwF (gcc)
11064
11065
11066@table @asis
11067
11068@item @code{-gnatwF}
11069
11070@emph{Suppress warnings on unreferenced formals.}
11071
11072This switch suppresses warnings for unreferenced formal
11073parameters. Note that the
11074combination @emph{-gnatwu} followed by @emph{-gnatwF} has the
11075effect of warning on unreferenced entities other than subprogram
11076formals.
11077@end table
11078
11079@geindex -gnatwg (gcc)
11080
11081
11082@table @asis
11083
11084@item @code{-gnatwg}
11085
11086@emph{Activate warnings on unrecognized pragmas.}
11087
11088@geindex Pragmas
11089@geindex unrecognized
11090
11091This switch causes a warning to be generated if an unrecognized
11092pragma is encountered. Apart from issuing this warning, the
11093pragma is ignored and has no effect. The default
11094is that such warnings are issued (satisfying the Ada Reference
11095Manual requirement that such warnings appear).
11096@end table
11097
11098@geindex -gnatwG (gcc)
11099
11100
11101@table @asis
11102
11103@item @code{-gnatwG}
11104
11105@emph{Suppress warnings on unrecognized pragmas.}
11106
11107This switch suppresses warnings for unrecognized pragmas.
11108@end table
11109
11110@geindex -gnatw.g (gcc)
11111
11112
11113@table @asis
11114
11115@item @code{-gnatw.g}
11116
11117@emph{Warnings used for GNAT sources}
11118
11119This switch sets the warning categories that are used by the standard
11120GNAT style. Currently this is equivalent to
11121@emph{-gnatwAao.sI.C.V.X}
11122but more warnings may be added in the future without advanced notice.
11123@end table
11124
11125@geindex -gnatwh (gcc)
11126
11127
11128@table @asis
11129
11130@item @code{-gnatwh}
11131
11132@emph{Activate warnings on hiding.}
11133
11134@geindex Hiding of Declarations
11135
11136This switch activates warnings on hiding declarations.
11137A declaration is considered hiding
11138if it is for a non-overloadable entity, and it declares an entity with the
11139same name as some other entity that is directly or use-visible. The default
11140is that such warnings are not generated.
11141@end table
11142
11143@geindex -gnatwH (gcc)
11144
11145
11146@table @asis
11147
11148@item @code{-gnatwH}
11149
11150@emph{Suppress warnings on hiding.}
11151
11152This switch suppresses warnings on hiding declarations.
11153@end table
11154
11155@geindex -gnatw.h (gcc)
11156
11157
11158@table @asis
11159
11160@item @code{-gnatw.h}
11161
11162@emph{Activate warnings on holes/gaps in records.}
11163
11164@geindex Record Representation (gaps)
11165
11166This switch activates warnings on component clauses in record
11167representation clauses that leave holes (gaps) in the record layout.
11168If this warning option is active, then record representation clauses
11169should specify a contiguous layout, adding unused fill fields if needed.
11170@end table
11171
11172@geindex -gnatw.H (gcc)
11173
11174
11175@table @asis
11176
11177@item @code{-gnatw.H}
11178
11179@emph{Suppress warnings on holes/gaps in records.}
11180
11181This switch suppresses warnings on component clauses in record
11182representation clauses that leave holes (haps) in the record layout.
11183@end table
11184
11185@geindex -gnatwi (gcc)
11186
11187
11188@table @asis
11189
11190@item @code{-gnatwi}
11191
11192@emph{Activate warnings on implementation units.}
11193
11194This switch activates warnings for a @emph{with} of an internal GNAT
11195implementation unit, defined as any unit from the @cite{Ada},
11196@cite{Interfaces}, @cite{GNAT},
11197or @cite{System}
11198hierarchies that is not
11199documented in either the Ada Reference Manual or the GNAT
11200Programmer's Reference Manual. Such units are intended only
11201for internal implementation purposes and should not be @emph{with}ed
11202by user programs. The default is that such warnings are generated
11203@end table
11204
11205@geindex -gnatwI (gcc)
11206
11207
11208@table @asis
11209
11210@item @code{-gnatwI}
11211
11212@emph{Disable warnings on implementation units.}
11213
11214This switch disables warnings for a @emph{with} of an internal GNAT
11215implementation unit.
11216@end table
11217
11218@geindex -gnatw.i (gcc)
11219
11220
11221@table @asis
11222
11223@item @code{-gnatw.i}
11224
11225@emph{Activate warnings on overlapping actuals.}
11226
11227This switch enables a warning on statically detectable overlapping actuals in
11228a subprogram call, when one of the actuals is an in-out parameter, and the
11229types of the actuals are not by-copy types. This warning is off by default.
11230@end table
11231
11232@geindex -gnatw.I (gcc)
11233
11234
11235@table @asis
11236
11237@item @code{-gnatw.I}
11238
11239@emph{Disable warnings on overlapping actuals.}
11240
11241This switch disables warnings on overlapping actuals in a call..
11242@end table
11243
11244@geindex -gnatwj (gcc)
11245
11246
11247@table @asis
11248
11249@item @code{-gnatwj}
11250
11251@emph{Activate warnings on obsolescent features (Annex J).}
11252
11253@geindex Features
11254@geindex obsolescent
11255
11256@geindex Obsolescent features
11257
11258If this warning option is activated, then warnings are generated for
11259calls to subprograms marked with @cite{pragma Obsolescent} and
11260for use of features in Annex J of the Ada Reference Manual. In the
11261case of Annex J, not all features are flagged. In particular use
11262of the renamed packages (like @cite{Text_IO}) and use of package
11263@cite{ASCII} are not flagged, since these are very common and
11264would generate many annoying positive warnings. The default is that
11265such warnings are not generated.
11266
11267In addition to the above cases, warnings are also generated for
11268GNAT features that have been provided in past versions but which
11269have been superseded (typically by features in the new Ada standard).
11270For example, @cite{pragma Ravenscar} will be flagged since its
11271function is replaced by @cite{pragma Profile(Ravenscar)}, and
11272@cite{pragma Interface_Name} will be flagged since its function
11273is replaced by @cite{pragma Import}.
11274
11275Note that this warning option functions differently from the
11276restriction @cite{No_Obsolescent_Features} in two respects.
11277First, the restriction applies only to annex J features.
11278Second, the restriction does flag uses of package @cite{ASCII}.
11279
11280@item @code{-gnatwJ}
11281
11282@emph{Suppress warnings on obsolescent features (Annex J).}
11283.. index:: -gnatwJ  (gcc)
11284
11285This switch disables warnings on use of obsolescent features.
11286
11287@item @code{-gnatwk}
11288
11289@emph{Activate warnings on variables that could be constants.}
11290.. index:: -gnatwk  (gcc)
11291
11292This switch activates warnings for variables that are initialized but
11293never modified, and then could be declared constants. The default is that
11294such warnings are not given.
11295@end table
11296
11297@geindex -gnatwK (gcc)
11298
11299
11300@table @asis
11301
11302@item @code{-gnatwK}
11303
11304@emph{Suppress warnings on variables that could be constants.}
11305
11306This switch disables warnings on variables that could be declared constants.
11307@end table
11308
11309@geindex -gnatw.k (gcc)
11310
11311
11312@table @asis
11313
11314@item @code{-gnatw.k}
11315
11316@emph{Activate warnings on redefinition of names in standard.}
11317
11318This switch activates warnings for declarations that declare a name that
11319is defined in package Standard. Such declarations can be confusing,
11320especially since the names in package Standard continue to be directly
11321visible, meaning that use visibiliy on such redeclared names does not
11322work as expected. Names of discriminants and components in records are
11323not included in this check.
11324@end table
11325
11326@geindex -gnatwK (gcc)
11327
11328
11329@table @asis
11330
11331@item @code{-gnatw.K}
11332
11333@emph{Suppress warnings on redefinition of names in standard.}
11334
11335This switch activates warnings for declarations that declare a name that
11336is defined in package Standard.
11337@end table
11338
11339@geindex -gnatwl (gcc)
11340
11341
11342@table @asis
11343
11344@item @code{-gnatwl}
11345
11346@emph{Activate warnings for elaboration pragmas.}
11347
11348@geindex Elaboration
11349@geindex warnings
11350
11351This switch activates warnings for possible elaboration problems,
11352including suspicious use
11353of @cite{Elaborate} pragmas, when using the static elaboration model, and
11354possible situations that may raise @cite{Program_Error} when using the
11355dynamic elaboration model.
11356See the section in this guide on elaboration checking for further details.
11357The default is that such warnings
11358are not generated.
11359@end table
11360
11361@geindex -gnatwL (gcc)
11362
11363
11364@table @asis
11365
11366@item @code{-gnatwL}
11367
11368@emph{Suppress warnings for elaboration pragmas.}
11369
11370This switch suppresses warnings for possible elaboration problems.
11371@end table
11372
11373@geindex -gnatw.l (gcc)
11374
11375
11376@table @asis
11377
11378@item @code{-gnatw.l}
11379
11380@emph{List inherited aspects.}
11381
11382This switch causes the compiler to list inherited invariants,
11383preconditions, and postconditions from Type_Invariant'Class, Invariant'Class,
11384Pre'Class, and Post'Class aspects. Also list inherited subtype predicates.
11385@end table
11386
11387@geindex -gnatw.L (gcc)
11388
11389
11390@table @asis
11391
11392@item @code{-gnatw.L}
11393
11394@emph{Suppress listing of inherited aspects.}
11395
11396This switch suppresses listing of inherited aspects.
11397@end table
11398
11399@geindex -gnatwm (gcc)
11400
11401
11402@table @asis
11403
11404@item @code{-gnatwm}
11405
11406@emph{Activate warnings on modified but unreferenced variables.}
11407
11408This switch activates warnings for variables that are assigned (using
11409an initialization value or with one or more assignment statements) but
11410whose value is never read. The warning is suppressed for volatile
11411variables and also for variables that are renamings of other variables
11412or for which an address clause is given.
11413The default is that these warnings are not given.
11414@end table
11415
11416@geindex -gnatwM (gcc)
11417
11418
11419@table @asis
11420
11421@item @code{-gnatwM}
11422
11423@emph{Disable warnings on modified but unreferenced variables.}
11424
11425This switch disables warnings for variables that are assigned or
11426initialized, but never read.
11427@end table
11428
11429@geindex -gnatw.m (gcc)
11430
11431
11432@table @asis
11433
11434@item @code{-gnatw.m}
11435
11436@emph{Activate warnings on suspicious modulus values.}
11437
11438This switch activates warnings for modulus values that seem suspicious.
11439The cases caught are where the size is the same as the modulus (e.g.
11440a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
11441with no size clause. The guess in both cases is that 2**x was intended
11442rather than x. In addition expressions of the form 2*x for small x
11443generate a warning (the almost certainly accurate guess being that
114442**x was intended). The default is that these warnings are given.
11445@end table
11446
11447@geindex -gnatw.M (gcc)
11448
11449
11450@table @asis
11451
11452@item @code{-gnatw.M}
11453
11454@emph{Disable warnings on suspicious modulus values.}
11455
11456This switch disables warnings for suspicious modulus values.
11457@end table
11458
11459@geindex -gnatwn (gcc)
11460
11461
11462@table @asis
11463
11464@item @code{-gnatwn}
11465
11466@emph{Set normal warnings mode.}
11467
11468This switch sets normal warning mode, in which enabled warnings are
11469issued and treated as warnings rather than errors. This is the default
11470mode. the switch @emph{-gnatwn} can be used to cancel the effect of
11471an explicit @emph{-gnatws} or
11472@emph{-gnatwe}. It also cancels the effect of the
11473implicit @emph{-gnatwe} that is activated by the
11474use of @emph{-gnatg}.
11475@end table
11476
11477@geindex -gnatw.n (gcc)
11478
11479@geindex Atomic Synchronization
11480@geindex warnings
11481
11482
11483@table @asis
11484
11485@item @code{-gnatw.n}
11486
11487@emph{Activate warnings on atomic synchronization.}
11488
11489This switch actives warnings when an access to an atomic variable
11490requires the generation of atomic synchronization code. These
11491warnings are off by default.
11492@end table
11493
11494@geindex -gnatw.N (gcc)
11495
11496
11497@table @asis
11498
11499@item @code{-gnatw.N}
11500
11501@emph{Suppress warnings on atomic synchronization.}
11502
11503@geindex Atomic Synchronization
11504@geindex warnings
11505
11506This switch suppresses warnings when an access to an atomic variable
11507requires the generation of atomic synchronization code.
11508@end table
11509
11510@geindex -gnatwo (gcc)
11511
11512@geindex Address Clauses
11513@geindex warnings
11514
11515
11516@table @asis
11517
11518@item @code{-gnatwo}
11519
11520@emph{Activate warnings on address clause overlays.}
11521
11522This switch activates warnings for possibly unintended initialization
11523effects of defining address clauses that cause one variable to overlap
11524another. The default is that such warnings are generated.
11525@end table
11526
11527@geindex -gnatwO (gcc)
11528
11529
11530@table @asis
11531
11532@item @code{-gnatwO}
11533
11534@emph{Suppress warnings on address clause overlays.}
11535
11536This switch suppresses warnings on possibly unintended initialization
11537effects of defining address clauses that cause one variable to overlap
11538another.
11539@end table
11540
11541@geindex -gnatw.o (gcc)
11542
11543
11544@table @asis
11545
11546@item @code{-gnatw.o}
11547
11548@emph{Activate warnings on modified but unreferenced out parameters.}
11549
11550This switch activates warnings for variables that are modified by using
11551them as actuals for a call to a procedure with an out mode formal, where
11552the resulting assigned value is never read. It is applicable in the case
11553where there is more than one out mode formal. If there is only one out
11554mode formal, the warning is issued by default (controlled by -gnatwu).
11555The warning is suppressed for volatile
11556variables and also for variables that are renamings of other variables
11557or for which an address clause is given.
11558The default is that these warnings are not given.
11559@end table
11560
11561@geindex -gnatw.O (gcc)
11562
11563
11564@table @asis
11565
11566@item @code{-gnatw.O}
11567
11568@emph{Disable warnings on modified but unreferenced out parameters.}
11569
11570This switch suppresses warnings for variables that are modified by using
11571them as actuals for a call to a procedure with an out mode formal, where
11572the resulting assigned value is never read.
11573@end table
11574
11575@geindex -gnatwp (gcc)
11576
11577@geindex Inlining
11578@geindex warnings
11579
11580
11581@table @asis
11582
11583@item @code{-gnatwp}
11584
11585@emph{Activate warnings on ineffective pragma Inlines.}
11586
11587This switch activates warnings for failure of front end inlining
11588(activated by @emph{-gnatN}) to inline a particular call. There are
11589many reasons for not being able to inline a call, including most
11590commonly that the call is too complex to inline. The default is
11591that such warnings are not given.
11592Warnings on ineffective inlining by the gcc back-end can be activated
11593separately, using the gcc switch -Winline.
11594@end table
11595
11596@geindex -gnatwP (gcc)
11597
11598
11599@table @asis
11600
11601@item @code{-gnatwP}
11602
11603@emph{Suppress warnings on ineffective pragma Inlines.}
11604
11605This switch suppresses warnings on ineffective pragma Inlines. If the
11606inlining mechanism cannot inline a call, it will simply ignore the
11607request silently.
11608@end table
11609
11610@geindex -gnatw.p (gcc)
11611
11612@geindex Parameter order
11613@geindex warnings
11614
11615
11616@table @asis
11617
11618@item @code{-gnatw.p}
11619
11620@emph{Activate warnings on parameter ordering.}
11621
11622This switch activates warnings for cases of suspicious parameter
11623ordering when the list of arguments are all simple identifiers that
11624match the names of the formals, but are in a different order. The
11625warning is suppressed if any use of named parameter notation is used,
11626so this is the appropriate way to suppress a false positive (and
11627serves to emphasize that the "misordering" is deliberate). The
11628default is that such warnings are not given.
11629@end table
11630
11631@geindex -gnatw.P (gcc)
11632
11633
11634@table @asis
11635
11636@item @code{-gnatw.P}
11637
11638@emph{Suppress warnings on parameter ordering.}
11639
11640This switch suppresses warnings on cases of suspicious parameter
11641ordering.
11642@end table
11643
11644@geindex -gnatwq (gcc)
11645
11646@geindex Parentheses
11647@geindex warnings
11648
11649
11650@table @asis
11651
11652@item @code{-gnatwq}
11653
11654@emph{Activate warnings on questionable missing parentheses.}
11655
11656This switch activates warnings for cases where parentheses are not used and
11657the result is potential ambiguity from a readers point of view. For example
11658(not a > b) when a and b are modular means ((not a) > b) and very likely the
11659programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
11660quite likely ((-x) mod 5) was intended. In such situations it seems best to
11661follow the rule of always parenthesizing to make the association clear, and
11662this warning switch warns if such parentheses are not present. The default
11663is that these warnings are given.
11664@end table
11665
11666@geindex -gnatwQ (gcc)
11667
11668
11669@table @asis
11670
11671@item @code{-gnatwQ}
11672
11673@emph{Suppress warnings on questionable missing parentheses.}
11674
11675This switch suppresses warnings for cases where the association is not
11676clear and the use of parentheses is preferred.
11677@end table
11678
11679@geindex -gnatwr (gcc)
11680
11681
11682@table @asis
11683
11684@item @code{-gnatwr}
11685
11686@emph{Activate warnings on redundant constructs.}
11687
11688This switch activates warnings for redundant constructs. The following
11689is the current list of constructs regarded as redundant:
11690
11691
11692@itemize *
11693
11694@item 
11695Assignment of an item to itself.
11696
11697@item 
11698Type conversion that converts an expression to its own type.
11699
11700@item 
11701Use of the attribute @cite{Base} where @cite{typ'Base} is the same
11702as @cite{typ}.
11703
11704@item 
11705Use of pragma @cite{Pack} when all components are placed by a record
11706representation clause.
11707
11708@item 
11709Exception handler containing only a reraise statement (raise with no
11710operand) which has no effect.
11711
11712@item 
11713Use of the operator abs on an operand that is known at compile time
11714to be non-negative
11715
11716@item 
11717Comparison of boolean expressions to an explicit True value.
11718@end itemize
11719
11720The default is that warnings for redundant constructs are not given.
11721@end table
11722
11723@geindex -gnatwR (gcc)
11724
11725
11726@table @asis
11727
11728@item @code{-gnatwR}
11729
11730@emph{Suppress warnings on redundant constructs.}
11731
11732This switch suppresses warnings for redundant constructs.
11733@end table
11734
11735@geindex -gnatw.r (gcc)
11736
11737
11738@table @asis
11739
11740@item @code{-gnatw.r}
11741
11742@emph{Activate warnings for object renaming function.}
11743
11744This switch activates warnings for an object renaming that renames a
11745function call, which is equivalent to a constant declaration (as
11746opposed to renaming the function itself).  The default is that these
11747warnings are given.
11748@end table
11749
11750@geindex -gnatwT (gcc)
11751
11752
11753@table @asis
11754
11755@item @code{-gnatw.R}
11756
11757@emph{Suppress warnings for object renaming function.}
11758
11759This switch suppresses warnings for object renaming function.
11760@end table
11761
11762@geindex -gnatws (gcc)
11763
11764
11765@table @asis
11766
11767@item @code{-gnatws}
11768
11769@emph{Suppress all warnings.}
11770
11771This switch completely suppresses the
11772output of all warning messages from the GNAT front end, including
11773both warnings that can be controlled by switches described in this
11774section, and those that are normally given unconditionally. The
11775effect of this suppress action can only be cancelled by a subsequent
11776use of the switch @emph{-gnatwn}.
11777
11778Note that switch @emph{-gnatws} does not suppress
11779warnings from the @emph{gcc} back end.
11780To suppress these back end warnings as well, use the switch @emph{-w}
11781in addition to @emph{-gnatws}. Also this switch has no effect on the
11782handling of style check messages.
11783@end table
11784
11785@geindex -gnatw.s (gcc)
11786
11787@geindex Record Representation (component sizes)
11788
11789
11790@table @asis
11791
11792@item @code{-gnatw.s}
11793
11794@emph{Activate warnings on overridden size clauses.}
11795
11796This switch activates warnings on component clauses in record
11797representation clauses where the length given overrides that
11798specified by an explicit size clause for the component type. A
11799warning is similarly given in the array case if a specified
11800component size overrides an explicit size clause for the array
11801component type.
11802@end table
11803
11804@geindex -gnatw.S (gcc)
11805
11806
11807@table @asis
11808
11809@item @code{-gnatw.S}
11810
11811@emph{Suppress warnings on overridden size clauses.}
11812
11813This switch suppresses warnings on component clauses in record
11814representation clauses that override size clauses, and similar
11815warnings when an array component size overrides a size clause.
11816@end table
11817
11818@geindex -gnatwt (gcc)
11819
11820@geindex Deactivated code
11821@geindex warnings
11822
11823@geindex Deleted code
11824@geindex warnings
11825
11826
11827@table @asis
11828
11829@item @code{-gnatwt}
11830
11831@emph{Activate warnings for tracking of deleted conditional code.}
11832
11833This switch activates warnings for tracking of code in conditionals (IF and
11834CASE statements) that is detected to be dead code which cannot be executed, and
11835which is removed by the front end. This warning is off by default. This may be
11836useful for detecting deactivated code in certified applications.
11837@end table
11838
11839@geindex -gnatwT (gcc)
11840
11841
11842@table @asis
11843
11844@item @code{-gnatwT}
11845
11846@emph{Suppress warnings for tracking of deleted conditional code.}
11847
11848This switch suppresses warnings for tracking of deleted conditional code.
11849@end table
11850
11851@geindex -gnatw.t (gcc)
11852
11853
11854@table @asis
11855
11856@item @code{-gnatw.t}
11857
11858@emph{Activate warnings on suspicious contracts.}
11859
11860This switch activates warnings on suspicious contracts. This includes
11861warnings on suspicious postconditions (whether a pragma @cite{Postcondition} or a
11862@cite{Post} aspect in Ada 2012) and suspicious contract cases (pragma or aspect
11863@cite{Contract_Cases}). A function postcondition or contract case is suspicious
11864when no postcondition or contract case for this function mentions the result
11865of the function.  A procedure postcondition or contract case is suspicious
11866when it only refers to the pre-state of the procedure, because in that case
11867it should rather be expressed as a precondition. This switch also controls
11868warnings on suspicious cases of expressions typically found in contracts like
11869quantified expressions and uses of Update attribute. The default is that such
11870warnings are generated.
11871@end table
11872
11873@geindex -gnatw.T (gcc)
11874
11875
11876@table @asis
11877
11878@item @code{-gnatw.T}
11879
11880@emph{Suppress warnings on suspicious contracts.}
11881
11882This switch suppresses warnings on suspicious contracts.
11883@end table
11884
11885@geindex -gnatwu (gcc)
11886
11887
11888@table @asis
11889
11890@item @code{-gnatwu}
11891
11892@emph{Activate warnings on unused entities.}
11893
11894This switch activates warnings to be generated for entities that
11895are declared but not referenced, and for units that are @emph{with}ed
11896and not
11897referenced. In the case of packages, a warning is also generated if
11898no entities in the package are referenced. This means that if a with'ed
11899package is referenced but the only references are in @cite{use}
11900clauses or @cite{renames}
11901declarations, a warning is still generated. A warning is also generated
11902for a generic package that is @emph{with}ed but never instantiated.
11903In the case where a package or subprogram body is compiled, and there
11904is a @emph{with} on the corresponding spec
11905that is only referenced in the body,
11906a warning is also generated, noting that the
11907@emph{with} can be moved to the body. The default is that
11908such warnings are not generated.
11909This switch also activates warnings on unreferenced formals
11910(it includes the effect of @emph{-gnatwf}).
11911@end table
11912
11913@geindex -gnatwU (gcc)
11914
11915
11916@table @asis
11917
11918@item @code{-gnatwU}
11919
11920@emph{Suppress warnings on unused entities.}
11921
11922This switch suppresses warnings for unused entities and packages.
11923It also turns off warnings on unreferenced formals (and thus includes
11924the effect of @emph{-gnatwF}).
11925@end table
11926
11927@geindex -gnatw.u (gcc)
11928
11929
11930@table @asis
11931
11932@item @code{-gnatw.u}
11933
11934@emph{Activate warnings on unordered enumeration types.}
11935
11936This switch causes enumeration types to be considered as conceptually
11937unordered, unless an explicit pragma @cite{Ordered} is given for the type.
11938The effect is to generate warnings in clients that use explicit comparisons
11939or subranges, since these constructs both treat objects of the type as
11940ordered. (A @emph{client} is defined as a unit that is other than the unit in
11941which the type is declared, or its body or subunits.) Please refer to
11942the description of pragma @cite{Ordered} in the
11943@cite{GNAT Reference Manual} for further details.
11944The default is that such warnings are not generated.
11945@end table
11946
11947@geindex -gnatw.U (gcc)
11948
11949
11950@table @asis
11951
11952@item @code{-gnatw.U}
11953
11954@emph{Deactivate warnings on unordered enumeration types.}
11955
11956This switch causes all enumeration types to be considered as ordered, so
11957that no warnings are given for comparisons or subranges for any type.
11958@end table
11959
11960@geindex -gnatwv (gcc)
11961
11962@geindex Unassigned variable warnings
11963
11964
11965@table @asis
11966
11967@item @code{-gnatwv}
11968
11969@emph{Activate warnings on unassigned variables.}
11970
11971This switch activates warnings for access to variables which
11972may not be properly initialized. The default is that
11973such warnings are generated.
11974@end table
11975
11976@geindex -gnatwV (gcc)
11977
11978
11979@table @asis
11980
11981@item @code{-gnatwV}
11982
11983@emph{Suppress warnings on unassigned variables.}
11984
11985This switch suppresses warnings for access to variables which
11986may not be properly initialized.
11987For variables of a composite type, the warning can also be suppressed in
11988Ada 2005 by using a default initialization with a box. For example, if
11989Table is an array of records whose components are only partially uninitialized,
11990then the following code:
11991
11992@example
11993Tab : Table := (others => <>);
11994@end example
11995
11996will suppress warnings on subsequent statements that access components
11997of variable Tab.
11998@end table
11999
12000@geindex -gnatw.v (gcc)
12001
12002@geindex bit order warnings
12003
12004
12005@table @asis
12006
12007@item @code{-gnatw.v}
12008
12009@emph{Activate info messages for non-default bit order.}
12010
12011This switch activates messages (labeled "info", they are not warnings,
12012just informational messages) about the effects of non-default bit-order
12013on records to which a component clause is applied. The effect of specifying
12014non-default bit ordering is a bit subtle (and changed with Ada 2005), so
12015these messages, which are given by default, are useful in understanding the
12016exact consequences of using this feature.
12017@end table
12018
12019@geindex -gnatw.V (gcc)
12020
12021
12022@table @asis
12023
12024@item @code{-gnatw.V}
12025
12026@emph{Suppress info messages for non-default bit order.}
12027
12028This switch suppresses information messages for the effects of specifying
12029non-default bit order on record components with component clauses.
12030@end table
12031
12032@geindex -gnatww (gcc)
12033
12034@geindex String indexing warnings
12035
12036
12037@table @asis
12038
12039@item @code{-gnatww}
12040
12041@emph{Activate warnings on wrong low bound assumption.}
12042
12043This switch activates warnings for indexing an unconstrained string parameter
12044with a literal or S'Length. This is a case where the code is assuming that the
12045low bound is one, which is in general not true (for example when a slice is
12046passed). The default is that such warnings are generated.
12047@end table
12048
12049@geindex -gnatwW (gcc)
12050
12051
12052@table @asis
12053
12054@item @code{-gnatwW}
12055
12056@emph{Suppress warnings on wrong low bound assumption.}
12057
12058This switch suppresses warnings for indexing an unconstrained string parameter
12059with a literal or S'Length. Note that this warning can also be suppressed
12060in a particular case by adding an assertion that the lower bound is 1,
12061as shown in the following example:
12062
12063@example
12064procedure K (S : String) is
12065   pragma Assert (S'First = 1);
12066   ...
12067@end example
12068@end table
12069
12070@geindex -gnatw.w (gcc)
12071
12072@geindex Warnings Off control
12073
12074
12075@table @asis
12076
12077@item @code{-gnatw.w}
12078
12079@emph{Activate warnings on Warnings Off pragmas}
12080
12081This switch activates warnings for use of @cite{pragma Warnings (Off@comma{} entity)}
12082where either the pragma is entirely useless (because it suppresses no
12083warnings), or it could be replaced by @cite{pragma Unreferenced} or
12084@cite{pragma Unmodified}.
12085Also activates warnings for the case of
12086Warnings (Off, String), where either there is no matching
12087Warnings (On, String), or the Warnings (Off) did not suppress any warning.
12088The default is that these warnings are not given.
12089@end table
12090
12091@geindex -gnatw.W (gcc)
12092
12093
12094@table @asis
12095
12096@item @code{-gnatw.W}
12097
12098@emph{Suppress warnings on unnecessary Warnings Off pragmas}
12099
12100This switch suppresses warnings for use of @cite{pragma Warnings (Off@comma{} ...)}.
12101@end table
12102
12103@geindex -gnatwx (gcc)
12104
12105@geindex Export/Import pragma warnings
12106
12107
12108@table @asis
12109
12110@item @code{-gnatwx}
12111
12112@emph{Activate warnings on Export/Import pragmas.}
12113
12114This switch activates warnings on Export/Import pragmas when
12115the compiler detects a possible conflict between the Ada and
12116foreign language calling sequences. For example, the use of
12117default parameters in a convention C procedure is dubious
12118because the C compiler cannot supply the proper default, so
12119a warning is issued. The default is that such warnings are
12120generated.
12121@end table
12122
12123@geindex -gnatwX (gcc)
12124
12125
12126@table @asis
12127
12128@item @code{-gnatwX}
12129
12130@emph{Suppress warnings on Export/Import pragmas.}
12131
12132This switch suppresses warnings on Export/Import pragmas.
12133The sense of this is that you are telling the compiler that
12134you know what you are doing in writing the pragma, and it
12135should not complain at you.
12136@end table
12137
12138@geindex -gnatwm (gcc)
12139
12140
12141@table @asis
12142
12143@item @code{-gnatw.x}
12144
12145@emph{Activate warnings for No_Exception_Propagation mode.}
12146
12147This switch activates warnings for exception usage when pragma Restrictions
12148(No_Exception_Propagation) is in effect. Warnings are given for implicit or
12149explicit exception raises which are not covered by a local handler, and for
12150exception handlers which do not cover a local raise. The default is that these
12151warnings are not given.
12152
12153@item @code{-gnatw.X}
12154
12155@emph{Disable warnings for No_Exception_Propagation mode.}
12156
12157This switch disables warnings for exception usage when pragma Restrictions
12158(No_Exception_Propagation) is in effect.
12159@end table
12160
12161@geindex -gnatwy (gcc)
12162
12163@geindex Ada compatibility issues warnings
12164
12165
12166@table @asis
12167
12168@item @code{-gnatwy}
12169
12170@emph{Activate warnings for Ada compatibility issues.}
12171
12172For the most part, newer versions of Ada are upwards compatible
12173with older versions. For example, Ada 2005 programs will almost
12174always work when compiled as Ada 2012.
12175However there are some exceptions (for example the fact that
12176@cite{some} is now a reserved word in Ada 2012). This
12177switch activates several warnings to help in identifying
12178and correcting such incompatibilities. The default is that
12179these warnings are generated. Note that at one point Ada 2005
12180was called Ada 0Y, hence the choice of character.
12181@end table
12182
12183@geindex -gnatwY (gcc)
12184
12185@geindex Ada compatibility issues warnings
12186
12187
12188@table @asis
12189
12190@item @code{-gnatwY}
12191
12192@emph{Disable warnings for Ada compatibility issues.}
12193
12194This switch suppresses the warnings intended to help in identifying
12195incompatibilities between Ada language versions.
12196@end table
12197
12198@geindex -gnatw.y (gcc)
12199
12200@geindex Package spec needing body
12201
12202
12203@table @asis
12204
12205@item @code{-gnatw.y}
12206
12207@emph{Activate information messages for why package spec needs body}
12208
12209There are a number of cases in which a package spec needs a body.
12210For example, the use of pragma Elaborate_Body, or the declaration
12211of a procedure specification requiring a completion. This switch
12212causes information messages to be output showing why a package
12213specification requires a body. This can be useful in the case of
12214a large package specification which is unexpectedly requiring a
12215body. The default is that such information messages are not output.
12216@end table
12217
12218@geindex -gnatw.Y (gcc)
12219
12220@geindex No information messages for why package spec needs body
12221
12222
12223@table @asis
12224
12225@item @code{-gnatw.Y}
12226
12227@emph{Disable information messages for why package spec needs body}
12228
12229This switch suppresses the output of information messages showing why
12230a package specification needs a body.
12231@end table
12232
12233@geindex -gnatwz (gcc)
12234
12235@geindex Unchecked_Conversion warnings
12236
12237
12238@table @asis
12239
12240@item @code{-gnatwz}
12241
12242@emph{Activate warnings on unchecked conversions.}
12243
12244This switch activates warnings for unchecked conversions
12245where the types are known at compile time to have different
12246sizes. The default is that such warnings are generated. Warnings are also
12247generated for subprogram pointers with different conventions.
12248@end table
12249
12250@geindex -gnatwZ (gcc)
12251
12252
12253@table @asis
12254
12255@item @code{-gnatwZ}
12256
12257@emph{Suppress warnings on unchecked conversions.}
12258
12259This switch suppresses warnings for unchecked conversions
12260where the types are known at compile time to have different
12261sizes or conventions.
12262@end table
12263
12264@geindex -gnatw.z (gcc)
12265
12266@geindex Size/Alignment warnings
12267
12268
12269@table @asis
12270
12271@item @code{-gnatw.z}
12272
12273@emph{Activate warnings for size not a multiple of alignment.}
12274
12275This switch activates warnings for cases of record types with
12276specified @cite{Size} and @cite{Alignment} attributes where the
12277size is not a multiple of the alignment, resulting in an object
12278size that is greater than the specified size. The default
12279is that such warnings are generated.
12280@end table
12281
12282@geindex -gnatw.Z (gcc)
12283
12284@geindex Size/Alignment warnings
12285
12286
12287@table @asis
12288
12289@item @code{-gnatw.Z}
12290
12291@emph{Suppress warnings for size not a multiple of alignment.}
12292
12293This switch suppresses warnings for cases of record types with
12294specified @cite{Size} and @cite{Alignment} attributes where the
12295size is not a multiple of the alignment, resulting in an object
12296size that is greater than the specified size.
12297The warning can also be
12298suppressed by giving an explicit @cite{Object_Size} value.
12299@end table
12300
12301@geindex -Wunused (gcc)
12302
12303
12304@table @asis
12305
12306@item @code{-Wunused}
12307
12308The warnings controlled by the @emph{-gnatw} switch are generated by
12309the front end of the compiler. The @emph{GCC} back end can provide
12310additional warnings and they are controlled by the @emph{-W} switch.
12311For example, @emph{-Wunused} activates back end
12312warnings for entities that are declared but not referenced.
12313@end table
12314
12315@geindex -Wuninitialized (gcc)
12316
12317
12318@table @asis
12319
12320@item @code{-Wuninitialized}
12321
12322Similarly, @emph{-Wuninitialized} activates
12323the back end warning for uninitialized variables. This switch must be
12324used in conjunction with an optimization level greater than zero.
12325@end table
12326
12327@geindex -Wstack-usage (gcc)
12328
12329
12330@table @asis
12331
12332@item @code{-Wstack-usage=@emph{len}}
12333
12334Warn if the stack usage of a subprogram might be larger than @cite{len} bytes.
12335See @ref{fa,,Static Stack Usage Analysis} for details.
12336@end table
12337
12338@geindex -Wall (gcc)
12339
12340
12341@table @asis
12342
12343@item @code{-Wall}
12344
12345This switch enables most warnings from the @emph{GCC} back end.
12346The code generator detects a number of warning situations that are missed
12347by the @emph{GNAT} front end, and this switch can be used to activate them.
12348The use of this switch also sets the default front end warning mode to
12349@emph{-gnatwa}, that is, most front end warnings activated as well.
12350@end table
12351
12352@geindex -w (gcc)
12353
12354
12355@table @asis
12356
12357@item @code{-w}
12358
12359Conversely, this switch suppresses warnings from the @emph{GCC} back end.
12360The use of this switch also sets the default front end warning mode to
12361@emph{-gnatws}, that is, front end warnings suppressed as well.
12362@end table
12363
12364@geindex -Werror (gcc)
12365
12366
12367@table @asis
12368
12369@item @code{-Werror}
12370
12371This switch causes warnings from the @emph{GCC} back end to be treated as
12372errors.  The warning string still appears, but the warning messages are
12373counted as errors, and prevent the generation of an object file.
12374@end table
12375
12376A string of warning parameters can be used in the same parameter. For example:
12377
12378@example
12379-gnatwaGe
12380@end example
12381
12382will turn on all optional warnings except for unrecognized pragma warnings,
12383and also specify that warnings should be treated as errors.
12384
12385When no switch @emph{-gnatw} is used, this is equivalent to:
12386
12387@quotation
12388
12389
12390@itemize *
12391
12392@item 
12393@code{-gnatw.a}
12394
12395@item 
12396@code{-gnatwB}
12397
12398@item 
12399@code{-gnatw.b}
12400
12401@item 
12402@code{-gnatwC}
12403
12404@item 
12405@code{-gnatw.C}
12406
12407@item 
12408@code{-gnatwD}
12409
12410@item 
12411@code{-gnatwF}
12412
12413@item 
12414@code{-gnatwg}
12415
12416@item 
12417@code{-gnatwH}
12418
12419@item 
12420@code{-gnatwi}
12421
12422@item 
12423@code{-gnatw.I}
12424
12425@item 
12426@code{-gnatwJ}
12427
12428@item 
12429@code{-gnatwK}
12430
12431@item 
12432@code{-gnatwL}
12433
12434@item 
12435@code{-gnatw.L}
12436
12437@item 
12438@code{-gnatwM}
12439
12440@item 
12441@code{-gnatw.m}
12442
12443@item 
12444@code{-gnatwn}
12445
12446@item 
12447@code{-gnatwo}
12448
12449@item 
12450@code{-gnatw.O}
12451
12452@item 
12453@code{-gnatwP}
12454
12455@item 
12456@code{-gnatw.P}
12457
12458@item 
12459@code{-gnatwq}
12460
12461@item 
12462@code{-gnatwR}
12463
12464@item 
12465@code{-gnatw.R}
12466
12467@item 
12468@code{-gnatw.S}
12469
12470@item 
12471@code{-gnatwT}
12472
12473@item 
12474@code{-gnatw.T}
12475
12476@item 
12477@code{-gnatwU}
12478
12479@item 
12480@code{-gnatwv}
12481
12482@item 
12483@code{-gnatww}
12484
12485@item 
12486@code{-gnatw.W}
12487
12488@item 
12489@code{-gnatwx}
12490
12491@item 
12492@code{-gnatw.X}
12493
12494@item 
12495@code{-gnatwy}
12496
12497@item 
12498@code{-gnatwz}
12499@end itemize
12500@end quotation
12501
12502@node Debugging and Assertion Control,Validity Checking,Warning Message Control,Compiler Switches
12503@anchor{gnat_ugn/building_executable_programs_with_gnat debugging-and-assertion-control}@anchor{105}@anchor{gnat_ugn/building_executable_programs_with_gnat id16}@anchor{106}
12504@subsection Debugging and Assertion Control
12505
12506
12507@geindex -gnata (gcc)
12508
12509
12510@table @asis
12511
12512@item @code{-gnata}
12513
12514@geindex Assert
12515
12516@geindex Debug
12517
12518@geindex Assertions
12519
12520The pragmas @cite{Assert} and @cite{Debug} normally have no effect and
12521are ignored. This switch, where @code{a} stands for assert, causes
12522@cite{Assert} and @cite{Debug} pragmas to be activated.
12523
12524The pragmas have the form:
12525
12526@example
12527pragma Assert (<Boolean-expression> [, <static-string-expression>])
12528pragma Debug (<procedure call>)
12529@end example
12530
12531The @cite{Assert} pragma causes @cite{Boolean-expression} to be tested.
12532If the result is @cite{True}, the pragma has no effect (other than
12533possible side effects from evaluating the expression). If the result is
12534@cite{False}, the exception @cite{Assert_Failure} declared in the package
12535@cite{System.Assertions} is
12536raised (passing @cite{static-string-expression}, if present, as the
12537message associated with the exception). If no string expression is
12538given the default is a string giving the file name and line number
12539of the pragma.
12540
12541The @cite{Debug} pragma causes @cite{procedure} to be called. Note that
12542@cite{pragma Debug} may appear within a declaration sequence, allowing
12543debugging procedures to be called between declarations.
12544@end table
12545
12546@node Validity Checking,Style Checking,Debugging and Assertion Control,Compiler Switches
12547@anchor{gnat_ugn/building_executable_programs_with_gnat validity-checking}@anchor{fb}@anchor{gnat_ugn/building_executable_programs_with_gnat id17}@anchor{107}
12548@subsection Validity Checking
12549
12550
12551@geindex Validity Checking
12552
12553The Ada Reference Manual defines the concept of invalid values (see
12554RM 13.9.1). The primary source of invalid values is uninitialized
12555variables. A scalar variable that is left uninitialized may contain
12556an invalid value; the concept of invalid does not apply to access or
12557composite types.
12558
12559It is an error to read an invalid value, but the RM does not require
12560run-time checks to detect such errors, except for some minimal
12561checking to prevent erroneous execution (i.e. unpredictable
12562behavior). This corresponds to the @emph{-gnatVd} switch below,
12563which is the default. For example, by default, if the expression of a
12564case statement is invalid, it will raise Constraint_Error rather than
12565causing a wild jump, and if an array index on the left-hand side of an
12566assignment is invalid, it will raise Constraint_Error rather than
12567overwriting an arbitrary memory location.
12568
12569The @emph{-gnatVa} may be used to enable additional validity checks,
12570which are not required by the RM. These checks are often very
12571expensive (which is why the RM does not require them). These checks
12572are useful in tracking down uninitialized variables, but they are
12573not usually recommended for production builds, and in particular
12574we do not recommend using these extra validity checking options in
12575combination with optimization, since this can confuse the optimizer.
12576If performance is a consideration, leading to the need to optimize,
12577then the validity checking options should not be used.
12578
12579The other @emph{-gnatV}@code{x} switches below allow finer-grained
12580control; you can enable whichever validity checks you desire. However,
12581for most debugging purposes, @emph{-gnatVa} is sufficient, and the
12582default @emph{-gnatVd} (i.e. standard Ada behavior) is usually
12583sufficient for non-debugging use.
12584
12585The @emph{-gnatB} switch tells the compiler to assume that all
12586values are valid (that is, within their declared subtype range)
12587except in the context of a use of the Valid attribute. This means
12588the compiler can generate more efficient code, since the range
12589of values is better known at compile time. However, an uninitialized
12590variable can cause wild jumps and memory corruption in this mode.
12591
12592The @emph{-gnatV}@code{x} switch allows control over the validity
12593checking mode as described below.
12594The @code{x} argument is a string of letters that
12595indicate validity checks that are performed or not performed in addition
12596to the default checks required by Ada as described above.
12597
12598@geindex -gnatVa (gcc)
12599
12600
12601@table @asis
12602
12603@item @code{-gnatVa}
12604
12605@emph{All validity checks.}
12606
12607All validity checks are turned on.
12608That is, @emph{-gnatVa} is
12609equivalent to @emph{gnatVcdfimorst}.
12610@end table
12611
12612@geindex -gnatVc (gcc)
12613
12614
12615@table @asis
12616
12617@item @code{-gnatVc}
12618
12619@emph{Validity checks for copies.}
12620
12621The right hand side of assignments, and the initializing values of
12622object declarations are validity checked.
12623@end table
12624
12625@geindex -gnatVd (gcc)
12626
12627
12628@table @asis
12629
12630@item @code{-gnatVd}
12631
12632@emph{Default (RM) validity checks.}
12633
12634Some validity checks are done by default following normal Ada semantics
12635(RM 13.9.1 (9-11)).
12636A check is done in case statements that the expression is within the range
12637of the subtype. If it is not, Constraint_Error is raised.
12638For assignments to array components, a check is done that the expression used
12639as index is within the range. If it is not, Constraint_Error is raised.
12640Both these validity checks may be turned off using switch @emph{-gnatVD}.
12641They are turned on by default. If @emph{-gnatVD} is specified, a subsequent
12642switch @emph{-gnatVd} will leave the checks turned on.
12643Switch @emph{-gnatVD} should be used only if you are sure that all such
12644expressions have valid values. If you use this switch and invalid values
12645are present, then the program is erroneous, and wild jumps or memory
12646overwriting may occur.
12647@end table
12648
12649@geindex -gnatVe (gcc)
12650
12651
12652@table @asis
12653
12654@item @code{-gnatVe}
12655
12656@emph{Validity checks for elementary components.}
12657
12658In the absence of this switch, assignments to record or array components are
12659not validity checked, even if validity checks for assignments generally
12660(@emph{-gnatVc}) are turned on. In Ada, assignment of composite values do not
12661require valid data, but assignment of individual components does. So for
12662example, there is a difference between copying the elements of an array with a
12663slice assignment, compared to assigning element by element in a loop. This
12664switch allows you to turn off validity checking for components, even when they
12665are assigned component by component.
12666@end table
12667
12668@geindex -gnatVf (gcc)
12669
12670
12671@table @asis
12672
12673@item @code{-gnatVf}
12674
12675@emph{Validity checks for floating-point values.}
12676
12677In the absence of this switch, validity checking occurs only for discrete
12678values. If @emph{-gnatVf} is specified, then validity checking also applies
12679for floating-point values, and NaNs and infinities are considered invalid,
12680as well as out of range values for constrained types. Note that this means
12681that standard IEEE infinity mode is not allowed. The exact contexts
12682in which floating-point values are checked depends on the setting of other
12683options. For example, @emph{-gnatVif} or @emph{-gnatVfi}
12684(the order does not matter) specifies that floating-point parameters of mode
12685@cite{in} should be validity checked.
12686@end table
12687
12688@geindex -gnatVi (gcc)
12689
12690
12691@table @asis
12692
12693@item @code{-gnatVi}
12694
12695@emph{Validity checks for `in} mode parameters`
12696
12697Arguments for parameters of mode @cite{in} are validity checked in function
12698and procedure calls at the point of call.
12699@end table
12700
12701@geindex -gnatVm (gcc)
12702
12703
12704@table @asis
12705
12706@item @code{-gnatVm}
12707
12708@emph{Validity checks for `in out} mode parameters.`
12709
12710Arguments for parameters of mode @cite{in out} are validity checked in
12711procedure calls at the point of call. The @cite{'m'} here stands for
12712modify, since this concerns parameters that can be modified by the call.
12713Note that there is no specific option to test @cite{out} parameters,
12714but any reference within the subprogram will be tested in the usual
12715manner, and if an invalid value is copied back, any reference to it
12716will be subject to validity checking.
12717@end table
12718
12719@geindex -gnatVn (gcc)
12720
12721
12722@table @asis
12723
12724@item @code{-gnatVn}
12725
12726@emph{No validity checks.}
12727
12728This switch turns off all validity checking, including the default checking
12729for case statements and left hand side subscripts. Note that the use of
12730the switch @emph{-gnatp} suppresses all run-time checks, including
12731validity checks, and thus implies @emph{-gnatVn}. When this switch
12732is used, it cancels any other @emph{-gnatV} previously issued.
12733
12734@item @code{-gnatVo}
12735
12736@emph{Validity checks for operator and attribute operands.}
12737.. index:: -gnatVo  (gcc)
12738
12739Arguments for predefined operators and attributes are validity checked.
12740This includes all operators in package @cite{Standard},
12741the shift operators defined as intrinsic in package @cite{Interfaces}
12742and operands for attributes such as @cite{Pos}. Checks are also made
12743on individual component values for composite comparisons, and on the
12744expressions in type conversions and qualified expressions. Checks are
12745also made on explicit ranges using @code{..} (e.g., slices, loops etc).
12746@end table
12747
12748@geindex -gnatVp (gcc)
12749
12750
12751@table @asis
12752
12753@item @code{-gnatVp}
12754
12755@emph{Validity checks for parameters.}
12756
12757This controls the treatment of parameters within a subprogram (as opposed
12758to @emph{-gnatVi} and @emph{-gnatVm} which control validity testing
12759of parameters on a call. If either of these call options is used, then
12760normally an assumption is made within a subprogram that the input arguments
12761have been validity checking at the point of call, and do not need checking
12762again within a subprogram). If @emph{-gnatVp} is set, then this assumption
12763is not made, and parameters are not assumed to be valid, so their validity
12764will be checked (or rechecked) within the subprogram.
12765@end table
12766
12767@geindex -gnatVr (gcc)
12768
12769
12770@table @asis
12771
12772@item @code{-gnatVr}
12773
12774@emph{Validity checks for function returns.}
12775
12776The expression in @cite{return} statements in functions is validity
12777checked.
12778@end table
12779
12780@geindex -gnatVs (gcc)
12781
12782
12783@table @asis
12784
12785@item @code{-gnatVs}
12786
12787@emph{Validity checks for subscripts.}
12788
12789All subscripts expressions are checked for validity, whether they appear
12790on the right side or left side (in default mode only left side subscripts
12791are validity checked).
12792@end table
12793
12794@geindex -gnatVt (gcc)
12795
12796
12797@table @asis
12798
12799@item @code{-gnatVt}
12800
12801@emph{Validity checks for tests.}
12802
12803Expressions used as conditions in @cite{if}, @cite{while} or @cite{exit}
12804statements are checked, as well as guard expressions in entry calls.
12805@end table
12806
12807The @emph{-gnatV} switch may be followed by a string of letters
12808to turn on a series of validity checking options.
12809For example, @code{-gnatVcr}
12810specifies that in addition to the default validity checking, copies and
12811function return expressions are to be validity checked.
12812In order to make it easier to specify the desired combination of effects,
12813the upper case letters @cite{CDFIMORST} may
12814be used to turn off the corresponding lower case option.
12815Thus @code{-gnatVaM} turns on all validity checking options except for
12816checking of @cite{**in out**} procedure arguments.
12817
12818The specification of additional validity checking generates extra code (and
12819in the case of @emph{-gnatVa} the code expansion can be substantial).
12820However, these additional checks can be very useful in detecting
12821uninitialized variables, incorrect use of unchecked conversion, and other
12822errors leading to invalid values. The use of pragma @cite{Initialize_Scalars}
12823is useful in conjunction with the extra validity checking, since this
12824ensures that wherever possible uninitialized variables have invalid values.
12825
12826See also the pragma @cite{Validity_Checks} which allows modification of
12827the validity checking mode at the program source level, and also allows for
12828temporary disabling of validity checks.
12829
12830@node Style Checking,Run-Time Checks,Validity Checking,Compiler Switches
12831@anchor{gnat_ugn/building_executable_programs_with_gnat id18}@anchor{108}@anchor{gnat_ugn/building_executable_programs_with_gnat style-checking}@anchor{100}
12832@subsection Style Checking
12833
12834
12835@geindex Style checking
12836
12837@geindex -gnaty (gcc)
12838
12839The @emph{-gnatyx} switch causes the compiler to
12840enforce specified style rules. A limited set of style rules has been used
12841in writing the GNAT sources themselves. This switch allows user programs
12842to activate all or some of these checks. If the source program fails a
12843specified style check, an appropriate message is given, preceded by
12844the character sequence '(style)'. This message does not prevent
12845successful compilation (unless the @emph{-gnatwe} switch is used).
12846
12847Note that this is by no means intended to be a general facility for
12848checking arbitrary coding standards. It is simply an embedding of the
12849style rules we have chosen for the GNAT sources. If you are starting
12850a project which does not have established style standards, you may
12851find it useful to adopt the entire set of GNAT coding standards, or
12852some subset of them.
12853
12854
12855The string @cite{x} is a sequence of letters or digits
12856indicating the particular style
12857checks to be performed. The following checks are defined:
12858
12859@geindex -gnaty[0-9] (gcc)
12860
12861
12862@table @asis
12863
12864@item @code{-gnaty0}
12865
12866@emph{Specify indentation level.}
12867
12868If a digit from 1-9 appears
12869in the string after @emph{-gnaty}
12870then proper indentation is checked, with the digit indicating the
12871indentation level required. A value of zero turns off this style check.
12872The general style of required indentation is as specified by
12873the examples in the Ada Reference Manual. Full line comments must be
12874aligned with the @cite{--} starting on a column that is a multiple of
12875the alignment level, or they may be aligned the same way as the following
12876non-blank line (this is useful when full line comments appear in the middle
12877of a statement, or they may be aligned with the source line on the previous
12878non-blank line.
12879@end table
12880
12881@geindex -gnatya (gcc)
12882
12883
12884@table @asis
12885
12886@item @code{-gnatya}
12887
12888@emph{Check attribute casing.}
12889
12890Attribute names, including the case of keywords such as @cite{digits}
12891used as attributes names, must be written in mixed case, that is, the
12892initial letter and any letter following an underscore must be uppercase.
12893All other letters must be lowercase.
12894@end table
12895
12896@geindex -gnatyA (gcc)
12897
12898
12899@table @asis
12900
12901@item @code{-gnatyA}
12902
12903@emph{Use of array index numbers in array attributes.}
12904
12905When using the array attributes First, Last, Range,
12906or Length, the index number must be omitted for one-dimensional arrays
12907and is required for multi-dimensional arrays.
12908@end table
12909
12910@geindex -gnatyb (gcc)
12911
12912
12913@table @asis
12914
12915@item @code{-gnatyb}
12916
12917@emph{Blanks not allowed at statement end.}
12918
12919Trailing blanks are not allowed at the end of statements. The purpose of this
12920rule, together with h (no horizontal tabs), is to enforce a canonical format
12921for the use of blanks to separate source tokens.
12922@end table
12923
12924@geindex -gnatyB (gcc)
12925
12926
12927@table @asis
12928
12929@item @code{-gnatyB}
12930
12931@emph{Check Boolean operators.}
12932
12933The use of AND/OR operators is not permitted except in the cases of modular
12934operands, array operands, and simple stand-alone boolean variables or
12935boolean constants. In all other cases @cite{and then}/@cite{or else} are
12936required.
12937@end table
12938
12939@geindex -gnatyc (gcc)
12940
12941
12942@table @asis
12943
12944@item @code{-gnatyc}
12945
12946@emph{Check comments, double space.}
12947
12948Comments must meet the following set of rules:
12949
12950
12951@itemize *
12952
12953@item 
12954The '@cite{--}' that starts the column must either start in column one,
12955or else at least one blank must precede this sequence.
12956
12957@item 
12958Comments that follow other tokens on a line must have at least one blank
12959following the '@cite{--}' at the start of the comment.
12960
12961@item 
12962Full line comments must have at least two blanks following the
12963'@cite{--}' that starts the comment, with the following exceptions.
12964
12965@item 
12966A line consisting only of the '@cite{--}' characters, possibly preceded
12967by blanks is permitted.
12968
12969@item 
12970A comment starting with '@cite{--x}' where @cite{x} is a special character
12971is permitted.
12972This allows proper processing of the output generated by specialized tools
12973including @emph{gnatprep} (where '@cite{--!}' is used) and the SPARK
12974annotation
12975language (where '@cite{--#}' is used). For the purposes of this rule, a
12976special character is defined as being in one of the ASCII ranges
12977@cite{16#21#...16#2F#} or @cite{16#3A#...16#3F#}.
12978Note that this usage is not permitted
12979in GNAT implementation units (i.e., when @emph{-gnatg} is used).
12980
12981@item 
12982A line consisting entirely of minus signs, possibly preceded by blanks, is
12983permitted. This allows the construction of box comments where lines of minus
12984signs are used to form the top and bottom of the box.
12985
12986@item 
12987A comment that starts and ends with '@cite{--}' is permitted as long as at
12988least one blank follows the initial '@cite{--}'. Together with the preceding
12989rule, this allows the construction of box comments, as shown in the following
12990example:
12991
12992@example
12993---------------------------
12994-- This is a box comment --
12995-- with two text lines.  --
12996---------------------------
12997@end example
12998@end itemize
12999@end table
13000
13001@geindex -gnatyC (gcc)
13002
13003
13004@table @asis
13005
13006@item @code{-gnatyC}
13007
13008@emph{Check comments, single space.}
13009
13010This is identical to @cite{c} except that only one space
13011is required following the @cite{--} of a comment instead of two.
13012@end table
13013
13014@geindex -gnatyd (gcc)
13015
13016
13017@table @asis
13018
13019@item @code{-gnatyd}
13020
13021@emph{Check no DOS line terminators present.}
13022
13023All lines must be terminated by a single ASCII.LF
13024character (in particular the DOS line terminator sequence CR/LF is not
13025allowed).
13026@end table
13027
13028@geindex -gnatye (gcc)
13029
13030
13031@table @asis
13032
13033@item @code{-gnatye}
13034
13035@emph{Check end/exit labels.}
13036
13037Optional labels on @cite{end} statements ending subprograms and on
13038@cite{exit} statements exiting named loops, are required to be present.
13039@end table
13040
13041@geindex -gnatyf (gcc)
13042
13043
13044@table @asis
13045
13046@item @code{-gnatyf}
13047
13048@emph{No form feeds or vertical tabs.}
13049
13050Neither form feeds nor vertical tab characters are permitted
13051in the source text.
13052@end table
13053
13054@geindex -gnatyg (gcc)
13055
13056
13057@table @asis
13058
13059@item @code{-gnatyg}
13060
13061@emph{GNAT style mode.}
13062
13063The set of style check switches is set to match that used by the GNAT sources.
13064This may be useful when developing code that is eventually intended to be
13065incorporated into GNAT. Currently this is equivalent to @emph{-gnatwydISux})
13066but additional style switches may be added to this set in the future without
13067advance notice.
13068@end table
13069
13070@geindex -gnatyh (gcc)
13071
13072
13073@table @asis
13074
13075@item @code{-gnatyh}
13076
13077@emph{No horizontal tabs.}
13078
13079Horizontal tab characters are not permitted in the source text.
13080Together with the b (no blanks at end of line) check, this
13081enforces a canonical form for the use of blanks to separate
13082source tokens.
13083@end table
13084
13085@geindex -gnatyi (gcc)
13086
13087
13088@table @asis
13089
13090@item @code{-gnatyi}
13091
13092@emph{Check if-then layout.}
13093
13094The keyword @cite{then} must appear either on the same
13095line as corresponding @cite{if}, or on a line on its own, lined
13096up under the @cite{if}.
13097@end table
13098
13099@geindex -gnatyI (gcc)
13100
13101
13102@table @asis
13103
13104@item @code{-gnatyI}
13105
13106@emph{check mode IN keywords.}
13107
13108Mode @cite{in} (the default mode) is not
13109allowed to be given explicitly. @cite{in out} is fine,
13110but not @cite{in} on its own.
13111@end table
13112
13113@geindex -gnatyk (gcc)
13114
13115
13116@table @asis
13117
13118@item @code{-gnatyk}
13119
13120@emph{Check keyword casing.}
13121
13122All keywords must be in lower case (with the exception of keywords
13123such as @cite{digits} used as attribute names to which this check
13124does not apply).
13125@end table
13126
13127@geindex -gnatyl (gcc)
13128
13129
13130@table @asis
13131
13132@item @code{-gnatyl}
13133
13134@emph{Check layout.}
13135
13136Layout of statement and declaration constructs must follow the
13137recommendations in the Ada Reference Manual, as indicated by the
13138form of the syntax rules. For example an @cite{else} keyword must
13139be lined up with the corresponding @cite{if} keyword.
13140
13141There are two respects in which the style rule enforced by this check
13142option are more liberal than those in the Ada Reference Manual. First
13143in the case of record declarations, it is permissible to put the
13144@cite{record} keyword on the same line as the @cite{type} keyword, and
13145then the @cite{end} in @cite{end record} must line up under @cite{type}.
13146This is also permitted when the type declaration is split on two lines.
13147For example, any of the following three layouts is acceptable:
13148
13149@example
13150type q is record
13151   a : integer;
13152   b : integer;
13153end record;
13154
13155type q is
13156   record
13157      a : integer;
13158      b : integer;
13159   end record;
13160
13161type q is
13162   record
13163      a : integer;
13164      b : integer;
13165end record;
13166@end example
13167
13168Second, in the case of a block statement, a permitted alternative
13169is to put the block label on the same line as the @cite{declare} or
13170@cite{begin} keyword, and then line the @cite{end} keyword up under
13171the block label. For example both the following are permitted:
13172
13173@example
13174Block : declare
13175   A : Integer := 3;
13176begin
13177   Proc (A, A);
13178end Block;
13179
13180Block :
13181   declare
13182      A : Integer := 3;
13183   begin
13184      Proc (A, A);
13185   end Block;
13186@end example
13187
13188The same alternative format is allowed for loops. For example, both of
13189the following are permitted:
13190
13191@example
13192Clear : while J < 10 loop
13193   A (J) := 0;
13194end loop Clear;
13195
13196Clear :
13197   while J < 10 loop
13198      A (J) := 0;
13199   end loop Clear;
13200@end example
13201@end table
13202
13203@geindex -gnatyLnnn (gcc)
13204
13205
13206@table @asis
13207
13208@item @code{-gnatyL}
13209
13210@emph{Set maximum nesting level.}
13211
13212The maximum level of nesting of constructs (including subprograms, loops,
13213blocks, packages, and conditionals) may not exceed the given value
13214@emph{nnn}. A value of zero disconnects this style check.
13215@end table
13216
13217@geindex -gnatym (gcc)
13218
13219
13220@table @asis
13221
13222@item @code{-gnatym}
13223
13224@emph{Check maximum line length.}
13225
13226The length of source lines must not exceed 79 characters, including
13227any trailing blanks. The value of 79 allows convenient display on an
1322880 character wide device or window, allowing for possible special
13229treatment of 80 character lines. Note that this count is of
13230characters in the source text. This means that a tab character counts
13231as one character in this count and a wide character sequence counts as
13232a single character (however many bytes are needed in the encoding).
13233@end table
13234
13235@geindex -gnatyMnnn (gcc)
13236
13237
13238@table @asis
13239
13240@item @code{-gnatyM}
13241
13242@emph{Set maximum line length.}
13243
13244The length of lines must not exceed the
13245given value @emph{nnn}. The maximum value that can be specified is 32767.
13246If neither style option for setting the line length is used, then the
13247default is 255. This also controls the maximum length of lexical elements,
13248where the only restriction is that they must fit on a single line.
13249@end table
13250
13251@geindex -gnatyn (gcc)
13252
13253
13254@table @asis
13255
13256@item @code{-gnatyn}
13257
13258@emph{Check casing of entities in Standard.}
13259
13260Any identifier from Standard must be cased
13261to match the presentation in the Ada Reference Manual (for example,
13262@cite{Integer} and @cite{ASCII.NUL}).
13263@end table
13264
13265@geindex -gnatyN (gcc)
13266
13267
13268@table @asis
13269
13270@item @code{-gnatyN}
13271
13272@emph{Turn off all style checks.}
13273
13274All style check options are turned off.
13275@end table
13276
13277@geindex -gnatyo (gcc)
13278
13279
13280@table @asis
13281
13282@item @code{-gnatyo}
13283
13284@emph{Check order of subprogram bodies.}
13285
13286All subprogram bodies in a given scope
13287(e.g., a package body) must be in alphabetical order. The ordering
13288rule uses normal Ada rules for comparing strings, ignoring casing
13289of letters, except that if there is a trailing numeric suffix, then
13290the value of this suffix is used in the ordering (e.g., Junk2 comes
13291before Junk10).
13292@end table
13293
13294@geindex -gnatyO (gcc)
13295
13296
13297@table @asis
13298
13299@item @code{-gnatyO}
13300
13301@emph{Check that overriding subprograms are explicitly marked as such.}
13302
13303This applies to all subprograms of a derived type that override a primitive
13304operation of the type, for both tagged and untagged types. In particular,
13305the declaration of a primitive operation of a type extension that overrides
13306an inherited operation must carry an overriding indicator. Another case is
13307the declaration of a function that overrides a predefined operator (such
13308as an equality operator).
13309@end table
13310
13311@geindex -gnatyp (gcc)
13312
13313
13314@table @asis
13315
13316@item @code{-gnatyp}
13317
13318@emph{Check pragma casing.}
13319
13320Pragma names must be written in mixed case, that is, the
13321initial letter and any letter following an underscore must be uppercase.
13322All other letters must be lowercase. An exception is that SPARK_Mode is
13323allowed as an alternative for Spark_Mode.
13324@end table
13325
13326@geindex -gnatyr (gcc)
13327
13328
13329@table @asis
13330
13331@item @code{-gnatyr}
13332
13333@emph{Check references.}
13334
13335All identifier references must be cased in the same way as the
13336corresponding declaration. No specific casing style is imposed on
13337identifiers. The only requirement is for consistency of references
13338with declarations.
13339@end table
13340
13341@geindex -gnatys (gcc)
13342
13343
13344@table @asis
13345
13346@item @code{-gnatys}
13347
13348@emph{Check separate specs.}
13349
13350Separate declarations ('specs') are required for subprograms (a
13351body is not allowed to serve as its own declaration). The only
13352exception is that parameterless library level procedures are
13353not required to have a separate declaration. This exception covers
13354the most frequent form of main program procedures.
13355@end table
13356
13357@geindex -gnatyS (gcc)
13358
13359
13360@table @asis
13361
13362@item @code{-gnatyS}
13363
13364@emph{Check no statements after then/else.}
13365
13366No statements are allowed
13367on the same line as a @cite{then} or @cite{else} keyword following the
13368keyword in an @cite{if} statement. @cite{or else} and @cite{and then} are not
13369affected, and a special exception allows a pragma to appear after @cite{else}.
13370@end table
13371
13372@geindex -gnatyt (gcc)
13373
13374
13375@table @asis
13376
13377@item @code{-gnatyt}
13378
13379@emph{Check token spacing.}
13380
13381The following token spacing rules are enforced:
13382
13383
13384@itemize *
13385
13386@item 
13387The keywords @cite{abs} and @cite{not} must be followed by a space.
13388
13389@item 
13390The token @cite{=>} must be surrounded by spaces.
13391
13392@item 
13393The token @cite{<>} must be preceded by a space or a left parenthesis.
13394
13395@item 
13396Binary operators other than @cite{**} must be surrounded by spaces.
13397There is no restriction on the layout of the @cite{**} binary operator.
13398
13399@item 
13400Colon must be surrounded by spaces.
13401
13402@item 
13403Colon-equal (assignment, initialization) must be surrounded by spaces.
13404
13405@item 
13406Comma must be the first non-blank character on the line, or be
13407immediately preceded by a non-blank character, and must be followed
13408by a space.
13409
13410@item 
13411If the token preceding a left parenthesis ends with a letter or digit, then
13412a space must separate the two tokens.
13413
13414@item 
13415If the token following a right parenthesis starts with a letter or digit, then
13416a space must separate the two tokens.
13417
13418@item 
13419A right parenthesis must either be the first non-blank character on
13420a line, or it must be preceded by a non-blank character.
13421
13422@item 
13423A semicolon must not be preceded by a space, and must not be followed by
13424a non-blank character.
13425
13426@item 
13427A unary plus or minus may not be followed by a space.
13428
13429@item 
13430A vertical bar must be surrounded by spaces.
13431@end itemize
13432
13433Exactly one blank (and no other white space) must appear between
13434a @cite{not} token and a following @cite{in} token.
13435@end table
13436
13437@geindex -gnatyu (gcc)
13438
13439
13440@table @asis
13441
13442@item @code{-gnatyu}
13443
13444@emph{Check unnecessary blank lines.}
13445
13446Unnecessary blank lines are not allowed. A blank line is considered
13447unnecessary if it appears at the end of the file, or if more than
13448one blank line occurs in sequence.
13449@end table
13450
13451@geindex -gnatyx (gcc)
13452
13453
13454@table @asis
13455
13456@item @code{-gnatyx}
13457
13458@emph{Check extra parentheses.}
13459
13460Unnecessary extra level of parentheses (C-style) are not allowed
13461around conditions in @cite{if} statements, @cite{while} statements and
13462@cite{exit} statements.
13463@end table
13464
13465@geindex -gnatyy (gcc)
13466
13467
13468@table @asis
13469
13470@item @code{-gnatyy}
13471
13472@emph{Set all standard style check options}
13473
13474This is equivalent to @cite{gnaty3aAbcefhiklmnprst}, that is all checking
13475options enabled with the exception of @emph{-gnatyB}, @emph{-gnatyd},
13476@emph{-gnatyI}, @emph{-gnatyLnnn}, @emph{-gnatyo}, @emph{-gnatyO},
13477@emph{-gnatyS}, @emph{-gnatyu}, and @emph{-gnatyx}.
13478@end table
13479
13480@geindex -gnaty- (gcc)
13481
13482
13483@table @asis
13484
13485@item @code{-gnaty-}
13486
13487@emph{Remove style check options}
13488
13489This causes any subsequent options in the string to act as canceling the
13490corresponding style check option. To cancel maximum nesting level control,
13491use @emph{L} parameter witout any integer value after that, because any
13492digit following @emph{-} in the parameter string of the @emph{-gnaty}
13493option will be threated as canceling indentation check. The same is true
13494for @emph{M} parameter. @emph{y} and @emph{N} parameters are not
13495allowed after @emph{-}.
13496@end table
13497
13498@geindex -gnaty+ (gcc)
13499
13500
13501@table @asis
13502
13503@item @code{-gnaty+}
13504
13505@emph{Enable style check options}
13506
13507This causes any subsequent options in the string to enable the corresponding
13508style check option. That is, it cancels the effect of a previous -,
13509if any.
13510@end table
13511
13512@c end of switch description (leave this comment to ease automatic parsing for
13513
13514@c GPS
13515
13516In the above rules, appearing in column one is always permitted, that is,
13517counts as meeting either a requirement for a required preceding space,
13518or as meeting a requirement for no preceding space.
13519
13520Appearing at the end of a line is also always permitted, that is, counts
13521as meeting either a requirement for a following space, or as meeting
13522a requirement for no following space.
13523
13524If any of these style rules is violated, a message is generated giving
13525details on the violation. The initial characters of such messages are
13526always '@cite{(style)}'. Note that these messages are treated as warning
13527messages, so they normally do not prevent the generation of an object
13528file. The @emph{-gnatwe} switch can be used to treat warning messages,
13529including style messages, as fatal errors.
13530
13531The switch @code{-gnaty} on its own (that is not
13532followed by any letters or digits) is equivalent
13533to the use of @emph{-gnatyy} as described above, that is all
13534built-in standard style check options are enabled.
13535
13536The switch @code{-gnatyN} clears any previously set style checks.
13537
13538@node Run-Time Checks,Using gcc for Syntax Checking,Style Checking,Compiler Switches
13539@anchor{gnat_ugn/building_executable_programs_with_gnat run-time-checks}@anchor{fe}@anchor{gnat_ugn/building_executable_programs_with_gnat id19}@anchor{109}
13540@subsection Run-Time Checks
13541
13542
13543@geindex Division by zero
13544
13545@geindex Access before elaboration
13546
13547@geindex Checks
13548@geindex division by zero
13549
13550@geindex Checks
13551@geindex access before elaboration
13552
13553@geindex Checks
13554@geindex stack overflow checking
13555
13556By default, the following checks are suppressed: integer overflow
13557checks, stack overflow checks, and checks for access before
13558elaboration on subprogram calls. All other checks, including range
13559checks and array bounds checks, are turned on by default. The
13560following @emph{gcc} switches refine this default behavior.
13561
13562@geindex -gnatp (gcc)
13563
13564
13565@table @asis
13566
13567@item @code{-gnatp}
13568
13569@geindex Suppressing checks
13570
13571@geindex Checks
13572@geindex suppressing
13573
13574This switch causes the unit to be compiled
13575as though @cite{pragma Suppress (All_checks)}
13576had been present in the source. Validity checks are also eliminated (in
13577other words @emph{-gnatp} also implies @emph{-gnatVn}.
13578Use this switch to improve the performance
13579of the code at the expense of safety in the presence of invalid data or
13580program bugs.
13581
13582Note that when checks are suppressed, the compiler is allowed, but not
13583required, to omit the checking code. If the run-time cost of the
13584checking code is zero or near-zero, the compiler will generate it even
13585if checks are suppressed. In particular, if the compiler can prove
13586that a certain check will necessarily fail, it will generate code to
13587do an unconditional 'raise', even if checks are suppressed. The
13588compiler warns in this case. Another case in which checks may not be
13589eliminated is when they are embedded in certain run time routines such
13590as math library routines.
13591
13592Of course, run-time checks are omitted whenever the compiler can prove
13593that they will not fail, whether or not checks are suppressed.
13594
13595Note that if you suppress a check that would have failed, program
13596execution is erroneous, which means the behavior is totally
13597unpredictable. The program might crash, or print wrong answers, or
13598do anything else. It might even do exactly what you wanted it to do
13599(and then it might start failing mysteriously next week or next
13600year). The compiler will generate code based on the assumption that
13601the condition being checked is true, which can result in erroneous
13602execution if that assumption is wrong.
13603
13604The checks subject to suppression include all the checks defined by
13605the Ada standard, the additional implementation defined checks
13606@cite{Alignment_Check},
13607@cite{Duplicated_Tag_Check}, @cite{Predicate_Check}, and
13608@cite{Validity_Check}, as well as any checks introduced using
13609@cite{pragma Check_Name}. Note that @cite{Atomic_Synchronization}
13610is not automatically suppressed by use of this option.
13611
13612If the code depends on certain checks being active, you can use
13613pragma @cite{Unsuppress} either as a configuration pragma or as
13614a local pragma to make sure that a specified check is performed
13615even if @emph{gnatp} is specified.
13616
13617The @emph{-gnatp} switch has no effect if a subsequent
13618@emph{-gnat-p} switch appears.
13619@end table
13620
13621@geindex -gnat-p (gcc)
13622
13623@geindex Suppressing checks
13624
13625@geindex Checks
13626@geindex suppressing
13627
13628@geindex Suppress
13629
13630
13631@table @asis
13632
13633@item @code{-gnat-p}
13634
13635This switch cancels the effect of a previous @emph{gnatp} switch.
13636@end table
13637
13638@geindex -gnato?? (gcc)
13639
13640@geindex Overflow checks
13641
13642@geindex Overflow mode
13643
13644@geindex Check
13645@geindex overflow
13646
13647
13648@table @asis
13649
13650@item @code{-gnato??}
13651
13652This switch controls the mode used for computing intermediate
13653arithmetic integer operations, and also enables overflow checking.
13654For a full description of overflow mode and checking control, see
13655the 'Overflow Check Handling in GNAT' appendix in this
13656User's Guide.
13657
13658Overflow checks are always enabled by this switch. The argument
13659controls the mode, using the codes
13660
13661
13662@table @asis
13663
13664@item @emph{1 = STRICT}
13665
13666In STRICT mode, intermediate operations are always done using the
13667base type, and overflow checking ensures that the result is within
13668the base type range.
13669
13670@item @emph{2 = MINIMIZED}
13671
13672In MINIMIZED mode, overflows in intermediate operations are avoided
13673where possible by using a larger integer type for the computation
13674(typically @cite{Long_Long_Integer}). Overflow checking ensures that
13675the result fits in this larger integer type.
13676
13677@item @emph{3 = ELIMINATED}
13678
13679In ELIMINATED mode, overflows in intermediate operations are avoided
13680by using multi-precision arithmetic. In this case, overflow checking
13681has no effect on intermediate operations (since overflow is impossible).
13682@end table
13683
13684If two digits are present after @emph{-gnato} then the first digit
13685sets the mode for expressions outside assertions, and the second digit
13686sets the mode for expressions within assertions. Here assertions is used
13687in the technical sense (which includes for example precondition and
13688postcondition expressions).
13689
13690If one digit is present, the corresponding mode is applicable to both
13691expressions within and outside assertion expressions.
13692
13693If no digits are present, the default is to enable overflow checks
13694and set STRICT mode for both kinds of expressions. This is compatible
13695with the use of @emph{-gnato} in previous versions of GNAT.
13696
13697@geindex Machine_Overflows
13698
13699Note that the @emph{-gnato??} switch does not affect the code generated
13700for any floating-point operations; it applies only to integer semantics.
13701For floating-point, GNAT has the @cite{Machine_Overflows}
13702attribute set to @cite{False} and the normal mode of operation is to
13703generate IEEE NaN and infinite values on overflow or invalid operations
13704(such as dividing 0.0 by 0.0).
13705
13706The reason that we distinguish overflow checking from other kinds of
13707range constraint checking is that a failure of an overflow check, unlike
13708for example the failure of a range check, can result in an incorrect
13709value, but cannot cause random memory destruction (like an out of range
13710subscript), or a wild jump (from an out of range case value). Overflow
13711checking is also quite expensive in time and space, since in general it
13712requires the use of double length arithmetic.
13713
13714Note again that the default is @emph{-gnato00},
13715so overflow checking is not performed in default mode. This means that out of
13716the box, with the default settings, GNAT does not do all the checks
13717expected from the language description in the Ada Reference Manual.
13718If you want all constraint checks to be performed, as described in this Manual,
13719then you must explicitly use the @emph{-gnato??}
13720switch either on the @emph{gnatmake} or @emph{gcc} command.
13721@end table
13722
13723@geindex -gnatE (gcc)
13724
13725@geindex Elaboration checks
13726
13727@geindex Check
13728@geindex elaboration
13729
13730
13731@table @asis
13732
13733@item @code{-gnatE}
13734
13735Enables dynamic checks for access-before-elaboration
13736on subprogram calls and generic instantiations.
13737Note that @emph{-gnatE} is not necessary for safety, because in the
13738default mode, GNAT ensures statically that the checks would not fail.
13739For full details of the effect and use of this switch,
13740@ref{1e,,Compiling with gcc}.
13741@end table
13742
13743@geindex -fstack-check (gcc)
13744
13745@geindex Stack Overflow Checking
13746
13747@geindex Checks
13748@geindex stack overflow checking
13749
13750
13751@table @asis
13752
13753@item @code{-fstack-check}
13754
13755Activates stack overflow checking. For full details of the effect and use of
13756this switch see @ref{f9,,Stack Overflow Checking}.
13757@end table
13758
13759@geindex Unsuppress
13760
13761The setting of these switches only controls the default setting of the
13762checks. You may modify them using either @cite{Suppress} (to remove
13763checks) or @cite{Unsuppress} (to add back suppressed checks) pragmas in
13764the program source.
13765
13766@node Using gcc for Syntax Checking,Using gcc for Semantic Checking,Run-Time Checks,Compiler Switches
13767@anchor{gnat_ugn/building_executable_programs_with_gnat id20}@anchor{10a}@anchor{gnat_ugn/building_executable_programs_with_gnat using-gcc-for-syntax-checking}@anchor{10b}
13768@subsection Using @emph{gcc} for Syntax Checking
13769
13770
13771@geindex -gnats (gcc)
13772
13773
13774@table @asis
13775
13776@item @code{-gnats}
13777
13778The @cite{s} stands for 'syntax'.
13779
13780Run GNAT in syntax checking only mode. For
13781example, the command
13782
13783@example
13784$ gcc -c -gnats x.adb
13785@end example
13786
13787compiles file @code{x.adb} in syntax-check-only mode. You can check a
13788series of files in a single command
13789, and can use wild cards to specify such a group of files.
13790Note that you must specify the @emph{-c} (compile
13791only) flag in addition to the @emph{-gnats} flag.
13792
13793You may use other switches in conjunction with @emph{-gnats}. In
13794particular, @emph{-gnatl} and @emph{-gnatv} are useful to control the
13795format of any generated error messages.
13796
13797When the source file is empty or contains only empty lines and/or comments,
13798the output is a warning:
13799
13800@example
13801$ gcc -c -gnats -x ada toto.txt
13802toto.txt:1:01: warning: empty file, contains no compilation units
13803$
13804@end example
13805
13806Otherwise, the output is simply the error messages, if any. No object file or
13807ALI file is generated by a syntax-only compilation. Also, no units other
13808than the one specified are accessed. For example, if a unit @cite{X}
13809@emph{with}s a unit @cite{Y}, compiling unit @cite{X} in syntax
13810check only mode does not access the source file containing unit
13811@cite{Y}.
13812
13813@geindex Multiple units
13814@geindex syntax checking
13815
13816Normally, GNAT allows only a single unit in a source file. However, this
13817restriction does not apply in syntax-check-only mode, and it is possible
13818to check a file containing multiple compilation units concatenated
13819together. This is primarily used by the @cite{gnatchop} utility
13820(@ref{38,,Renaming Files with gnatchop}).
13821@end table
13822
13823@node Using gcc for Semantic Checking,Compiling Different Versions of Ada,Using gcc for Syntax Checking,Compiler Switches
13824@anchor{gnat_ugn/building_executable_programs_with_gnat id21}@anchor{10c}@anchor{gnat_ugn/building_executable_programs_with_gnat using-gcc-for-semantic-checking}@anchor{10d}
13825@subsection Using @emph{gcc} for Semantic Checking
13826
13827
13828@geindex -gnatc (gcc)
13829
13830
13831@table @asis
13832
13833@item @code{-gnatc}
13834
13835The @cite{c} stands for 'check'.
13836Causes the compiler to operate in semantic check mode,
13837with full checking for all illegalities specified in the
13838Ada Reference Manual, but without generation of any object code
13839(no object file is generated).
13840
13841Because dependent files must be accessed, you must follow the GNAT
13842semantic restrictions on file structuring to operate in this mode:
13843
13844
13845@itemize *
13846
13847@item 
13848The needed source files must be accessible
13849(see @ref{8e,,Search Paths and the Run-Time Library (RTL)}).
13850
13851@item 
13852Each file must contain only one compilation unit.
13853
13854@item 
13855The file name and unit name must match (@ref{54,,File Naming Rules}).
13856@end itemize
13857
13858The output consists of error messages as appropriate. No object file is
13859generated. An @code{ALI} file is generated for use in the context of
13860cross-reference tools, but this file is marked as not being suitable
13861for binding (since no object file is generated).
13862The checking corresponds exactly to the notion of
13863legality in the Ada Reference Manual.
13864
13865Any unit can be compiled in semantics-checking-only mode, including
13866units that would not normally be compiled (subunits,
13867and specifications where a separate body is present).
13868@end table
13869
13870@node Compiling Different Versions of Ada,Character Set Control,Using gcc for Semantic Checking,Compiler Switches
13871@anchor{gnat_ugn/building_executable_programs_with_gnat compiling-different-versions-of-ada}@anchor{6}@anchor{gnat_ugn/building_executable_programs_with_gnat id22}@anchor{10e}
13872@subsection Compiling Different Versions of Ada
13873
13874
13875The switches described in this section allow you to explicitly specify
13876the version of the Ada language that your programs are written in.
13877The default mode is Ada 2012,
13878but you can also specify Ada 95, Ada 2005 mode, or
13879indicate Ada 83 compatibility mode.
13880
13881@geindex Compatibility with Ada 83
13882
13883@geindex -gnat83 (gcc)
13884
13885@geindex ACVC
13886@geindex Ada 83 tests
13887
13888@geindex Ada 83 mode
13889
13890
13891@table @asis
13892
13893@item @code{-gnat83 (Ada 83 Compatibility Mode)}
13894
13895Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
13896specifies that the program is to be compiled in Ada 83 mode. With
13897@emph{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
13898semantics where this can be done easily.
13899It is not possible to guarantee this switch does a perfect
13900job; some subtle tests, such as are
13901found in earlier ACVC tests (and that have been removed from the ACATS suite
13902for Ada 95), might not compile correctly.
13903Nevertheless, this switch may be useful in some circumstances, for example
13904where, due to contractual reasons, existing code needs to be maintained
13905using only Ada 83 features.
13906
13907With few exceptions (most notably the need to use @cite{<>} on
13908.. index:: Generic formal parameters
13909
13910unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
13911reserved words, and the use of packages
13912with optional bodies), it is not necessary to specify the
13913@emph{-gnat83} switch when compiling Ada 83 programs, because, with rare
13914exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
13915a correct Ada 83 program is usually also a correct program
13916in these later versions of the language standard. For further information
13917please refer to the @cite{Compatibility_and_Porting_Guide} chapter in the
13918@cite{GNAT Reference Manual}.
13919@end table
13920
13921@geindex -gnat95 (gcc)
13922
13923@geindex Ada 95 mode
13924
13925
13926@table @asis
13927
13928@item @code{-gnat95} (Ada 95 mode)
13929
13930This switch directs the compiler to implement the Ada 95 version of the
13931language.
13932Since Ada 95 is almost completely upwards
13933compatible with Ada 83, Ada 83 programs may generally be compiled using
13934this switch (see the description of the @emph{-gnat83} switch for further
13935information about Ada 83 mode).
13936If an Ada 2005 program is compiled in Ada 95 mode,
13937uses of the new Ada 2005 features will cause error
13938messages or warnings.
13939
13940This switch also can be used to cancel the effect of a previous
13941@emph{-gnat83}, @emph{-gnat05/2005}, or @emph{-gnat12/2012}
13942switch earlier in the command line.
13943@end table
13944
13945@geindex -gnat05 (gcc)
13946
13947@geindex -gnat2005 (gcc)
13948
13949@geindex Ada 2005 mode
13950
13951
13952@table @asis
13953
13954@item @code{-gnat05} or @code{-gnat2005} (Ada 2005 mode)
13955
13956This switch directs the compiler to implement the Ada 2005 version of the
13957language, as documented in the official Ada standards document.
13958Since Ada 2005 is almost completely upwards
13959compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
13960may generally be compiled using this switch (see the description of the
13961@emph{-gnat83} and @emph{-gnat95} switches for further
13962information).
13963@end table
13964
13965@geindex -gnat12 (gcc)
13966
13967@geindex -gnat2012 (gcc)
13968
13969@geindex Ada 2012 mode
13970
13971
13972@table @asis
13973
13974@item @code{-gnat12} or @code{-gnat2012} (Ada 2012 mode)
13975
13976This switch directs the compiler to implement the Ada 2012 version of the
13977language (also the default).
13978Since Ada 2012 is almost completely upwards
13979compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
13980Ada 83 and Ada 95 programs
13981may generally be compiled using this switch (see the description of the
13982@emph{-gnat83}, @emph{-gnat95}, and @emph{-gnat05/2005} switches
13983for further information).
13984@end table
13985
13986@geindex -gnatX (gcc)
13987
13988@geindex Ada language extensions
13989
13990@geindex GNAT extensions
13991
13992
13993@table @asis
13994
13995@item @code{-gnatX} (Enable GNAT Extensions)
13996
13997This switch directs the compiler to implement the latest version of the
13998language (currently Ada 2012) and also to enable certain GNAT implementation
13999extensions that are not part of any Ada standard. For a full list of these
14000extensions, see the GNAT reference manual.
14001@end table
14002
14003@node Character Set Control,File Naming Control,Compiling Different Versions of Ada,Compiler Switches
14004@anchor{gnat_ugn/building_executable_programs_with_gnat id23}@anchor{10f}@anchor{gnat_ugn/building_executable_programs_with_gnat character-set-control}@anchor{4a}
14005@subsection Character Set Control
14006
14007
14008@geindex -gnati (gcc)
14009
14010
14011@table @asis
14012
14013@item @code{-gnati@emph{c}}
14014
14015Normally GNAT recognizes the Latin-1 character set in source program
14016identifiers, as described in the Ada Reference Manual.
14017This switch causes
14018GNAT to recognize alternate character sets in identifiers. @cite{c} is a
14019single character  indicating the character set, as follows:
14020
14021
14022@multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
14023@item
14024
14025@emph{1}
14026
14027@tab
14028
14029ISO 8859-1 (Latin-1) identifiers
14030
14031@item
14032
14033@emph{2}
14034
14035@tab
14036
14037ISO 8859-2 (Latin-2) letters allowed in identifiers
14038
14039@item
14040
14041@emph{3}
14042
14043@tab
14044
14045ISO 8859-3 (Latin-3) letters allowed in identifiers
14046
14047@item
14048
14049@emph{4}
14050
14051@tab
14052
14053ISO 8859-4 (Latin-4) letters allowed in identifiers
14054
14055@item
14056
14057@emph{5}
14058
14059@tab
14060
14061ISO 8859-5 (Cyrillic) letters allowed in identifiers
14062
14063@item
14064
14065@emph{9}
14066
14067@tab
14068
14069ISO 8859-15 (Latin-9) letters allowed in identifiers
14070
14071@item
14072
14073@emph{p}
14074
14075@tab
14076
14077IBM PC letters (code page 437) allowed in identifiers
14078
14079@item
14080
14081@emph{8}
14082
14083@tab
14084
14085IBM PC letters (code page 850) allowed in identifiers
14086
14087@item
14088
14089@emph{f}
14090
14091@tab
14092
14093Full upper-half codes allowed in identifiers
14094
14095@item
14096
14097@emph{n}
14098
14099@tab
14100
14101No upper-half codes allowed in identifiers
14102
14103@item
14104
14105@emph{w}
14106
14107@tab
14108
14109Wide-character codes (that is, codes greater than 255)
14110allowed in identifiers
14111
14112@end multitable
14113
14114
14115See @ref{40,,Foreign Language Representation} for full details on the
14116implementation of these character sets.
14117@end table
14118
14119@geindex -gnatW (gcc)
14120
14121
14122@table @asis
14123
14124@item @code{-gnatW@emph{e}}
14125
14126Specify the method of encoding for wide characters.
14127@cite{e} is one of the following:
14128
14129
14130@multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
14131@item
14132
14133@emph{h}
14134
14135@tab
14136
14137Hex encoding (brackets coding also recognized)
14138
14139@item
14140
14141@emph{u}
14142
14143@tab
14144
14145Upper half encoding (brackets encoding also recognized)
14146
14147@item
14148
14149@emph{s}
14150
14151@tab
14152
14153Shift/JIS encoding (brackets encoding also recognized)
14154
14155@item
14156
14157@emph{e}
14158
14159@tab
14160
14161EUC encoding (brackets encoding also recognized)
14162
14163@item
14164
14165@emph{8}
14166
14167@tab
14168
14169UTF-8 encoding (brackets encoding also recognized)
14170
14171@item
14172
14173@emph{b}
14174
14175@tab
14176
14177Brackets encoding only (default value)
14178
14179@end multitable
14180
14181
14182For full details on these encoding
14183methods see @ref{50,,Wide_Character Encodings}.
14184Note that brackets coding is always accepted, even if one of the other
14185options is specified, so for example @emph{-gnatW8} specifies that both
14186brackets and UTF-8 encodings will be recognized. The units that are
14187with'ed directly or indirectly will be scanned using the specified
14188representation scheme, and so if one of the non-brackets scheme is
14189used, it must be used consistently throughout the program. However,
14190since brackets encoding is always recognized, it may be conveniently
14191used in standard libraries, allowing these libraries to be used with
14192any of the available coding schemes.
14193
14194Note that brackets encoding only applies to program text. Within comments,
14195brackets are considered to be normal graphic characters, and bracket sequences
14196are never recognized as wide characters.
14197
14198If no @emph{-gnatW?} parameter is present, then the default
14199representation is normally Brackets encoding only. However, if the
14200first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
14201byte order mark or BOM for UTF-8), then these three characters are
14202skipped and the default representation for the file is set to UTF-8.
14203
14204Note that the wide character representation that is specified (explicitly
14205or by default) for the main program also acts as the default encoding used
14206for Wide_Text_IO files if not specifically overridden by a WCEM form
14207parameter.
14208@end table
14209
14210When no @emph{-gnatW?} is specified, then characters (other than wide
14211characters represented using brackets notation) are treated as 8-bit
14212Latin-1 codes. The codes recognized are the Latin-1 graphic characters,
14213and ASCII format effectors (CR, LF, HT, VT). Other lower half control
14214characters in the range 16#00#..16#1F# are not accepted in program text
14215or in comments. Upper half control characters (16#80#..16#9F#) are rejected
14216in program text, but allowed and ignored in comments. Note in particular
14217that the Next Line (NEL) character whose encoding is 16#85# is not recognized
14218as an end of line in this default mode. If your source program contains
14219instances of the NEL character used as a line terminator,
14220you must use UTF-8 encoding for the whole
14221source program. In default mode, all lines must be ended by a standard
14222end of line sequence (CR, CR/LF, or LF).
14223
14224Note that the convention of simply accepting all upper half characters in
14225comments means that programs that use standard ASCII for program text, but
14226UTF-8 encoding for comments are accepted in default mode, providing that the
14227comments are ended by an appropriate (CR, or CR/LF, or LF) line terminator.
14228This is a common mode for many programs with foreign language comments.
14229
14230@node File Naming Control,Subprogram Inlining Control,Character Set Control,Compiler Switches
14231@anchor{gnat_ugn/building_executable_programs_with_gnat file-naming-control}@anchor{110}@anchor{gnat_ugn/building_executable_programs_with_gnat id24}@anchor{111}
14232@subsection File Naming Control
14233
14234
14235@geindex -gnatk (gcc)
14236
14237
14238@table @asis
14239
14240@item @code{-gnatk@emph{n}}
14241
14242Activates file name 'krunching'. @cite{n}, a decimal integer in the range
142431-999, indicates the maximum allowable length of a file name (not
14244including the @code{.ads} or @code{.adb} extension). The default is not
14245to enable file name krunching.
14246
14247For the source file naming rules, @ref{54,,File Naming Rules}.
14248@end table
14249
14250@node Subprogram Inlining Control,Auxiliary Output Control,File Naming Control,Compiler Switches
14251@anchor{gnat_ugn/building_executable_programs_with_gnat subprogram-inlining-control}@anchor{112}@anchor{gnat_ugn/building_executable_programs_with_gnat id25}@anchor{113}
14252@subsection Subprogram Inlining Control
14253
14254
14255@geindex -gnatn (gcc)
14256
14257
14258@table @asis
14259
14260@item @code{-gnatn[12]}
14261
14262The @cite{n} here is intended to suggest the first syllable of the
14263word 'inline'.
14264GNAT recognizes and processes @cite{Inline} pragmas. However, for the
14265inlining to actually occur, optimization must be enabled and, in order
14266to enable inlining of subprograms specified by pragma @cite{Inline},
14267you must also specify this switch.
14268In the absence of this switch, GNAT does not attempt
14269inlining and does not need to access the bodies of
14270subprograms for which @cite{pragma Inline} is specified if they are not
14271in the current unit.
14272
14273You can optionally specify the inlining level: 1 for moderate inlining across
14274modules, which is a good compromise between compilation times and performances
14275at run time, or 2 for full inlining across modules, which may bring about
14276longer compilation times. If no inlining level is specified, the compiler will
14277pick it based on the optimization level: 1 for @emph{-O1}, @emph{-O2} or
14278@emph{-Os} and 2 for @emph{-O3}.
14279
14280If you specify this switch the compiler will access these bodies,
14281creating an extra source dependency for the resulting object file, and
14282where possible, the call will be inlined.
14283For further details on when inlining is possible
14284see @ref{114,,Inlining of Subprograms}.
14285@end table
14286
14287@geindex -gnatN (gcc)
14288
14289
14290@table @asis
14291
14292@item @code{-gnatN}
14293
14294This switch activates front-end inlining which also
14295generates additional dependencies.
14296
14297When using a gcc-based back end (in practice this means using any version
14298of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
14299@emph{-gnatN} is deprecated, and the use of @emph{-gnatn} is preferred.
14300Historically front end inlining was more extensive than the gcc back end
14301inlining, but that is no longer the case.
14302@end table
14303
14304@node Auxiliary Output Control,Debugging Control,Subprogram Inlining Control,Compiler Switches
14305@anchor{gnat_ugn/building_executable_programs_with_gnat auxiliary-output-control}@anchor{115}@anchor{gnat_ugn/building_executable_programs_with_gnat id26}@anchor{116}
14306@subsection Auxiliary Output Control
14307
14308
14309@geindex -gnatt (gcc)
14310
14311@geindex Writing internal trees
14312
14313@geindex Internal trees
14314@geindex writing to file
14315
14316
14317@table @asis
14318
14319@item @code{-gnatt}
14320
14321Causes GNAT to write the internal tree for a unit to a file (with the
14322extension @code{.adt}.
14323This not normally required, but is used by separate analysis tools.
14324Typically
14325these tools do the necessary compilations automatically, so you should
14326not have to specify this switch in normal operation.
14327Note that the combination of switches @emph{-gnatct}
14328generates a tree in the form required by ASIS applications.
14329@end table
14330
14331@geindex -gnatu (gcc)
14332
14333
14334@table @asis
14335
14336@item @code{-gnatu}
14337
14338Print a list of units required by this compilation on @code{stdout}.
14339The listing includes all units on which the unit being compiled depends
14340either directly or indirectly.
14341@end table
14342
14343@geindex -pass-exit-codes (gcc)
14344
14345
14346@table @asis
14347
14348@item @code{-pass-exit-codes}
14349
14350If this switch is not used, the exit code returned by @emph{gcc} when
14351compiling multiple files indicates whether all source files have
14352been successfully used to generate object files or not.
14353
14354When @emph{-pass-exit-codes} is used, @emph{gcc} exits with an extended
14355exit status and allows an integrated development environment to better
14356react to a compilation failure. Those exit status are:
14357
14358
14359@multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
14360@item
14361
14362@emph{5}
14363
14364@tab
14365
14366There was an error in at least one source file.
14367
14368@item
14369
14370@emph{3}
14371
14372@tab
14373
14374At least one source file did not generate an object file.
14375
14376@item
14377
14378@emph{2}
14379
14380@tab
14381
14382The compiler died unexpectedly (internal error for example).
14383
14384@item
14385
14386@emph{0}
14387
14388@tab
14389
14390An object file has been generated for every source file.
14391
14392@end multitable
14393
14394@end table
14395
14396@node Debugging Control,Exception Handling Control,Auxiliary Output Control,Compiler Switches
14397@anchor{gnat_ugn/building_executable_programs_with_gnat debugging-control}@anchor{117}@anchor{gnat_ugn/building_executable_programs_with_gnat id27}@anchor{118}
14398@subsection Debugging Control
14399
14400
14401@quotation
14402
14403@geindex Debugging options
14404@end quotation
14405
14406@geindex -gnatd (gcc)
14407
14408
14409@table @asis
14410
14411@item @code{-gnatd@emph{x}}
14412
14413Activate internal debugging switches. @cite{x} is a letter or digit, or
14414string of letters or digits, which specifies the type of debugging
14415outputs desired. Normally these are used only for internal development
14416or system debugging purposes. You can find full documentation for these
14417switches in the body of the @cite{Debug} unit in the compiler source
14418file @code{debug.adb}.
14419@end table
14420
14421@geindex -gnatG (gcc)
14422
14423
14424@table @asis
14425
14426@item @code{-gnatG[=@emph{nn}]}
14427
14428This switch causes the compiler to generate auxiliary output containing
14429a pseudo-source listing of the generated expanded code. Like most Ada
14430compilers, GNAT works by first transforming the high level Ada code into
14431lower level constructs. For example, tasking operations are transformed
14432into calls to the tasking run-time routines. A unique capability of GNAT
14433is to list this expanded code in a form very close to normal Ada source.
14434This is very useful in understanding the implications of various Ada
14435usage on the efficiency of the generated code. There are many cases in
14436Ada (e.g., the use of controlled types), where simple Ada statements can
14437generate a lot of run-time code. By using @emph{-gnatG} you can identify
14438these cases, and consider whether it may be desirable to modify the coding
14439approach to improve efficiency.
14440
14441The optional parameter @cite{nn} if present after -gnatG specifies an
14442alternative maximum line length that overrides the normal default of 72.
14443This value is in the range 40-999999, values less than 40 being silently
14444reset to 40. The equal sign is optional.
14445
14446The format of the output is very similar to standard Ada source, and is
14447easily understood by an Ada programmer. The following special syntactic
14448additions correspond to low level features used in the generated code that
14449do not have any exact analogies in pure Ada source form. The following
14450is a partial list of these special constructions. See the spec
14451of package @cite{Sprint} in file @code{sprint.ads} for a full list.
14452
14453@geindex -gnatL (gcc)
14454
14455If the switch @emph{-gnatL} is used in conjunction with
14456@emph{-gnatG}, then the original source lines are interspersed
14457in the expanded source (as comment lines with the original line number).
14458
14459
14460@table @asis
14461
14462@item @code{new @emph{xxx} [storage_pool = @emph{yyy}]}
14463
14464Shows the storage pool being used for an allocator.
14465
14466@item @code{at end @emph{procedure-name};}
14467
14468Shows the finalization (cleanup) procedure for a scope.
14469
14470@item @code{(if @emph{expr} then @emph{expr} else @emph{expr})}
14471
14472Conditional expression equivalent to the @cite{x?y:z} construction in C.
14473
14474@item @code{@emph{target}^(@emph{source})}
14475
14476A conversion with floating-point truncation instead of rounding.
14477
14478@item @code{@emph{target}?(@emph{source})}
14479
14480A conversion that bypasses normal Ada semantic checking. In particular
14481enumeration types and fixed-point types are treated simply as integers.
14482
14483@item @code{@emph{target}?^(@emph{source})}
14484
14485Combines the above two cases.
14486@end table
14487
14488@code{@emph{x} #/ @emph{y}}
14489
14490@code{@emph{x} #mod @emph{y}}
14491
14492@code{@emph{x} # @emph{y}}
14493
14494
14495@table @asis
14496
14497@item @code{@emph{x} #rem @emph{y}}
14498
14499A division or multiplication of fixed-point values which are treated as
14500integers without any kind of scaling.
14501
14502@item @code{free @emph{expr} [storage_pool = @emph{xxx}]}
14503
14504Shows the storage pool associated with a @cite{free} statement.
14505
14506@item @code{[subtype or type declaration]}
14507
14508Used to list an equivalent declaration for an internally generated
14509type that is referenced elsewhere in the listing.
14510
14511@item @code{freeze @emph{type-name} [@emph{actions}]}
14512
14513Shows the point at which @cite{type-name} is frozen, with possible
14514associated actions to be performed at the freeze point.
14515
14516@item @code{reference @emph{itype}}
14517
14518Reference (and hence definition) to internal type @cite{itype}.
14519
14520@item @code{@emph{function-name}! (@emph{arg}, @emph{arg}, @emph{arg})}
14521
14522Intrinsic function call.
14523
14524@item @code{@emph{label-name} : label}
14525
14526Declaration of label @cite{labelname}.
14527
14528@item @code{#$ @emph{subprogram-name}}
14529
14530An implicit call to a run-time support routine
14531(to meet the requirement of H.3.1(9) in a
14532convenient manner).
14533
14534@item @code{@emph{expr} && @emph{expr} && @emph{expr} ... && @emph{expr}}
14535
14536A multiple concatenation (same effect as @cite{expr} & @cite{expr} &
14537@cite{expr}, but handled more efficiently).
14538
14539@item @code{[constraint_error]}
14540
14541Raise the @cite{Constraint_Error} exception.
14542
14543@item @code{@emph{expression}'reference}
14544
14545A pointer to the result of evaluating @{expression@}.
14546
14547@item @code{@emph{target-type}!(@emph{source-expression})}
14548
14549An unchecked conversion of @cite{source-expression} to @cite{target-type}.
14550
14551@item @code{[@emph{numerator}/@emph{denominator}]}
14552
14553Used to represent internal real literals (that) have no exact
14554representation in base 2-16 (for example, the result of compile time
14555evaluation of the expression 1.0/27.0).
14556@end table
14557@end table
14558
14559@geindex -gnatD (gcc)
14560
14561
14562@table @asis
14563
14564@item @code{-gnatD[=nn]}
14565
14566When used in conjunction with @emph{-gnatG}, this switch causes
14567the expanded source, as described above for
14568@emph{-gnatG} to be written to files with names
14569@code{xxx.dg}, where @code{xxx} is the normal file name,
14570instead of to the standard output file. For
14571example, if the source file name is @code{hello.adb}, then a file
14572@code{hello.adb.dg} will be written.  The debugging
14573information generated by the @emph{gcc} @emph{-g} switch
14574will refer to the generated @code{xxx.dg} file. This allows
14575you to do source level debugging using the generated code which is
14576sometimes useful for complex code, for example to find out exactly
14577which part of a complex construction raised an exception. This switch
14578also suppress generation of cross-reference information (see
14579@emph{-gnatx}) since otherwise the cross-reference information
14580would refer to the @code{.dg} file, which would cause
14581confusion since this is not the original source file.
14582
14583Note that @emph{-gnatD} actually implies @emph{-gnatG}
14584automatically, so it is not necessary to give both options.
14585In other words @emph{-gnatD} is equivalent to @emph{-gnatDG}).
14586
14587@geindex -gnatL (gcc)
14588
14589If the switch @emph{-gnatL} is used in conjunction with
14590@emph{-gnatDG}, then the original source lines are interspersed
14591in the expanded source (as comment lines with the original line number).
14592
14593The optional parameter @cite{nn} if present after -gnatD specifies an
14594alternative maximum line length that overrides the normal default of 72.
14595This value is in the range 40-999999, values less than 40 being silently
14596reset to 40. The equal sign is optional.
14597@end table
14598
14599@geindex -gnatr (gcc)
14600
14601@geindex pragma Restrictions
14602
14603
14604@table @asis
14605
14606@item @code{-gnatr}
14607
14608This switch causes pragma Restrictions to be treated as Restriction_Warnings
14609so that violation of restrictions causes warnings rather than illegalities.
14610This is useful during the development process when new restrictions are added
14611or investigated. The switch also causes pragma Profile to be treated as
14612Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
14613restriction warnings rather than restrictions.
14614@end table
14615
14616@geindex -gnatR (gcc)
14617
14618
14619@table @asis
14620
14621@item @code{-gnatR[0|1|2|3[s]]}
14622
14623This switch controls output from the compiler of a listing showing
14624representation information for declared types and objects. For
14625@emph{-gnatR0}, no information is output (equivalent to omitting
14626the @emph{-gnatR} switch). For @emph{-gnatR1} (which is the default,
14627so @emph{-gnatR} with no parameter has the same effect), size and alignment
14628information is listed for declared array and record types. For
14629@emph{-gnatR2}, size and alignment information is listed for all
14630declared types and objects. The @cite{Linker_Section} is also listed for any
14631entity for which the @cite{Linker_Section} is set explicitly or implicitly (the
14632latter case occurs for objects of a type for which a @cite{Linker_Section}
14633is set).
14634
14635Finally @emph{-gnatR3} includes symbolic
14636expressions for values that are computed at run time for
14637variant records. These symbolic expressions have a mostly obvious
14638format with #n being used to represent the value of the n'th
14639discriminant. See source files @code{repinfo.ads/adb} in the
14640@cite{GNAT} sources for full details on the format of @emph{-gnatR3}
14641output. If the switch is followed by an s (e.g., @emph{-gnatR2s}), then
14642the output is to a file with the name @code{file.rep} where
14643file is the name of the corresponding source file.
14644
14645@item @code{-gnatRm[s]}
14646
14647This form of the switch controls output of subprogram conventions
14648and parameter passing mechanisms for all subprograms. A following
14649@cite{s} means output to a file as described above.
14650
14651Note that it is possible for record components to have zero size. In
14652this case, the component clause uses an obvious extension of permitted
14653Ada syntax, for example @cite{at 0 range 0 .. -1}.
14654
14655Representation information requires that code be generated (since it is the
14656code generator that lays out complex data structures). If an attempt is made
14657to output representation information when no code is generated, for example
14658when a subunit is compiled on its own, then no information can be generated
14659and the compiler outputs a message to this effect.
14660@end table
14661
14662@geindex -gnatS (gcc)
14663
14664
14665@table @asis
14666
14667@item @code{-gnatS}
14668
14669The use of the switch @emph{-gnatS} for an
14670Ada compilation will cause the compiler to output a
14671representation of package Standard in a form very
14672close to standard Ada. It is not quite possible to
14673do this entirely in standard Ada (since new
14674numeric base types cannot be created in standard
14675Ada), but the output is easily
14676readable to any Ada programmer, and is useful to
14677determine the characteristics of target dependent
14678types in package Standard.
14679@end table
14680
14681@geindex -gnatx (gcc)
14682
14683
14684@table @asis
14685
14686@item @code{-gnatx}
14687
14688Normally the compiler generates full cross-referencing information in
14689the @code{ALI} file. This information is used by a number of tools,
14690including @cite{gnatfind} and @cite{gnatxref}. The @emph{-gnatx} switch
14691suppresses this information. This saves some space and may slightly
14692speed up compilation, but means that these tools cannot be used.
14693@end table
14694
14695@node Exception Handling Control,Units to Sources Mapping Files,Debugging Control,Compiler Switches
14696@anchor{gnat_ugn/building_executable_programs_with_gnat id28}@anchor{119}@anchor{gnat_ugn/building_executable_programs_with_gnat exception-handling-control}@anchor{11a}
14697@subsection Exception Handling Control
14698
14699
14700GNAT uses two methods for handling exceptions at run-time. The
14701@cite{setjmp/longjmp} method saves the context when entering
14702a frame with an exception handler. Then when an exception is
14703raised, the context can be restored immediately, without the
14704need for tracing stack frames. This method provides very fast
14705exception propagation, but introduces significant overhead for
14706the use of exception handlers, even if no exception is raised.
14707
14708The other approach is called 'zero cost' exception handling.
14709With this method, the compiler builds static tables to describe
14710the exception ranges. No dynamic code is required when entering
14711a frame containing an exception handler. When an exception is
14712raised, the tables are used to control a back trace of the
14713subprogram invocation stack to locate the required exception
14714handler. This method has considerably poorer performance for
14715the propagation of exceptions, but there is no overhead for
14716exception handlers if no exception is raised. Note that in this
14717mode and in the context of mixed Ada and C/C++ programming,
14718to propagate an exception through a C/C++ code, the C/C++ code
14719must be compiled with the @emph{-funwind-tables} GCC's
14720option.
14721
14722The following switches may be used to control which of the
14723two exception handling methods is used.
14724
14725@geindex --RTS=sjlj (gnatmake)
14726
14727
14728@table @asis
14729
14730@item @code{--RTS=sjlj}
14731
14732This switch causes the setjmp/longjmp run-time (when available) to be used
14733for exception handling. If the default
14734mechanism for the target is zero cost exceptions, then
14735this switch can be used to modify this default, and must be
14736used for all units in the partition.
14737This option is rarely used. One case in which it may be
14738advantageous is if you have an application where exception
14739raising is common and the overall performance of the
14740application is improved by favoring exception propagation.
14741@end table
14742
14743@geindex --RTS=zcx (gnatmake)
14744
14745@geindex Zero Cost Exceptions
14746
14747
14748@table @asis
14749
14750@item @code{--RTS=zcx}
14751
14752This switch causes the zero cost approach to be used
14753for exception handling. If this is the default mechanism for the
14754target (see below), then this switch is unneeded. If the default
14755mechanism for the target is setjmp/longjmp exceptions, then
14756this switch can be used to modify this default, and must be
14757used for all units in the partition.
14758This option can only be used if the zero cost approach
14759is available for the target in use, otherwise it will generate an error.
14760@end table
14761
14762The same option @emph{--RTS} must be used both for @emph{gcc}
14763and @emph{gnatbind}. Passing this option to @emph{gnatmake}
14764(@ref{df,,Switches for gnatmake}) will ensure the required consistency
14765through the compilation and binding steps.
14766
14767@node Units to Sources Mapping Files,Code Generation Control,Exception Handling Control,Compiler Switches
14768@anchor{gnat_ugn/building_executable_programs_with_gnat id29}@anchor{11b}@anchor{gnat_ugn/building_executable_programs_with_gnat units-to-sources-mapping-files}@anchor{fc}
14769@subsection Units to Sources Mapping Files
14770
14771
14772@geindex -gnatem (gcc)
14773
14774
14775@table @asis
14776
14777@item @code{-gnatem=@emph{path}}
14778
14779A mapping file is a way to communicate to the compiler two mappings:
14780from unit names to file names (without any directory information) and from
14781file names to path names (with full directory information). These mappings
14782are used by the compiler to short-circuit the path search.
14783
14784The use of mapping files is not required for correct operation of the
14785compiler, but mapping files can improve efficiency, particularly when
14786sources are read over a slow network connection. In normal operation,
14787you need not be concerned with the format or use of mapping files,
14788and the @emph{-gnatem} switch is not a switch that you would use
14789explicitly. It is intended primarily for use by automatic tools such as
14790@emph{gnatmake} running under the project file facility. The
14791description here of the format of mapping files is provided
14792for completeness and for possible use by other tools.
14793
14794A mapping file is a sequence of sets of three lines. In each set, the
14795first line is the unit name, in lower case, with @cite{%s} appended
14796for specs and @cite{%b} appended for bodies; the second line is the
14797file name; and the third line is the path name.
14798
14799Example:
14800
14801@example
14802main%b
14803main.2.ada
14804/gnat/project1/sources/main.2.ada
14805@end example
14806
14807When the switch @emph{-gnatem} is specified, the compiler will
14808create in memory the two mappings from the specified file. If there is
14809any problem (nonexistent file, truncated file or duplicate entries),
14810no mapping will be created.
14811
14812Several @emph{-gnatem} switches may be specified; however, only the
14813last one on the command line will be taken into account.
14814
14815When using a project file, @emph{gnatmake} creates a temporary
14816mapping file and communicates it to the compiler using this switch.
14817@end table
14818
14819@node Code Generation Control,,Units to Sources Mapping Files,Compiler Switches
14820@anchor{gnat_ugn/building_executable_programs_with_gnat code-generation-control}@anchor{11c}@anchor{gnat_ugn/building_executable_programs_with_gnat id30}@anchor{11d}
14821@subsection Code Generation Control
14822
14823
14824The GCC technology provides a wide range of target dependent
14825@code{-m} switches for controlling
14826details of code generation with respect to different versions of
14827architectures. This includes variations in instruction sets (e.g.,
14828different members of the power pc family), and different requirements
14829for optimal arrangement of instructions (e.g., different members of
14830the x86 family). The list of available @emph{-m} switches may be
14831found in the GCC documentation.
14832
14833Use of these @emph{-m} switches may in some cases result in improved
14834code performance.
14835
14836The GNAT technology is tested and qualified without any
14837@code{-m} switches,
14838so generally the most reliable approach is to avoid the use of these
14839switches. However, we generally expect most of these switches to work
14840successfully with GNAT, and many customers have reported successful
14841use of these options.
14842
14843Our general advice is to avoid the use of @emph{-m} switches unless
14844special needs lead to requirements in this area. In particular,
14845there is no point in using @emph{-m} switches to improve performance
14846unless you actually see a performance improvement.
14847
14848@node Binding with gnatbind,Linking with gnatlink,Compiler Switches,Building Executable Programs with GNAT
14849@anchor{gnat_ugn/building_executable_programs_with_gnat binding-with-gnatbind}@anchor{1f}@anchor{gnat_ugn/building_executable_programs_with_gnat id31}@anchor{11e}
14850@section Binding with @cite{gnatbind}
14851
14852
14853@geindex gnatbind
14854
14855This chapter describes the GNAT binder, @cite{gnatbind}, which is used
14856to bind compiled GNAT objects.
14857
14858Note: to invoke @cite{gnatbind} with a project file, use the @cite{gnat}
14859driver (see @ref{11f,,The GNAT Driver and Project Files}).
14860
14861The @cite{gnatbind} program performs four separate functions:
14862
14863
14864@itemize *
14865
14866@item 
14867Checks that a program is consistent, in accordance with the rules in
14868Chapter 10 of the Ada Reference Manual. In particular, error
14869messages are generated if a program uses inconsistent versions of a
14870given unit.
14871
14872@item 
14873Checks that an acceptable order of elaboration exists for the program
14874and issues an error message if it cannot find an order of elaboration
14875that satisfies the rules in Chapter 10 of the Ada Language Manual.
14876
14877@item 
14878Generates a main program incorporating the given elaboration order.
14879This program is a small Ada package (body and spec) that
14880must be subsequently compiled
14881using the GNAT compiler. The necessary compilation step is usually
14882performed automatically by @emph{gnatlink}. The two most important
14883functions of this program
14884are to call the elaboration routines of units in an appropriate order
14885and to call the main program.
14886
14887@item 
14888Determines the set of object files required by the given main program.
14889This information is output in the forms of comments in the generated program,
14890to be read by the @emph{gnatlink} utility used to link the Ada application.
14891@end itemize
14892
14893@menu
14894* Running gnatbind:: 
14895* Switches for gnatbind:: 
14896* Command-Line Access:: 
14897* Search Paths for gnatbind:: 
14898* Examples of gnatbind Usage:: 
14899
14900@end menu
14901
14902@node Running gnatbind,Switches for gnatbind,,Binding with gnatbind
14903@anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatbind}@anchor{120}@anchor{gnat_ugn/building_executable_programs_with_gnat id32}@anchor{121}
14904@subsection Running @cite{gnatbind}
14905
14906
14907The form of the @cite{gnatbind} command is
14908
14909@example
14910$ gnatbind [`switches`] `mainprog`[.ali] [`switches`]
14911@end example
14912
14913where @code{mainprog.adb} is the Ada file containing the main program
14914unit body. @cite{gnatbind} constructs an Ada
14915package in two files whose names are
14916@code{b~mainprog.ads}, and @code{b~mainprog.adb}.
14917For example, if given the
14918parameter @code{hello.ali}, for a main program contained in file
14919@code{hello.adb}, the binder output files would be @code{b~hello.ads}
14920and @code{b~hello.adb}.
14921
14922When doing consistency checking, the binder takes into consideration
14923any source files it can locate. For example, if the binder determines
14924that the given main program requires the package @cite{Pack}, whose
14925@code{.ALI}
14926file is @code{pack.ali} and whose corresponding source spec file is
14927@code{pack.ads}, it attempts to locate the source file @code{pack.ads}
14928(using the same search path conventions as previously described for the
14929@emph{gcc} command). If it can locate this source file, it checks that
14930the time stamps
14931or source checksums of the source and its references to in @code{ALI} files
14932match. In other words, any @code{ALI} files that mentions this spec must have
14933resulted from compiling this version of the source file (or in the case
14934where the source checksums match, a version close enough that the
14935difference does not matter).
14936
14937@geindex Source files
14938@geindex use by binder
14939
14940The effect of this consistency checking, which includes source files, is
14941that the binder ensures that the program is consistent with the latest
14942version of the source files that can be located at bind time. Editing a
14943source file without compiling files that depend on the source file cause
14944error messages to be generated by the binder.
14945
14946For example, suppose you have a main program @code{hello.adb} and a
14947package @cite{P}, from file @code{p.ads} and you perform the following
14948steps:
14949
14950
14951@itemize *
14952
14953@item 
14954Enter @cite{gcc -c hello.adb} to compile the main program.
14955
14956@item 
14957Enter @cite{gcc -c p.ads} to compile package @cite{P}.
14958
14959@item 
14960Edit file @code{p.ads}.
14961
14962@item 
14963Enter @cite{gnatbind hello}.
14964@end itemize
14965
14966At this point, the file @code{p.ali} contains an out-of-date time stamp
14967because the file @code{p.ads} has been edited. The attempt at binding
14968fails, and the binder generates the following error messages:
14969
14970@example
14971error: "hello.adb" must be recompiled ("p.ads" has been modified)
14972error: "p.ads" has been modified and must be recompiled
14973@end example
14974
14975Now both files must be recompiled as indicated, and then the bind can
14976succeed, generating a main program. You need not normally be concerned
14977with the contents of this file, but for reference purposes a sample
14978binder output file is given in @ref{10,,Example of Binder Output File}.
14979
14980In most normal usage, the default mode of @emph{gnatbind} which is to
14981generate the main package in Ada, as described in the previous section.
14982In particular, this means that any Ada programmer can read and understand
14983the generated main program. It can also be debugged just like any other
14984Ada code provided the @emph{-g} switch is used for
14985@emph{gnatbind} and @emph{gnatlink}.
14986
14987@node Switches for gnatbind,Command-Line Access,Running gnatbind,Binding with gnatbind
14988@anchor{gnat_ugn/building_executable_programs_with_gnat id33}@anchor{122}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatbind}@anchor{123}
14989@subsection Switches for @emph{gnatbind}
14990
14991
14992The following switches are available with @cite{gnatbind}; details will
14993be presented in subsequent sections.
14994
14995@geindex --version (gnatbind)
14996
14997
14998@table @asis
14999
15000@item @code{--version}
15001
15002Display Copyright and version, then exit disregarding all other options.
15003@end table
15004
15005@geindex --help (gnatbind)
15006
15007
15008@table @asis
15009
15010@item @code{--help}
15011
15012If @emph{--version} was not used, display usage, then exit disregarding
15013all other options.
15014@end table
15015
15016@geindex -a (gnatbind)
15017
15018
15019@table @asis
15020
15021@item @code{-a}
15022
15023Indicates that, if supported by the platform, the adainit procedure should
15024be treated as an initialisation routine by the linker (a constructor). This
15025is intended to be used by the Project Manager to automatically initialize
15026shared Stand-Alone Libraries.
15027@end table
15028
15029@geindex -aO (gnatbind)
15030
15031
15032@table @asis
15033
15034@item @code{-aO}
15035
15036Specify directory to be searched for ALI files.
15037@end table
15038
15039@geindex -aI (gnatbind)
15040
15041
15042@table @asis
15043
15044@item @code{-aI}
15045
15046Specify directory to be searched for source file.
15047@end table
15048
15049@geindex -A (gnatbind)
15050
15051
15052@table @asis
15053
15054@item @code{-A[=@emph{filename}]}
15055
15056Output ALI list (to standard output or to the named file).
15057@end table
15058
15059@geindex -b (gnatbind)
15060
15061
15062@table @asis
15063
15064@item @code{-b}
15065
15066Generate brief messages to @code{stderr} even if verbose mode set.
15067@end table
15068
15069@geindex -c (gnatbind)
15070
15071
15072@table @asis
15073
15074@item @code{-c}
15075
15076Check only, no generation of binder output file.
15077@end table
15078
15079@geindex -dnn[k|m] (gnatbind)
15080
15081
15082@table @asis
15083
15084@item @code{-d@emph{nn}[k|m]}
15085
15086This switch can be used to change the default task stack size value
15087to a specified size @cite{nn}, which is expressed in bytes by default, or
15088in kilobytes when suffixed with @cite{k} or in megabytes when suffixed
15089with @cite{m}.
15090In the absence of a @code{[k|m]} suffix, this switch is equivalent,
15091in effect, to completing all task specs with
15092
15093@example
15094pragma Storage_Size (nn);
15095@end example
15096
15097When they do not already have such a pragma.
15098@end table
15099
15100@geindex -D (gnatbind)
15101
15102
15103@table @asis
15104
15105@item @code{-D@emph{nn}[k|m]}
15106
15107This switch can be used to change the default secondary stack size value
15108to a specified size @cite{nn}, which is expressed in bytes by default, or
15109in kilobytes when suffixed with @cite{k} or in megabytes when suffixed
15110with @cite{m}.
15111
15112The secondary stack is used to deal with functions that return a variable
15113sized result, for example a function returning an unconstrained
15114String. There are two ways in which this secondary stack is allocated.
15115
15116For most targets, the secondary stack is growing on demand and is allocated
15117as a chain of blocks in the heap. The -D option is not very
15118relevant. It only give some control over the size of the allocated
15119blocks (whose size is the minimum of the default secondary stack size value,
15120and the actual size needed for the current allocation request).
15121
15122For certain targets, notably VxWorks 653,
15123the secondary stack is allocated by carving off a fixed ratio chunk of the
15124primary task stack. The -D option is used to define the
15125size of the environment task's secondary stack.
15126@end table
15127
15128@geindex -e (gnatbind)
15129
15130
15131@table @asis
15132
15133@item @code{-e}
15134
15135Output complete list of elaboration-order dependencies.
15136@end table
15137
15138@geindex -E (gnatbind)
15139
15140
15141@table @asis
15142
15143@item @code{-E}
15144
15145Store tracebacks in exception occurrences when the target supports it.
15146
15147See also the packages @cite{GNAT.Traceback} and
15148@cite{GNAT.Traceback.Symbolic} for more information.
15149Note that on x86 ports, you must not use @emph{-fomit-frame-pointer}
15150@emph{gcc} option.
15151@end table
15152
15153@geindex -F (gnatbind)
15154
15155
15156@table @asis
15157
15158@item @code{-F}
15159
15160Force the checks of elaboration flags. @emph{gnatbind} does not normally
15161generate checks of elaboration flags for the main executable, except when
15162a Stand-Alone Library is used. However, there are cases when this cannot be
15163detected by gnatbind. An example is importing an interface of a Stand-Alone
15164Library through a pragma Import and only specifying through a linker switch
15165this Stand-Alone Library. This switch is used to guarantee that elaboration
15166flag checks are generated.
15167@end table
15168
15169@geindex -h (gnatbind)
15170
15171
15172@table @asis
15173
15174@item @code{-h}
15175
15176Output usage (help) information
15177
15178@geindex -H32 (gnatbind)
15179
15180@item @code{-H32}
15181
15182Use 32-bit allocations for @cite{__gnat_malloc} (and thus for access types).
15183For further details see @ref{124,,Dynamic Allocation Control}.
15184
15185@geindex -H64 (gnatbind)
15186
15187@geindex __gnat_malloc
15188
15189@item @code{-H64}
15190
15191Use 64-bit allocations for @cite{__gnat_malloc} (and thus for access types).
15192For further details see @ref{124,,Dynamic Allocation Control}.
15193
15194@geindex -I (gnatbind)
15195
15196@item @code{-I}
15197
15198Specify directory to be searched for source and ALI files.
15199
15200@geindex -I- (gnatbind)
15201
15202@item @code{-I-}
15203
15204Do not look for sources in the current directory where @cite{gnatbind} was
15205invoked, and do not look for ALI files in the directory containing the
15206ALI file named in the @cite{gnatbind} command line.
15207
15208@geindex -l (gnatbind)
15209
15210@item @code{-l}
15211
15212Output chosen elaboration order.
15213
15214@geindex -L (gnatbind)
15215
15216@item @code{-L@emph{xxx}}
15217
15218Bind the units for library building. In this case the adainit and
15219adafinal procedures (@ref{ba,,Binding with Non-Ada Main Programs})
15220are renamed to @cite{xxx`init and `xxx`final. Implies -n. (:ref:`GNAT_and_Libraries}, for more details.)
15221
15222@geindex -M (gnatbind)
15223
15224@item @code{-M@emph{xyz}}
15225
15226Rename generated main program from main to xyz. This option is
15227supported on cross environments only.
15228
15229@geindex -m (gnatbind)
15230
15231@item @code{-m@emph{n}}
15232
15233Limit number of detected errors or warnings to @cite{n}, where @cite{n} is
15234in the range 1..999999. The default value if no switch is
15235given is 9999. If the number of warnings reaches this limit, then a
15236message is output and further warnings are suppressed, the bind
15237continues in this case. If the number of errors reaches this
15238limit, then a message is output and the bind is abandoned.
15239A value of zero means that no limit is enforced. The equal
15240sign is optional.
15241
15242@geindex -n (gnatbind)
15243
15244@item @code{-n}
15245
15246No main program.
15247
15248@geindex -nostdinc (gnatbind)
15249
15250@item @code{-nostdinc}
15251
15252Do not look for sources in the system default directory.
15253
15254@geindex -nostdlib (gnatbind)
15255
15256@item @code{-nostdlib}
15257
15258Do not look for library files in the system default directory.
15259
15260@geindex --RTS (gnatbind)
15261
15262@item @code{--RTS=@emph{rts-path}}
15263
15264Specifies the default location of the runtime library. Same meaning as the
15265equivalent @emph{gnatmake} flag (@ref{df,,Switches for gnatmake}).
15266
15267@geindex -o (gnatbind)
15268
15269@item @code{-o @emph{file}}
15270
15271Name the output file @cite{file} (default is @code{b~`xxx}.adb`).
15272Note that if this option is used, then linking must be done manually,
15273gnatlink cannot be used.
15274
15275@geindex -O (gnatbind)
15276
15277@item @code{-O[=@emph{filename}]}
15278
15279Output object list (to standard output or to the named file).
15280
15281@geindex -p (gnatbind)
15282
15283@item @code{-p}
15284
15285Pessimistic (worst-case) elaboration order
15286
15287@geindex -P (gnatbind)
15288
15289@item @code{-P}
15290
15291Generate binder file suitable for CodePeer.
15292
15293@geindex -R (gnatbind)
15294
15295@item @code{-R}
15296
15297Output closure source list, which includes all non-run-time units that are
15298included in the bind.
15299
15300@geindex -Ra (gnatbind)
15301
15302@item @code{-Ra}
15303
15304Like @emph{-R} but the list includes run-time units.
15305
15306@geindex -s (gnatbind)
15307
15308@item @code{-s}
15309
15310Require all source files to be present.
15311
15312@geindex -S (gnatbind)
15313
15314@item @code{-S@emph{xxx}}
15315
15316Specifies the value to be used when detecting uninitialized scalar
15317objects with pragma Initialize_Scalars.
15318The @cite{xxx} string specified with the switch is one of:
15319
15320
15321@itemize *
15322
15323@item 
15324@code{in} for an invalid value*.
15325
15326If zero is invalid for the discrete type in question,
15327then the scalar value is set to all zero bits.
15328For signed discrete types, the largest possible negative value of
15329the underlying scalar is set (i.e. a one bit followed by all zero bits).
15330For unsigned discrete types, the underlying scalar value is set to all
15331one bits. For floating-point types, a NaN value is set
15332(see body of package System.Scalar_Values for exact values).
15333
15334@item 
15335@code{lo} for low value.
15336
15337If zero is invalid for the discrete type in question,
15338then the scalar value is set to all zero bits.
15339For signed discrete types, the largest possible negative value of
15340the underlying scalar is set (i.e. a one bit followed by all zero bits).
15341For unsigned discrete types, the underlying scalar value is set to all
15342zero bits. For floating-point, a small value is set
15343(see body of package System.Scalar_Values for exact values).
15344
15345@item 
15346@code{hi} for high value.
15347
15348If zero is invalid for the discrete type in question,
15349then the scalar value is set to all one bits.
15350For signed discrete types, the largest possible positive value of
15351the underlying scalar is set (i.e. a zero bit followed by all one bits).
15352For unsigned discrete types, the underlying scalar value is set to all
15353one bits. For floating-point, a large value is set
15354(see body of package System.Scalar_Values for exact values).
15355
15356@item 
15357@cite{xx} for hex value (two hex digits).
15358
15359The underlying scalar is set to a value consisting of repeated bytes, whose
15360value corresponds to the given value. For example if @code{BF} is given,
15361then a 32-bit scalar value will be set to the bit patterm @code{16#BFBFBFBF#}.
15362@end itemize
15363
15364@geindex GNAT_INIT_SCALARS
15365
15366In addition, you can specify @emph{-Sev} to indicate that the value is
15367to be set at run time. In this case, the program will look for an environment
15368variable of the form @code{GNAT_INIT_SCALARS=@emph{yy}}, where @cite{yy} is one
15369of @emph{in/lo/hi/`xx*` with the same meanings as above.
15370If no environment variable is found, or if it does not have a valid value,
15371then the default is *in} (invalid values).
15372@end table
15373
15374@geindex -static (gnatbind)
15375
15376
15377@table @asis
15378
15379@item @code{-static}
15380
15381Link against a static GNAT run time.
15382
15383@geindex -shared (gnatbind)
15384
15385@item @code{-shared}
15386
15387Link against a shared GNAT run time when available.
15388
15389@geindex -t (gnatbind)
15390
15391@item @code{-t}
15392
15393Tolerate time stamp and other consistency errors
15394
15395@geindex -T (gnatbind)
15396
15397@item @code{-T@emph{n}}
15398
15399Set the time slice value to @cite{n} milliseconds. If the system supports
15400the specification of a specific time slice value, then the indicated value
15401is used. If the system does not support specific time slice values, but
15402does support some general notion of round-robin scheduling, then any
15403nonzero value will activate round-robin scheduling.
15404
15405A value of zero is treated specially. It turns off time
15406slicing, and in addition, indicates to the tasking run time that the
15407semantics should match as closely as possible the Annex D
15408requirements of the Ada RM, and in particular sets the default
15409scheduling policy to @cite{FIFO_Within_Priorities}.
15410
15411@geindex -u (gnatbind)
15412
15413@item @code{-u@emph{n}}
15414
15415Enable dynamic stack usage, with @cite{n} results stored and displayed
15416at program termination. A result is generated when a task
15417terminates. Results that can't be stored are displayed on the fly, at
15418task termination. This option is currently not supported on Itanium
15419platforms. (See @ref{125,,Dynamic Stack Usage Analysis} for details.)
15420
15421@geindex -v (gnatbind)
15422
15423@item @code{-v}
15424
15425Verbose mode. Write error messages, header, summary output to
15426@code{stdout}.
15427
15428@geindex -w (gnatbind)
15429
15430@item @code{-w@emph{x}}
15431
15432Warning mode; @cite{x} = s/e for suppress/treat as error
15433
15434@geindex -Wx (gnatbind)
15435
15436@item @code{-Wx@emph{e}}
15437
15438Override default wide character encoding for standard Text_IO files.
15439
15440@geindex -x (gnatbind)
15441
15442@item @code{-x}
15443
15444Exclude source files (check object consistency only).
15445
15446@geindex -Xnnn (gnatbind)
15447
15448@item @code{-X@emph{nnn}}
15449
15450Set default exit status value, normally 0 for POSIX compliance.
15451
15452@geindex -y (gnatbind)
15453
15454@item @code{-y}
15455
15456Enable leap seconds support in @cite{Ada.Calendar} and its children.
15457
15458@geindex -z (gnatbind)
15459
15460@item @code{-z}
15461
15462No main subprogram.
15463@end table
15464
15465You may obtain this listing of switches by running @cite{gnatbind} with
15466no arguments.
15467
15468@menu
15469* Consistency-Checking Modes:: 
15470* Binder Error Message Control:: 
15471* Elaboration Control:: 
15472* Output Control:: 
15473* Dynamic Allocation Control:: 
15474* Binding with Non-Ada Main Programs:: 
15475* Binding Programs with No Main Subprogram:: 
15476
15477@end menu
15478
15479@node Consistency-Checking Modes,Binder Error Message Control,,Switches for gnatbind
15480@anchor{gnat_ugn/building_executable_programs_with_gnat consistency-checking-modes}@anchor{126}@anchor{gnat_ugn/building_executable_programs_with_gnat id34}@anchor{127}
15481@subsubsection Consistency-Checking Modes
15482
15483
15484As described earlier, by default @cite{gnatbind} checks
15485that object files are consistent with one another and are consistent
15486with any source files it can locate. The following switches control binder
15487access to sources.
15488
15489@quotation
15490
15491@geindex -s (gnatbind)
15492@end quotation
15493
15494
15495@table @asis
15496
15497@item @code{-s}
15498
15499Require source files to be present. In this mode, the binder must be
15500able to locate all source files that are referenced, in order to check
15501their consistency. In normal mode, if a source file cannot be located it
15502is simply ignored. If you specify this switch, a missing source
15503file is an error.
15504
15505@geindex -Wx (gnatbind)
15506
15507@item @code{-Wx@emph{e}}
15508
15509Override default wide character encoding for standard Text_IO files.
15510Normally the default wide character encoding method used for standard
15511[Wide_[Wide_]]Text_IO files is taken from the encoding specified for
15512the main source input (see description of switch
15513@emph{-gnatWx} for the compiler). The
15514use of this switch for the binder (which has the same set of
15515possible arguments) overrides this default as specified.
15516
15517@geindex -x (gnatbind)
15518
15519@item @code{-x}
15520
15521Exclude source files. In this mode, the binder only checks that ALI
15522files are consistent with one another. Source files are not accessed.
15523The binder runs faster in this mode, and there is still a guarantee that
15524the resulting program is self-consistent.
15525If a source file has been edited since it was last compiled, and you
15526specify this switch, the binder will not detect that the object
15527file is out of date with respect to the source file. Note that this is the
15528mode that is automatically used by @emph{gnatmake} because in this
15529case the checking against sources has already been performed by
15530@emph{gnatmake} in the course of compilation (i.e., before binding).
15531@end table
15532
15533@node Binder Error Message Control,Elaboration Control,Consistency-Checking Modes,Switches for gnatbind
15534@anchor{gnat_ugn/building_executable_programs_with_gnat id35}@anchor{128}@anchor{gnat_ugn/building_executable_programs_with_gnat binder-error-message-control}@anchor{129}
15535@subsubsection Binder Error Message Control
15536
15537
15538The following switches provide control over the generation of error
15539messages from the binder:
15540
15541@quotation
15542
15543@geindex -v (gnatbind)
15544@end quotation
15545
15546
15547@table @asis
15548
15549@item @code{-v}
15550
15551Verbose mode. In the normal mode, brief error messages are generated to
15552@code{stderr}. If this switch is present, a header is written
15553to @code{stdout} and any error messages are directed to @code{stdout}.
15554All that is written to @code{stderr} is a brief summary message.
15555
15556@geindex -b (gnatbind)
15557
15558@item @code{-b}
15559
15560Generate brief error messages to @code{stderr} even if verbose mode is
15561specified. This is relevant only when used with the
15562@emph{-v} switch.
15563
15564@geindex -m (gnatbind)
15565
15566@item @code{-m@emph{n}}
15567
15568Limits the number of error messages to @cite{n}, a decimal integer in the
15569range 1-999. The binder terminates immediately if this limit is reached.
15570
15571@geindex -M (gnatbind)
15572
15573@item @code{-M@emph{xxx}}
15574
15575Renames the generated main program from @cite{main} to @cite{xxx}.
15576This is useful in the case of some cross-building environments, where
15577the actual main program is separate from the one generated
15578by @cite{gnatbind}.
15579
15580@geindex -ws (gnatbind)
15581
15582@geindex Warnings
15583
15584@item @code{-ws}
15585
15586Suppress all warning messages.
15587
15588@geindex -we (gnatbind)
15589
15590@item @code{-we}
15591
15592Treat any warning messages as fatal errors.
15593
15594@geindex -t (gnatbind)
15595
15596@geindex Time stamp checks
15597@geindex in binder
15598
15599@geindex Binder consistency checks
15600
15601@geindex Consistency checks
15602@geindex in binder
15603
15604@item @code{-t}
15605
15606The binder performs a number of consistency checks including:
15607
15608
15609@itemize *
15610
15611@item 
15612Check that time stamps of a given source unit are consistent
15613
15614@item 
15615Check that checksums of a given source unit are consistent
15616
15617@item 
15618Check that consistent versions of @cite{GNAT} were used for compilation
15619
15620@item 
15621Check consistency of configuration pragmas as required
15622@end itemize
15623
15624Normally failure of such checks, in accordance with the consistency
15625requirements of the Ada Reference Manual, causes error messages to be
15626generated which abort the binder and prevent the output of a binder
15627file and subsequent link to obtain an executable.
15628
15629The @emph{-t} switch converts these error messages
15630into warnings, so that
15631binding and linking can continue to completion even in the presence of such
15632errors. The result may be a failed link (due to missing symbols), or a
15633non-functional executable which has undefined semantics.
15634
15635@cartouche
15636@quotation Note 
15637This means that @emph{-t} should be used only in unusual situations,
15638with extreme care.
15639@end quotation
15640@end cartouche
15641@end table
15642
15643@node Elaboration Control,Output Control,Binder Error Message Control,Switches for gnatbind
15644@anchor{gnat_ugn/building_executable_programs_with_gnat id36}@anchor{12a}@anchor{gnat_ugn/building_executable_programs_with_gnat elaboration-control}@anchor{12b}
15645@subsubsection Elaboration Control
15646
15647
15648The following switches provide additional control over the elaboration
15649order. For full details see @ref{11,,Elaboration Order Handling in GNAT}.
15650
15651@quotation
15652
15653@geindex -p (gnatbind)
15654@end quotation
15655
15656
15657@table @asis
15658
15659@item @code{-p}
15660
15661Normally the binder attempts to choose an elaboration order that is
15662likely to minimize the likelihood of an elaboration order error resulting
15663in raising a @cite{Program_Error} exception. This switch reverses the
15664action of the binder, and requests that it deliberately choose an order
15665that is likely to maximize the likelihood of an elaboration error.
15666This is useful in ensuring portability and avoiding dependence on
15667accidental fortuitous elaboration ordering.
15668
15669Normally it only makes sense to use the @emph{-p}
15670switch if dynamic
15671elaboration checking is used (@emph{-gnatE} switch used for compilation).
15672This is because in the default static elaboration mode, all necessary
15673@cite{Elaborate} and @cite{Elaborate_All} pragmas are implicitly inserted.
15674These implicit pragmas are still respected by the binder in
15675@emph{-p} mode, so a
15676safe elaboration order is assured.
15677
15678Note that @emph{-p} is not intended for
15679production use; it is more for debugging/experimental use.
15680@end table
15681
15682@node Output Control,Dynamic Allocation Control,Elaboration Control,Switches for gnatbind
15683@anchor{gnat_ugn/building_executable_programs_with_gnat output-control}@anchor{12c}@anchor{gnat_ugn/building_executable_programs_with_gnat id37}@anchor{12d}
15684@subsubsection Output Control
15685
15686
15687The following switches allow additional control over the output
15688generated by the binder.
15689
15690@quotation
15691
15692@geindex -c (gnatbind)
15693@end quotation
15694
15695
15696@table @asis
15697
15698@item @code{-c}
15699
15700Check only. Do not generate the binder output file. In this mode the
15701binder performs all error checks but does not generate an output file.
15702
15703@geindex -e (gnatbind)
15704
15705@item @code{-e}
15706
15707Output complete list of elaboration-order dependencies, showing the
15708reason for each dependency. This output can be rather extensive but may
15709be useful in diagnosing problems with elaboration order. The output is
15710written to @code{stdout}.
15711
15712@geindex -h (gnatbind)
15713
15714@item @code{-h}
15715
15716Output usage information. The output is written to @code{stdout}.
15717
15718@geindex -K (gnatbind)
15719
15720@item @code{-K}
15721
15722Output linker options to @code{stdout}. Includes library search paths,
15723contents of pragmas Ident and Linker_Options, and libraries added
15724by @cite{gnatbind}.
15725
15726@geindex -l (gnatbind)
15727
15728@item @code{-l}
15729
15730Output chosen elaboration order. The output is written to @code{stdout}.
15731
15732@geindex -O (gnatbind)
15733
15734@item @code{-O}
15735
15736Output full names of all the object files that must be linked to provide
15737the Ada component of the program. The output is written to @code{stdout}.
15738This list includes the files explicitly supplied and referenced by the user
15739as well as implicitly referenced run-time unit files. The latter are
15740omitted if the corresponding units reside in shared libraries. The
15741directory names for the run-time units depend on the system configuration.
15742
15743@geindex -o (gnatbind)
15744
15745@item @code{-o @emph{file}}
15746
15747Set name of output file to @cite{file} instead of the normal
15748@code{b~`mainprog}.adb` default. Note that @cite{file} denote the Ada
15749binder generated body filename.
15750Note that if this option is used, then linking must be done manually.
15751It is not possible to use gnatlink in this case, since it cannot locate
15752the binder file.
15753
15754@geindex -r (gnatbind)
15755
15756@item @code{-r}
15757
15758Generate list of @cite{pragma Restrictions} that could be applied to
15759the current unit. This is useful for code audit purposes, and also may
15760be used to improve code generation in some cases.
15761@end table
15762
15763@node Dynamic Allocation Control,Binding with Non-Ada Main Programs,Output Control,Switches for gnatbind
15764@anchor{gnat_ugn/building_executable_programs_with_gnat dynamic-allocation-control}@anchor{124}@anchor{gnat_ugn/building_executable_programs_with_gnat id38}@anchor{12e}
15765@subsubsection Dynamic Allocation Control
15766
15767
15768The heap control switches -- @emph{-H32} and @emph{-H64} --
15769determine whether dynamic allocation uses 32-bit or 64-bit memory.
15770They only affect compiler-generated allocations via @cite{__gnat_malloc};
15771explicit calls to @cite{malloc} and related functions from the C
15772run-time library are unaffected.
15773
15774
15775@table @asis
15776
15777@item @code{-H32}
15778
15779Allocate memory on 32-bit heap
15780
15781@item @code{-H64}
15782
15783Allocate memory on 64-bit heap.  This is the default
15784unless explicitly overridden by a @cite{'Size} clause on the access type.
15785@end table
15786
15787These switches are only effective on VMS platforms.
15788
15789@node Binding with Non-Ada Main Programs,Binding Programs with No Main Subprogram,Dynamic Allocation Control,Switches for gnatbind
15790@anchor{gnat_ugn/building_executable_programs_with_gnat binding-with-non-ada-main-programs}@anchor{ba}@anchor{gnat_ugn/building_executable_programs_with_gnat id39}@anchor{12f}
15791@subsubsection Binding with Non-Ada Main Programs
15792
15793
15794The description so far has assumed that the main
15795program is in Ada, and that the task of the binder is to generate a
15796corresponding function @cite{main} that invokes this Ada main
15797program. GNAT also supports the building of executable programs where
15798the main program is not in Ada, but some of the called routines are
15799written in Ada and compiled using GNAT (@ref{46,,Mixed Language Programming}).
15800The following switch is used in this situation:
15801
15802@quotation
15803
15804@geindex -n (gnatbind)
15805@end quotation
15806
15807
15808@table @asis
15809
15810@item @code{-n}
15811
15812No main program. The main program is not in Ada.
15813@end table
15814
15815In this case, most of the functions of the binder are still required,
15816but instead of generating a main program, the binder generates a file
15817containing the following callable routines:
15818
15819@quotation
15820
15821@geindex adainit
15822
15823
15824@table @asis
15825
15826@item @emph{adainit}
15827
15828You must call this routine to initialize the Ada part of the program by
15829calling the necessary elaboration routines. A call to @cite{adainit} is
15830required before the first call to an Ada subprogram.
15831
15832Note that it is assumed that the basic execution environment must be setup
15833to be appropriate for Ada execution at the point where the first Ada
15834subprogram is called. In particular, if the Ada code will do any
15835floating-point operations, then the FPU must be setup in an appropriate
15836manner. For the case of the x86, for example, full precision mode is
15837required. The procedure GNAT.Float_Control.Reset may be used to ensure
15838that the FPU is in the right state.
15839@end table
15840
15841@geindex adafinal
15842
15843
15844@table @asis
15845
15846@item @emph{adafinal}
15847
15848You must call this routine to perform any library-level finalization
15849required by the Ada subprograms. A call to @cite{adafinal} is required
15850after the last call to an Ada subprogram, and before the program
15851terminates.
15852@end table
15853@end quotation
15854
15855@geindex -n (gnatbind)
15856
15857@geindex Binder
15858@geindex multiple input files
15859
15860If the @emph{-n} switch
15861is given, more than one ALI file may appear on
15862the command line for @cite{gnatbind}. The normal @emph{closure}
15863calculation is performed for each of the specified units. Calculating
15864the closure means finding out the set of units involved by tracing
15865@emph{with} references. The reason it is necessary to be able to
15866specify more than one ALI file is that a given program may invoke two or
15867more quite separate groups of Ada units.
15868
15869The binder takes the name of its output file from the last specified ALI
15870file, unless overridden by the use of the @emph{-o file}.
15871
15872@geindex -o (gnatbind)
15873
15874The output is an Ada unit in source form that can be compiled with GNAT.
15875This compilation occurs automatically as part of the @emph{gnatlink}
15876processing.
15877
15878Currently the GNAT run time requires a FPU using 80 bits mode
15879precision. Under targets where this is not the default it is required to
15880call GNAT.Float_Control.Reset before using floating point numbers (this
15881include float computation, float input and output) in the Ada code. A
15882side effect is that this could be the wrong mode for the foreign code
15883where floating point computation could be broken after this call.
15884
15885@node Binding Programs with No Main Subprogram,,Binding with Non-Ada Main Programs,Switches for gnatbind
15886@anchor{gnat_ugn/building_executable_programs_with_gnat binding-programs-with-no-main-subprogram}@anchor{130}@anchor{gnat_ugn/building_executable_programs_with_gnat id40}@anchor{131}
15887@subsubsection Binding Programs with No Main Subprogram
15888
15889
15890It is possible to have an Ada program which does not have a main
15891subprogram. This program will call the elaboration routines of all the
15892packages, then the finalization routines.
15893
15894The following switch is used to bind programs organized in this manner:
15895
15896@quotation
15897
15898@geindex -z (gnatbind)
15899@end quotation
15900
15901
15902@table @asis
15903
15904@item @code{-z}
15905
15906Normally the binder checks that the unit name given on the command line
15907corresponds to a suitable main subprogram. When this switch is used,
15908a list of ALI files can be given, and the execution of the program
15909consists of elaboration of these units in an appropriate order. Note
15910that the default wide character encoding method for standard Text_IO
15911files is always set to Brackets if this switch is set (you can use
15912the binder switch
15913@emph{-Wx} to override this default).
15914@end table
15915
15916@node Command-Line Access,Search Paths for gnatbind,Switches for gnatbind,Binding with gnatbind
15917@anchor{gnat_ugn/building_executable_programs_with_gnat id41}@anchor{132}@anchor{gnat_ugn/building_executable_programs_with_gnat command-line-access}@anchor{133}
15918@subsection Command-Line Access
15919
15920
15921The package @cite{Ada.Command_Line} provides access to the command-line
15922arguments and program name. In order for this interface to operate
15923correctly, the two variables
15924
15925@example
15926int gnat_argc;
15927char **gnat_argv;
15928@end example
15929
15930@geindex gnat_argv
15931
15932@geindex gnat_argc
15933
15934are declared in one of the GNAT library routines. These variables must
15935be set from the actual @cite{argc} and @cite{argv} values passed to the
15936main program. With no @emph{n} present, @cite{gnatbind}
15937generates the C main program to automatically set these variables.
15938If the @emph{n} switch is used, there is no automatic way to
15939set these variables. If they are not set, the procedures in
15940@cite{Ada.Command_Line} will not be available, and any attempt to use
15941them will raise @cite{Constraint_Error}. If command line access is
15942required, your main program must set @cite{gnat_argc} and
15943@cite{gnat_argv} from the @cite{argc} and @cite{argv} values passed to
15944it.
15945
15946@node Search Paths for gnatbind,Examples of gnatbind Usage,Command-Line Access,Binding with gnatbind
15947@anchor{gnat_ugn/building_executable_programs_with_gnat search-paths-for-gnatbind}@anchor{91}@anchor{gnat_ugn/building_executable_programs_with_gnat id42}@anchor{134}
15948@subsection Search Paths for @cite{gnatbind}
15949
15950
15951The binder takes the name of an ALI file as its argument and needs to
15952locate source files as well as other ALI files to verify object consistency.
15953
15954For source files, it follows exactly the same search rules as @emph{gcc}
15955(see @ref{8e,,Search Paths and the Run-Time Library (RTL)}). For ALI files the
15956directories searched are:
15957
15958
15959@itemize *
15960
15961@item 
15962The directory containing the ALI file named in the command line, unless
15963the switch @emph{-I-} is specified.
15964
15965@item 
15966All directories specified by @emph{-I}
15967switches on the @cite{gnatbind}
15968command line, in the order given.
15969
15970@geindex ADA_PRJ_OBJECTS_FILE
15971
15972@item 
15973Each of the directories listed in the text file whose name is given
15974by the 
15975@geindex ADA_PRJ_OBJECTS_FILE
15976@geindex environment variable; ADA_PRJ_OBJECTS_FILE
15977@code{ADA_PRJ_OBJECTS_FILE} environment variable.
15978
15979@geindex ADA_PRJ_OBJECTS_FILE
15980@geindex environment variable; ADA_PRJ_OBJECTS_FILE
15981@code{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the gnat
15982driver when project files are used. It should not normally be set
15983by other means.
15984
15985@geindex ADA_OBJECTS_PATH
15986
15987@item 
15988Each of the directories listed in the value of the
15989@geindex ADA_OBJECTS_PATH
15990@geindex environment variable; ADA_OBJECTS_PATH
15991@code{ADA_OBJECTS_PATH} environment variable.
15992Construct this value
15993exactly as the 
15994@geindex PATH
15995@geindex environment variable; PATH
15996@code{PATH} environment variable: a list of directory
15997names separated by colons (semicolons when working with the NT version
15998of GNAT).
15999
16000@item 
16001The content of the @code{ada_object_path} file which is part of the GNAT
16002installation tree and is used to store standard libraries such as the
16003GNAT Run Time Library (RTL) unless the switch @emph{-nostdlib} is
16004specified. See @ref{8b,,Installing a library}
16005@end itemize
16006
16007@geindex -I (gnatbind)
16008
16009@geindex -aI (gnatbind)
16010
16011@geindex -aO (gnatbind)
16012
16013In the binder the switch @emph{-I}
16014is used to specify both source and
16015library file paths. Use @emph{-aI}
16016instead if you want to specify
16017source paths only, and @emph{-aO}
16018if you want to specify library paths
16019only. This means that for the binder
16020@code{-I@emph{dir}} is equivalent to
16021@code{-aI@emph{dir}}
16022@code{-aO`@emph{dir}}.
16023The binder generates the bind file (a C language source file) in the
16024current working directory.
16025
16026@geindex Ada
16027
16028@geindex System
16029
16030@geindex Interfaces
16031
16032@geindex GNAT
16033
16034The packages @cite{Ada}, @cite{System}, and @cite{Interfaces} and their
16035children make up the GNAT Run-Time Library, together with the package
16036GNAT and its children, which contain a set of useful additional
16037library functions provided by GNAT. The sources for these units are
16038needed by the compiler and are kept together in one directory. The ALI
16039files and object files generated by compiling the RTL are needed by the
16040binder and the linker and are kept together in one directory, typically
16041different from the directory containing the sources. In a normal
16042installation, you need not specify these directory names when compiling
16043or binding. Either the environment variables or the built-in defaults
16044cause these files to be found.
16045
16046Besides simplifying access to the RTL, a major use of search paths is
16047in compiling sources from multiple directories. This can make
16048development environments much more flexible.
16049
16050@node Examples of gnatbind Usage,,Search Paths for gnatbind,Binding with gnatbind
16051@anchor{gnat_ugn/building_executable_programs_with_gnat examples-of-gnatbind-usage}@anchor{135}@anchor{gnat_ugn/building_executable_programs_with_gnat id43}@anchor{136}
16052@subsection Examples of @cite{gnatbind} Usage
16053
16054
16055Here are some examples of @cite{gnatbind} invovations:
16056
16057@quotation
16058
16059@example
16060gnatbind hello
16061@end example
16062
16063The main program @cite{Hello} (source program in @code{hello.adb}) is
16064bound using the standard switch settings. The generated main program is
16065@code{b~hello.adb}. This is the normal, default use of the binder.
16066
16067@example
16068gnatbind hello -o mainprog.adb
16069@end example
16070
16071The main program @cite{Hello} (source program in @code{hello.adb}) is
16072bound using the standard switch settings. The generated main program is
16073@code{mainprog.adb} with the associated spec in
16074@code{mainprog.ads}. Note that you must specify the body here not the
16075spec. Note that if this option is used, then linking must be done manually,
16076since gnatlink will not be able to find the generated file.
16077@end quotation
16078
16079@node Linking with gnatlink,Using the GNU make Utility,Binding with gnatbind,Building Executable Programs with GNAT
16080@anchor{gnat_ugn/building_executable_programs_with_gnat id44}@anchor{137}@anchor{gnat_ugn/building_executable_programs_with_gnat linking-with-gnatlink}@anchor{20}
16081@section Linking with @emph{gnatlink}
16082
16083
16084@c index: ! gnatlink
16085
16086This chapter discusses @emph{gnatlink}, a tool that links
16087an Ada program and builds an executable file. This utility
16088invokes the system linker (via the @emph{gcc} command)
16089with a correct list of object files and library references.
16090@emph{gnatlink} automatically determines the list of files and
16091references for the Ada part of a program. It uses the binder file
16092generated by the @emph{gnatbind} to determine this list.
16093
16094Note: to invoke @cite{gnatlink} with a project file, use the @cite{gnat}
16095driver (see @ref{11f,,The GNAT Driver and Project Files}).
16096
16097@menu
16098* Running gnatlink:: 
16099* Switches for gnatlink:: 
16100
16101@end menu
16102
16103@node Running gnatlink,Switches for gnatlink,,Linking with gnatlink
16104@anchor{gnat_ugn/building_executable_programs_with_gnat id45}@anchor{138}@anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatlink}@anchor{139}
16105@subsection Running @emph{gnatlink}
16106
16107
16108The form of the @emph{gnatlink} command is
16109
16110@example
16111$ gnatlink [`switches`] `mainprog`[.ali]
16112           [`non-Ada objects`] [`linker options`]
16113@end example
16114
16115The arguments of @emph{gnatlink} (switches, main @code{ALI} file,
16116non-Ada objects
16117or linker options) may be in any order, provided that no non-Ada object may
16118be mistaken for a main @code{ALI} file.
16119Any file name @code{F} without the @code{.ali}
16120extension will be taken as the main @code{ALI} file if a file exists
16121whose name is the concatenation of @code{F} and @code{.ali}.
16122
16123@code{mainprog.ali} references the ALI file of the main program.
16124The @code{.ali} extension of this file can be omitted. From this
16125reference, @emph{gnatlink} locates the corresponding binder file
16126@code{b~mainprog.adb} and, using the information in this file along
16127with the list of non-Ada objects and linker options, constructs a
16128linker command file to create the executable.
16129
16130The arguments other than the @emph{gnatlink} switches and the main
16131@code{ALI} file are passed to the linker uninterpreted.
16132They typically include the names of
16133object files for units written in other languages than Ada and any library
16134references required to resolve references in any of these foreign language
16135units, or in @cite{Import} pragmas in any Ada units.
16136
16137@cite{linker options} is an optional list of linker specific
16138switches.
16139The default linker called by gnatlink is @emph{gcc} which in
16140turn calls the appropriate system linker.
16141
16142One useful option for the linker is @emph{-s}: it reduces the size of the
16143executable by removing all symbol table and relocation information from the
16144executable.
16145
16146Standard options for the linker such as @emph{-lmy_lib} or
16147@emph{-Ldir} can be added as is.
16148For options that are not recognized by
16149@emph{gcc} as linker options, use the @emph{gcc} switches
16150@emph{-Xlinker} or @emph{-Wl,}.
16151
16152Refer to the GCC documentation for
16153details.
16154
16155Here is an example showing how to generate a linker map:
16156
16157@example
16158$ gnatlink my_prog -Wl,-Map,MAPFILE
16159@end example
16160
16161Using @cite{linker options} it is possible to set the program stack and
16162heap size.
16163See @ref{13a,,Setting Stack Size from gnatlink} and
16164@ref{13b,,Setting Heap Size from gnatlink}.
16165
16166@emph{gnatlink} determines the list of objects required by the Ada
16167program and prepends them to the list of objects passed to the linker.
16168@emph{gnatlink} also gathers any arguments set by the use of
16169@cite{pragma Linker_Options} and adds them to the list of arguments
16170presented to the linker.
16171
16172@node Switches for gnatlink,,Running gnatlink,Linking with gnatlink
16173@anchor{gnat_ugn/building_executable_programs_with_gnat id46}@anchor{13c}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatlink}@anchor{13d}
16174@subsection Switches for @emph{gnatlink}
16175
16176
16177The following switches are available with the @emph{gnatlink} utility:
16178
16179@geindex --version (gnatlink)
16180
16181
16182@table @asis
16183
16184@item @code{--version}
16185
16186Display Copyright and version, then exit disregarding all other options.
16187@end table
16188
16189@geindex --help (gnatlink)
16190
16191
16192@table @asis
16193
16194@item @code{--help}
16195
16196If @emph{--version} was not used, display usage, then exit disregarding
16197all other options.
16198@end table
16199
16200@geindex Command line length
16201
16202@geindex -f (gnatlink)
16203
16204
16205@table @asis
16206
16207@item @code{-f}
16208
16209On some targets, the command line length is limited, and @emph{gnatlink}
16210will generate a separate file for the linker if the list of object files
16211is too long.
16212The @emph{-f} switch forces this file
16213to be generated even if
16214the limit is not exceeded. This is useful in some cases to deal with
16215special situations where the command line length is exceeded.
16216@end table
16217
16218@geindex Debugging information
16219@geindex including
16220
16221@geindex -g (gnatlink)
16222
16223
16224@table @asis
16225
16226@item @code{-g}
16227
16228The option to include debugging information causes the Ada bind file (in
16229other words, @code{b~mainprog.adb}) to be compiled with @emph{-g}.
16230In addition, the binder does not delete the @code{b~mainprog.adb},
16231@code{b~mainprog.o} and @code{b~mainprog.ali} files.
16232Without @emph{-g}, the binder removes these files by default.
16233@end table
16234
16235@geindex -n (gnatlink)
16236
16237
16238@table @asis
16239
16240@item @code{-n}
16241
16242Do not compile the file generated by the binder. This may be used when
16243a link is rerun with different options, but there is no need to recompile
16244the binder file.
16245@end table
16246
16247@geindex -v (gnatlink)
16248
16249
16250@table @asis
16251
16252@item @code{-v}
16253
16254Verbose mode. Causes additional information to be output, including a full
16255list of the included object files.
16256This switch option is most useful when you want
16257to see what set of object files are being used in the link step.
16258@end table
16259
16260@geindex -v -v (gnatlink)
16261
16262
16263@table @asis
16264
16265@item @code{-v -v}
16266
16267Very verbose mode. Requests that the compiler operate in verbose mode when
16268it compiles the binder file, and that the system linker run in verbose mode.
16269@end table
16270
16271@geindex -o (gnatlink)
16272
16273
16274@table @asis
16275
16276@item @code{-o @emph{exec-name}}
16277
16278@cite{exec-name} specifies an alternate name for the generated
16279executable program. If this switch is omitted, the executable has the same
16280name as the main unit. For example, @cite{gnatlink try.ali} creates
16281an executable called @code{try}.
16282@end table
16283
16284@geindex -b (gnatlink)
16285
16286
16287@table @asis
16288
16289@item @code{-b @emph{target}}
16290
16291Compile your program to run on @cite{target}, which is the name of a
16292system configuration. You must have a GNAT cross-compiler built if
16293@cite{target} is not the same as your host system.
16294@end table
16295
16296@geindex -B (gnatlink)
16297
16298
16299@table @asis
16300
16301@item @code{-B@emph{dir}}
16302
16303Load compiler executables (for example, @cite{gnat1}, the Ada compiler)
16304from @cite{dir} instead of the default location. Only use this switch
16305when multiple versions of the GNAT compiler are available.
16306See the @cite{Directory Options} section in @cite{The_GNU_Compiler_Collection}
16307for further details. You would normally use the @emph{-b} or
16308@emph{-V} switch instead.
16309@end table
16310
16311@geindex -M (gnatlink)
16312
16313
16314@table @asis
16315
16316@item @code{-M}
16317
16318When linking an executable, create a map file. The name of the map file
16319has the same name as the executable with extension ".map".
16320@end table
16321
16322@geindex -M= (gnatlink)
16323
16324
16325@table @asis
16326
16327@item @code{-M=@emph{mapfile}}
16328
16329When linking an executable, create a map file. The name of the map file is
16330@cite{mapfile}.
16331@end table
16332
16333@geindex --GCC=compiler_name (gnatlink)
16334
16335
16336@table @asis
16337
16338@item @code{--GCC=@emph{compiler_name}}
16339
16340Program used for compiling the binder file. The default is
16341@code{gcc}. You need to use quotes around @cite{compiler_name} if
16342@cite{compiler_name} contains spaces or other separator characters.
16343As an example @code{--GCC="foo -x -y"} will instruct @emph{gnatlink} to
16344use @code{foo -x -y} as your compiler. Note that switch @code{-c} is always
16345inserted after your command name. Thus in the above example the compiler
16346command that will be used by @emph{gnatlink} will be @code{foo -c -x -y}.
16347A limitation of this syntax is that the name and path name of the executable
16348itself must not include any embedded spaces. If the compiler executable is
16349different from the default one (gcc or <prefix>-gcc), then the back-end
16350switches in the ALI file are not used to compile the binder generated source.
16351For example, this is the case with @code{--GCC="foo -x -y"}. But the back end
16352switches will be used for @code{--GCC="gcc -gnatv"}. If several
16353@code{--GCC=compiler_name} are used, only the last @cite{compiler_name}
16354is taken into account. However, all the additional switches are also taken
16355into account. Thus,
16356@code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
16357@code{--GCC="bar -x -y -z -t"}.
16358@end table
16359
16360@geindex --LINK= (gnatlink)
16361
16362
16363@table @asis
16364
16365@item @code{--LINK=@emph{name}}
16366
16367@cite{name} is the name of the linker to be invoked. This is especially
16368useful in mixed language programs since languages such as C++ require
16369their own linker to be used. When this switch is omitted, the default
16370name for the linker is @emph{gcc}. When this switch is used, the
16371specified linker is called instead of @emph{gcc} with exactly the same
16372parameters that would have been passed to @emph{gcc} so if the desired
16373linker requires different parameters it is necessary to use a wrapper
16374script that massages the parameters before invoking the real linker. It
16375may be useful to control the exact invocation by using the verbose
16376switch.
16377@end table
16378
16379@node Using the GNU make Utility,,Linking with gnatlink,Building Executable Programs with GNAT
16380@anchor{gnat_ugn/building_executable_programs_with_gnat id47}@anchor{13e}@anchor{gnat_ugn/building_executable_programs_with_gnat using-the-gnu-make-utility}@anchor{21}
16381@section Using the GNU @cite{make} Utility
16382
16383
16384@geindex make (GNU)
16385@geindex GNU make
16386
16387This chapter offers some examples of makefiles that solve specific
16388problems. It does not explain how to write a makefile, nor does it try to replace the
16389@emph{gnatmake} utility (@ref{1d,,Building with gnatmake}).
16390
16391All the examples in this section are specific to the GNU version of
16392make. Although @emph{make} is a standard utility, and the basic language
16393is the same, these examples use some advanced features found only in
16394@cite{GNU make}.
16395
16396@menu
16397* Using gnatmake in a Makefile:: 
16398* Automatically Creating a List of Directories:: 
16399* Generating the Command Line Switches:: 
16400* Overcoming Command Line Length Limits:: 
16401
16402@end menu
16403
16404@node Using gnatmake in a Makefile,Automatically Creating a List of Directories,,Using the GNU make Utility
16405@anchor{gnat_ugn/building_executable_programs_with_gnat using-gnatmake-in-a-makefile}@anchor{13f}@anchor{gnat_ugn/building_executable_programs_with_gnat id48}@anchor{140}
16406@subsection Using gnatmake in a Makefile
16407
16408
16409@c index makefile (GNU make)
16410
16411Complex project organizations can be handled in a very powerful way by
16412using GNU make combined with gnatmake. For instance, here is a Makefile
16413which allows you to build each subsystem of a big project into a separate
16414shared library. Such a makefile allows you to significantly reduce the link
16415time of very big applications while maintaining full coherence at
16416each step of the build process.
16417
16418The list of dependencies are handled automatically by
16419@emph{gnatmake}. The Makefile is simply used to call gnatmake in each of
16420the appropriate directories.
16421
16422Note that you should also read the example on how to automatically
16423create the list of directories
16424(@ref{141,,Automatically Creating a List of Directories})
16425which might help you in case your project has a lot of subdirectories.
16426
16427@example
16428## This Makefile is intended to be used with the following directory
16429## configuration:
16430##  - The sources are split into a series of csc (computer software components)
16431##    Each of these csc is put in its own directory.
16432##    Their name are referenced by the directory names.
16433##    They will be compiled into shared library (although this would also work
16434##    with static libraries
16435##  - The main program (and possibly other packages that do not belong to any
16436##    csc is put in the top level directory (where the Makefile is).
16437##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
16438##                    \\_ second_csc (sources) __ lib (will contain the library)
16439##                    \\_ ...
16440## Although this Makefile is build for shared library, it is easy to modify
16441## to build partial link objects instead (modify the lines with -shared and
16442## gnatlink below)
16443##
16444## With this makefile, you can change any file in the system or add any new
16445## file, and everything will be recompiled correctly (only the relevant shared
16446## objects will be recompiled, and the main program will be re-linked).
16447
16448# The list of computer software component for your project. This might be
16449# generated automatically.
16450CSC_LIST=aa bb cc
16451
16452# Name of the main program (no extension)
16453MAIN=main
16454
16455# If we need to build objects with -fPIC, uncomment the following line
16456#NEED_FPIC=-fPIC
16457
16458# The following variable should give the directory containing libgnat.so
16459# You can get this directory through 'gnatls -v'. This is usually the last
16460# directory in the Object_Path.
16461GLIB=...
16462
16463# The directories for the libraries
16464# (This macro expands the list of CSC to the list of shared libraries, you
16465# could simply use the expanded form:
16466# LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
16467LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
16468
16469$@{MAIN@}: objects $@{LIB_DIR@}
16470    gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
16471    gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
16472
16473objects::
16474    # recompile the sources
16475    gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
16476
16477# Note: In a future version of GNAT, the following commands will be simplified
16478# by a new tool, gnatmlib
16479$@{LIB_DIR@}:
16480    mkdir -p $@{dir $@@ @}
16481    cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
16482    cd $@{dir $@@ @} && cp -f ../*.ali .
16483
16484# The dependencies for the modules
16485# Note that we have to force the expansion of *.o, since in some cases
16486# make won't be able to do it itself.
16487aa/lib/libaa.so: $@{wildcard aa/*.o@}
16488bb/lib/libbb.so: $@{wildcard bb/*.o@}
16489cc/lib/libcc.so: $@{wildcard cc/*.o@}
16490
16491# Make sure all of the shared libraries are in the path before starting the
16492# program
16493run::
16494    LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
16495
16496clean::
16497    $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
16498    $@{RM@} $@{CSC_LIST:%=%/*.ali@}
16499    $@{RM@} $@{CSC_LIST:%=%/*.o@}
16500    $@{RM@} *.o *.ali $@{MAIN@}
16501@end example
16502
16503@node Automatically Creating a List of Directories,Generating the Command Line Switches,Using gnatmake in a Makefile,Using the GNU make Utility
16504@anchor{gnat_ugn/building_executable_programs_with_gnat automatically-creating-a-list-of-directories}@anchor{141}@anchor{gnat_ugn/building_executable_programs_with_gnat id49}@anchor{142}
16505@subsection Automatically Creating a List of Directories
16506
16507
16508In most makefiles, you will have to specify a list of directories, and
16509store it in a variable. For small projects, it is often easier to
16510specify each of them by hand, since you then have full control over what
16511is the proper order for these directories, which ones should be
16512included.
16513
16514However, in larger projects, which might involve hundreds of
16515subdirectories, it might be more convenient to generate this list
16516automatically.
16517
16518The example below presents two methods. The first one, although less
16519general, gives you more control over the list. It involves wildcard
16520characters, that are automatically expanded by @emph{make}. Its
16521shortcoming is that you need to explicitly specify some of the
16522organization of your project, such as for instance the directory tree
16523depth, whether some directories are found in a separate tree, etc.
16524
16525The second method is the most general one. It requires an external
16526program, called @emph{find}, which is standard on all Unix systems. All
16527the directories found under a given root directory will be added to the
16528list.
16529
16530@example
16531# The examples below are based on the following directory hierarchy:
16532# All the directories can contain any number of files
16533# ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
16534#                       ->  ab
16535#                       ->  ac
16536#                ->  b  ->  ba  ->  baa
16537#                       ->  bb
16538#                       ->  bc
16539# This Makefile creates a variable called DIRS, that can be reused any time
16540# you need this list (see the other examples in this section)
16541
16542# The root of your project's directory hierarchy
16543ROOT_DIRECTORY=.
16544
16545####
16546# First method: specify explicitly the list of directories
16547# This allows you to specify any subset of all the directories you need.
16548####
16549
16550DIRS := a/aa/ a/ab/ b/ba/
16551
16552####
16553# Second method: use wildcards
16554# Note that the argument(s) to wildcard below should end with a '/'.
16555# Since wildcards also return file names, we have to filter them out
16556# to avoid duplicate directory names.
16557# We thus use make's `dir` and `sort` functions.
16558# It sets DIRs to the following value (note that the directories aaa and baa
16559# are not given, unless you change the arguments to wildcard).
16560# DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
16561####
16562
16563DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
16564                    $@{ROOT_DIRECTORY@}/*/*/@}@}@}
16565
16566####
16567# Third method: use an external program
16568# This command is much faster if run on local disks, avoiding NFS slowdowns.
16569# This is the most complete command: it sets DIRs to the following value:
16570# DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
16571####
16572
16573DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
16574@end example
16575
16576@node Generating the Command Line Switches,Overcoming Command Line Length Limits,Automatically Creating a List of Directories,Using the GNU make Utility
16577@anchor{gnat_ugn/building_executable_programs_with_gnat id50}@anchor{143}@anchor{gnat_ugn/building_executable_programs_with_gnat generating-the-command-line-switches}@anchor{144}
16578@subsection Generating the Command Line Switches
16579
16580
16581Once you have created the list of directories as explained in the
16582previous section (@ref{141,,Automatically Creating a List of Directories}),
16583you can easily generate the command line arguments to pass to gnatmake.
16584
16585For the sake of completeness, this example assumes that the source path
16586is not the same as the object path, and that you have two separate lists
16587of directories.
16588
16589@example
16590# see "Automatically creating a list of directories" to create
16591# these variables
16592SOURCE_DIRS=
16593OBJECT_DIRS=
16594
16595GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
16596GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
16597
16598all:
16599        gnatmake $@{GNATMAKE_SWITCHES@} main_unit
16600@end example
16601
16602@node Overcoming Command Line Length Limits,,Generating the Command Line Switches,Using the GNU make Utility
16603@anchor{gnat_ugn/building_executable_programs_with_gnat overcoming-command-line-length-limits}@anchor{145}@anchor{gnat_ugn/building_executable_programs_with_gnat id51}@anchor{146}
16604@subsection Overcoming Command Line Length Limits
16605
16606
16607One problem that might be encountered on big projects is that many
16608operating systems limit the length of the command line. It is thus hard to give
16609gnatmake the list of source and object directories.
16610
16611This example shows how you can set up environment variables, which will
16612make @emph{gnatmake} behave exactly as if the directories had been
16613specified on the command line, but have a much higher length limit (or
16614even none on most systems).
16615
16616It assumes that you have created a list of directories in your Makefile,
16617using one of the methods presented in
16618@ref{141,,Automatically Creating a List of Directories}.
16619For the sake of completeness, we assume that the object
16620path (where the ALI files are found) is different from the sources patch.
16621
16622Note a small trick in the Makefile below: for efficiency reasons, we
16623create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
16624expanded immediately by @cite{make}. This way we overcome the standard
16625make behavior which is to expand the variables only when they are
16626actually used.
16627
16628On Windows, if you are using the standard Windows command shell, you must
16629replace colons with semicolons in the assignments to these variables.
16630
16631@example
16632# In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
16633# This is the same thing as putting the -I arguments on the command line.
16634# (the equivalent of using -aI on the command line would be to define
16635#  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
16636# You can of course have different values for these variables.
16637#
16638# Note also that we need to keep the previous values of these variables, since
16639# they might have been set before running 'make' to specify where the GNAT
16640# library is installed.
16641
16642# see "Automatically creating a list of directories" to create these
16643# variables
16644SOURCE_DIRS=
16645OBJECT_DIRS=
16646
16647empty:=
16648space:=$@{empty@} $@{empty@}
16649SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
16650OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
16651ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
16652ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
16653export ADA_INCLUDE_PATH
16654export ADA_OBJECTS_PATH
16655
16656all:
16657        gnatmake main_unit
16658@end example
16659
16660@c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
16661
16662@node GNAT Project Manager,Tools Supporting Project Files,Building Executable Programs with GNAT,Top
16663@anchor{gnat_ugn/gnat_project_manager doc}@anchor{147}@anchor{gnat_ugn/gnat_project_manager gnat-project-manager}@anchor{b}@anchor{gnat_ugn/gnat_project_manager id1}@anchor{148}
16664@chapter GNAT Project Manager
16665
16666
16667@menu
16668* Introduction:: 
16669* Building With Projects:: 
16670* Organizing Projects into Subsystems:: 
16671* Scenarios in Projects:: 
16672* Library Projects:: 
16673* Project Extension:: 
16674* Aggregate Projects:: 
16675* Aggregate Library Projects:: 
16676* Project File Reference:: 
16677
16678@end menu
16679
16680@node Introduction,Building With Projects,,GNAT Project Manager
16681@anchor{gnat_ugn/gnat_project_manager introduction}@anchor{149}@anchor{gnat_ugn/gnat_project_manager gnat-project-manager-introduction}@anchor{14a}
16682@section Introduction
16683
16684
16685This chapter describes GNAT's @emph{Project Manager}, a facility that allows
16686you to manage complex builds involving a number of source files, directories,
16687and options for different system configurations. In particular,
16688project files allow you to specify:
16689
16690
16691@itemize *
16692
16693@item 
16694The directory or set of directories containing the source files, and/or the
16695names of the specific source files themselves
16696
16697@item 
16698The directory in which the compiler's output
16699(@code{ALI} files, object files, tree files, etc.) is to be placed
16700
16701@item 
16702The directory in which the executable programs are to be placed
16703
16704@item 
16705Switch settings for any of the project-enabled tools;
16706you can apply these settings either globally or to individual compilation units.
16707
16708@item 
16709The source files containing the main subprogram(s) to be built
16710
16711@item 
16712The source programming language(s)
16713
16714@item 
16715Source file naming conventions; you can specify these either globally or for
16716individual compilation units (see @ref{14b,,Naming Schemes}).
16717
16718@item 
16719Change any of the above settings depending on external values, thus enabling
16720the reuse of the projects in various @strong{scenarios} (see @ref{14c,,Scenarios in Projects}).
16721
16722@item 
16723Automatically build libraries as part of the build process
16724(see @ref{8a,,Library Projects}).
16725@end itemize
16726
16727Project files are written in a syntax close to that of Ada, using familiar
16728notions such as packages, context clauses, declarations, default values,
16729assignments, and inheritance (see @ref{14d,,Project File Reference}).
16730
16731Project files can be built hierarchically from other project files, simplifying
16732complex system integration and project reuse (see @ref{14e,,Organizing Projects into Subsystems}).
16733
16734
16735@itemize *
16736
16737@item 
16738One project can import other projects containing needed source files.
16739More generally, the Project Manager lets you structure large development
16740efforts into hierarchical subsystems, where build decisions are delegated
16741to the subsystem level, and thus different compilation environments
16742(switch settings) used for different subsystems.
16743
16744@item 
16745You can organize GNAT projects in a hierarchy: a child project
16746can extend a parent project, inheriting the parent's source files and
16747optionally overriding any of them with alternative versions
16748(see @ref{14f,,Project Extension}).
16749@end itemize
16750
16751Several tools support project files, generally in addition to specifying
16752the information on the command line itself). They share common switches
16753to control the loading of the project (in particular
16754@code{-P@emph{projectfile}} and
16755@code{-X@emph{vbl}=@emph{value}}).
16756
16757The Project Manager supports a wide range of development strategies,
16758for systems of all sizes.  Here are some typical practices that are
16759easily handled:
16760
16761
16762@itemize *
16763
16764@item 
16765Using a common set of source files and generating object files in different
16766directories via different switch settings. It can be used for instance, for
16767generating separate sets of object files for debugging and for production.
16768
16769@item 
16770Using a mostly-shared set of source files with different versions of
16771some units or subunits. It can be used for instance, for grouping and hiding
16772all OS dependencies in a small number of implementation units.
16773@end itemize
16774
16775Project files can be used to achieve some of the effects of a source
16776versioning system (for example, defining separate projects for
16777the different sets of sources that comprise different releases) but the
16778Project Manager is independent of any source configuration management tool
16779that might be used by the developers.
16780
16781The various sections below introduce the different concepts related to
16782projects. Each section starts with examples and use cases, and then goes into
16783the details of related project file capabilities.
16784
16785@node Building With Projects,Organizing Projects into Subsystems,Introduction,GNAT Project Manager
16786@anchor{gnat_ugn/gnat_project_manager building-with-projects}@anchor{150}@anchor{gnat_ugn/gnat_project_manager id2}@anchor{151}
16787@section Building With Projects
16788
16789
16790In its simplest form, a unique project is used to build a single executable.
16791This section concentrates on such a simple setup. Later sections will extend
16792this basic model to more complex setups.
16793
16794The following concepts are the foundation of project files, and will be further
16795detailed later in this documentation. They are summarized here as a reference.
16796
16797
16798@table @asis
16799
16800@item @strong{Project file}:
16801
16802A text file using an Ada-like syntax, generally using the @code{.gpr}
16803extension. It defines build-related characteristics of an application.
16804The characteristics include the list of sources, the location of those
16805sources, the location for the generated object files, the name of
16806the main program, and the options for the various tools involved in the
16807build process.
16808
16809@item @strong{Project attribute}:
16810
16811A specific project characteristic is defined by an attribute clause. Its
16812value is a string or a sequence of strings. All settings in a project
16813are defined through a list of predefined attributes with precise
16814semantics. See @ref{152,,Attributes}.
16815
16816@item @strong{Package in a project}:
16817
16818Global attributes are defined at the top level of a project.
16819Attributes affecting specific tools are grouped in a
16820package whose name is related to tool's function. The most common
16821packages are @cite{Builder}, @cite{Compiler}, @cite{Binder},
16822and @cite{Linker}. See @ref{153,,Packages}.
16823
16824@item @strong{Project variables}:
16825
16826In addition to attributes, a project can use variables to store intermediate
16827values and avoid duplication in complex expressions. It can be initialized
16828with a value coming from the environment.
16829A frequent use of variables is to define scenarios.
16830See @ref{154,,External Values}, @ref{14c,,Scenarios in Projects}, and @ref{155,,Variables}.
16831
16832@item @strong{Source files} and @strong{source directories}:
16833
16834A source file is associated with a language through a naming convention. For
16835instance, @cite{foo.c} is typically the name of a C source file;
16836@cite{bar.ads} or @cite{bar.1.ada} are two common naming conventions for a
16837file containing an Ada spec. A compilation unit is often composed of a main
16838source file and potentially several auxiliary ones, such as header files in C.
16839The naming conventions can be user defined @ref{14b,,Naming Schemes}, and will
16840drive the builder to call the appropriate compiler for the given source file.
16841Source files are searched for in the source directories associated with the
16842project through the @strong{Source_Dirs} attribute. By default, all the files (in
16843these source directories) following the naming conventions associated with the
16844declared languages are considered to be part of the project. It is also
16845possible to limit the list of source files using the @strong{Source_Files} or
16846@strong{Source_List_File} attributes. Note that those last two attributes only
16847accept basenames with no directory information.
16848
16849@item @strong{Object files} and @strong{object directory}:
16850
16851An object file is an intermediate file produced by the compiler from a
16852compilation unit. It is used by post-compilation tools to produce
16853final executables or libraries. Object files produced in the context of
16854a given project are stored in a single directory that can be specified by the
16855@strong{Object_Dir} attribute. In order to store objects in
16856two or more object directories, the system must be split into
16857distinct subsystems with their own project file.
16858@end table
16859
16860The following subsections introduce gradually all the attributes of interest
16861for simple build needs. Here is the simple setup that will be used in the
16862following examples.
16863
16864The Ada source files @code{pack.ads}, @code{pack.adb}, and @code{proc.adb} are in
16865the @code{common/} directory. The file @code{proc.adb} contains an Ada main
16866subprogram @cite{Proc} that @emph{with}s package @cite{Pack}. We want to compile
16867these source files with the switch
16868@emph{-O2}, and put the resulting files in
16869the directory @code{obj/}.
16870
16871@example
16872common/
16873  pack.ads
16874  pack.adb
16875  proc.adb
16876common/obj/
16877  proc.ali, proc.o pack.ali, pack.o
16878@end example
16879
16880Our project is to be called @emph{Build}. The name of the
16881file is the name of the project (case-insensitive) with the
16882@code{.gpr} extension, therefore the project file name is @code{build.gpr}. This
16883is not mandatory, but a warning is issued when this convention is not followed.
16884
16885This is a very simple example, and as stated above, a single project
16886file is enough for it. We will thus create a new file, that for now
16887should contain the following code:
16888
16889@example
16890project Build is
16891end Build;
16892@end example
16893
16894@menu
16895* Source Files and Directories:: 
16896* Duplicate Sources in Projects:: 
16897* Object and Exec Directory:: 
16898* Main Subprograms:: 
16899* Tools Options in Project Files:: 
16900* Compiling with Project Files:: 
16901* Executable File Names:: 
16902* Avoid Duplication With Variables:: 
16903* Naming Schemes:: 
16904* Installation:: 
16905* Distributed support:: 
16906
16907@end menu
16908
16909@node Source Files and Directories,Duplicate Sources in Projects,,Building With Projects
16910@anchor{gnat_ugn/gnat_project_manager id3}@anchor{156}@anchor{gnat_ugn/gnat_project_manager source-files-and-directories}@anchor{157}
16911@subsection Source Files and Directories
16912
16913
16914When you create a new project, the first thing to describe is how to find the
16915corresponding source files. These are the only settings that are needed by all
16916the tools that will use this project (builder, compiler, binder and linker for
16917the compilation, IDEs to edit the source files,...).
16918
16919@geindex Source directories (GNAT Project Manager)
16920
16921The first step is to declare the source directories, which are the directories
16922to be searched to find source files. In the case of the example,
16923the @code{common} directory is the only source directory.
16924
16925@geindex Source_Dirs (GNAT Project Manager)
16926
16927There are several ways of defining source directories:
16928
16929
16930@itemize *
16931
16932@item 
16933When the attribute @strong{Source_Dirs} is not used, a project contains a
16934single source directory which is the one where the project file itself
16935resides. In our example, if @code{build.gpr} is placed in the @code{common}
16936directory, the project has the needed implicit source directory.
16937
16938@item 
16939The attribute @strong{Source_Dirs} can be set to a list of path names, one
16940for each of the source directories. Such paths can either be absolute
16941names (for instance @code{"/usr/local/common/"} on UNIX), or relative to the
16942directory in which the project file resides (for instance "." if
16943@code{build.gpr} is inside @code{common/}, or "common" if it is one level up).
16944Each of the source directories must exist and be readable.
16945
16946@geindex portability of path names (GNAT Project Manager)
16947
16948The syntax for directories is platform specific. For portability, however,
16949the project manager will always properly translate UNIX-like path names to
16950the native format of the specific platform. For instance, when the same
16951project file is to be used both on Unix and Windows, "/" should be used as
16952the directory separator rather than "\".
16953
16954@item 
16955The attribute @strong{Source_Dirs} can automatically include subdirectories
16956using a special syntax inspired by some UNIX shells. If any of the paths in
16957the list ends with "@code{**}", then that path and all its subdirectories
16958(recursively) are included in the list of source directories. For instance,
16959@code{**} and @code{./**} represent the complete directory tree rooted at
16960the directory in which the project file resides.
16961
16962@geindex Source directories (GNAT Project Manager)
16963
16964@geindex Excluded_Source_Dirs (GNAT Project Manager)
16965
16966When using that construct, it can sometimes be convenient to also use the
16967attribute @strong{Excluded_Source_Dirs}, which is also a list of paths. Each entry
16968specifies a directory whose immediate content, not including subdirs, is to
16969be excluded. It is also possible to exclude a complete directory subtree
16970using the "**" notation.
16971
16972@geindex Ignore_Source_Sub_Dirs (GNAT Project Manager)
16973
16974It is often desirable to remove, from the source directories, directory
16975subtrees rooted at some subdirectories. An example is the subdirectories
16976created by a Version Control System such as Subversion that creates directory
16977subtrees rooted at subdirectories ".svn". To do that, attribute
16978@strong{Ignore_Source_Sub_Dirs} can be used. It specifies the list of simple
16979file names for the roots of these undesirable directory subtrees.
16980
16981@c code-block: ada-project
16982@c 
16983@c for Source_Dirs use ("./**");
16984@c for Ignore_Source_Sub_Dirs use (".svn");
16985@end itemize
16986
16987When applied to the simple example, and because we generally prefer to have
16988the project file at the toplevel directory rather than mixed with the sources,
16989we will create the following file
16990
16991@c code-block: ada-project
16992@c 
16993@c build.gpr
16994@c project Build is
16995@c    for Source_Dirs use ("common");  --  <<<<
16996@c end Build;
16997
16998Once source directories have been specified, one may need to indicate
16999source files of interest. By default, all source files present in the source
17000directories are considered by the project manager. When this is not desired,
17001it is possible to specify the list of sources to consider explicitly.
17002In such a case, only source file base names are indicated and not
17003their absolute or relative path names. The project manager is in charge of
17004locating the specified source files in the specified source directories.
17005
17006
17007@itemize *
17008
17009@item 
17010By default, the project manager searches for all source files of all
17011specified languages in all the source directories.
17012
17013Since the project manager was initially developed for Ada environments, the
17014default language is usually Ada and the above project file is complete: it
17015defines without ambiguity the sources composing the project: that is to say,
17016all the sources in subdirectory "common" for the default language (Ada) using
17017the default naming convention.
17018
17019@geindex Languages (GNAT Project Manager)
17020
17021However, when compiling a multi-language application, or a pure C
17022application, the project manager must be told which languages are of
17023interest, which is done by setting the @strong{Languages} attribute to a list of
17024strings, each of which is the name of a language. Tools like
17025@emph{gnatmake} only know about Ada, while other tools like
17026@emph{gprbuild} know about many more languages such as C, C++, Fortran,
17027assembly and others can be added dynamically.
17028
17029@geindex Naming scheme (GNAT Project Manager)
17030
17031Even when using only Ada, the default naming might not be suitable. Indeed,
17032how does the project manager recognizes an "Ada file" from any other
17033file? Project files can describe the naming scheme used for source files,
17034and override the default (see @ref{14b,,Naming Schemes}). The default is the
17035standard GNAT extension (@code{.adb} for bodies and @code{.ads} for
17036specs), which is what is used in our example, explaining why no naming scheme
17037is explicitly specified.
17038See @ref{14b,,Naming Schemes}.
17039
17040@geindex Source_Files (GNAT Project Manager)
17041
17042@item 
17043@cite{Source_Files}.
17044In some cases, source directories might contain files that should not be
17045included in a project. One can specify the explicit list of file names to
17046be considered through the @strong{Source_Files} attribute.
17047When this attribute is defined, instead of looking at every file in the
17048source directories, the project manager takes only those names into
17049consideration  reports  errors if they cannot be found in the source
17050directories or does not correspond to the naming scheme.
17051
17052@item 
17053For various reasons, it is sometimes useful to have a project with no
17054sources (most of the time because the attributes defined in the project
17055file will be reused in other projects, as explained in
17056@ref{14e,,Organizing Projects into Subsystems}. To do this, the attribute
17057@emph{Source_Files} is set to the empty list, i.e. @cite{()}. Alternatively,
17058@emph{Source_Dirs} can be set to the empty list, with the same
17059result.
17060
17061@geindex Source_List_File (GNAT Project Manager)
17062
17063@item 
17064@cite{Source_List_File}.
17065If there is a great number of files, it might be more convenient to use
17066the attribute @strong{Source_List_File}, which specifies the full path of a file.
17067This file must contain a list of source file names (one per line, no
17068directory information) that are searched as if they had been defined
17069through @emph{Source_Files}. Such a file can easily be created through
17070external tools.
17071
17072A warning is issued if both attributes @cite{Source_Files} and
17073@cite{Source_List_File} are given explicit values. In this case, the
17074attribute @cite{Source_Files} prevails.
17075
17076@geindex Excluded_Source_Files (GNAT Project Manager)
17077
17078@geindex Locally_Removed_Files (GNAT Project Manager)
17079
17080@geindex Excluded_Source_List_File (GNAT Project Manager)
17081
17082@item 
17083@cite{Excluded_Source_Files}.
17084Specifying an explicit list of files is not always convenient.It might be
17085more convenient to use the default search rules with specific exceptions.
17086This can be done thanks to the attribute @strong{Excluded_Source_Files}
17087(or its synonym @strong{Locally_Removed_Files}).
17088Its value is the list of file names that should not be taken into account.
17089This attribute is often used when extending a project,
17090see @ref{14f,,Project Extension}. A similar attribute
17091@strong{Excluded_Source_List_File} plays the same
17092role but takes the name of file containing file names similarly to
17093@cite{Source_List_File}.
17094@end itemize
17095
17096In most simple cases, such as the above example, the default source file search
17097behavior provides the expected result, and we do not need to add anything after
17098setting @cite{Source_Dirs}. The project manager automatically finds
17099@code{pack.ads}, @code{pack.adb}, and @code{proc.adb} as source files of the
17100project.
17101
17102Note that by default a warning is issued when a project has no sources attached
17103to it and this is not explicitly indicated in the project file.
17104
17105@node Duplicate Sources in Projects,Object and Exec Directory,Source Files and Directories,Building With Projects
17106@anchor{gnat_ugn/gnat_project_manager duplicate-sources-in-projects}@anchor{158}@anchor{gnat_ugn/gnat_project_manager id4}@anchor{159}
17107@subsection Duplicate Sources in Projects
17108
17109
17110If the order of the source directories is known statically, that is if
17111@cite{"/**"} is not used in the string list @cite{Source_Dirs}, then there may
17112be several files with the same name sitting in different directories of the
17113project. In this case, only the file in the first directory is considered as a
17114source of the project and the others are hidden. If @cite{"/**"} is used in the
17115string list @cite{Source_Dirs}, it is an error to have several files with the
17116same name in the same directory @cite{"/**"} subtree, since there would be an
17117ambiguity as to which one should be used. However, two files with the same name
17118may exist in two single directories or directory subtrees. In this case, the
17119one in the first directory or directory subtree is a source of the project.
17120
17121If there are two sources in different directories of the same @cite{"/**"}
17122subtree, one way to resolve the problem is to exclude the directory of the
17123file that should not be used as a source of the project.
17124
17125@node Object and Exec Directory,Main Subprograms,Duplicate Sources in Projects,Building With Projects
17126@anchor{gnat_ugn/gnat_project_manager object-and-exec-directory}@anchor{15a}@anchor{gnat_ugn/gnat_project_manager id5}@anchor{15b}
17127@subsection Object and Exec Directory
17128
17129
17130The next step when writing a project is to indicate where the compiler should
17131put the object files. In fact, the compiler and other tools might create
17132several different kind of files (for GNAT, there is the object file and the ALI
17133file for instance). One of the important concepts in projects is that most
17134tools may consider source directories as read-only and do not attempt to create
17135new or temporary files there. Instead, all files are created in the object
17136directory. It is of course not true for project-aware IDEs, whose purpose it is
17137to create the source files.
17138
17139@geindex Object_Dir (GNAT Project Manager)
17140
17141The object directory is specified through the @strong{Object_Dir} attribute.
17142Its value is the path to the object directory, either absolute or
17143relative to the directory containing the project file. This
17144directory must already exist and be readable and writable, although
17145some tools have a switch to create the directory if needed (See
17146the switch @cite{-p} for @emph{gnatmake}
17147and @emph{gprbuild}).
17148
17149If the attribute @cite{Object_Dir} is not specified, it defaults to
17150the project directory, that is the directory containing the project file.
17151
17152For our example, we can specify the object dir in this way:
17153
17154@c code-block: ada-project
17155@c 
17156@c project Build is
17157@c    for Source_Dirs use ("common");
17158@c    for Object_Dir use "obj";   --  <<<<
17159@c end Build;
17160
17161As mentioned earlier, there is a single object directory per project. As a
17162result, if you have an existing system where the object files are spread across
17163several directories, you can either move all of them into the same directory if
17164you want to build it with a single project file, or study the section on
17165subsystems (see @ref{14e,,Organizing Projects into Subsystems}) to see how each
17166separate object directory can be associated with one of the subsystems
17167constituting the application.
17168
17169When the @emph{linker} is called, it usually creates an executable. By
17170default, this executable is placed in the object directory of the project. It
17171might be convenient to store it in its own directory.
17172
17173@geindex Exec_Dir (GNAT Project Manager)
17174
17175This can be done through the @cite{Exec_Dir} attribute, which, like
17176@emph{Object_Dir} contains a single absolute or relative path and must point to
17177an existing and writable directory, unless you ask the tool to create it on
17178your behalf. When not specified, It defaults to the object directory and
17179therefore to the project file's directory if neither @emph{Object_Dir} nor
17180@emph{Exec_Dir} was specified.
17181
17182In the case of the example, let's place the executable in the root
17183of the hierarchy, ie the same directory as @code{build.gpr}. Hence
17184the project file is now
17185
17186@c code-block: ada-project
17187@c 
17188@c project Build is
17189@c    for Source_Dirs use ("common");
17190@c    for Object_Dir use "obj";
17191@c    for Exec_Dir use ".";  --   <<<<
17192@c end Build;
17193
17194@node Main Subprograms,Tools Options in Project Files,Object and Exec Directory,Building With Projects
17195@anchor{gnat_ugn/gnat_project_manager id6}@anchor{15c}@anchor{gnat_ugn/gnat_project_manager main-subprograms}@anchor{15d}
17196@subsection Main Subprograms
17197
17198
17199In the previous section, executables were mentioned. The project manager needs
17200to be taught what they are. In a project file, an executable is indicated by
17201pointing to the source file of a main subprogram. In C this is the file that
17202contains the @cite{main} function, and in Ada the file that contains the main
17203unit.
17204
17205There can be any number of such main files within a given project, and thus
17206several executables can be built in the context of a single project file. Of
17207course, one given executable might not (and in fact will not) need all the
17208source files referenced by the project. As opposed to other build environments
17209such as @emph{makefile}, one does not need to specify the list of
17210dependencies of each executable, the project-aware builder knows enough of the
17211semantics of the languages to build and link only the necessary elements.
17212
17213@geindex Main (GNAT Project Manager)
17214
17215The list of main files is specified via the @strong{Main} attribute. It contains
17216a list of file names (no directories). If a project defines this
17217attribute, it is not necessary to identify  main files on the
17218command line when invoking a builder, and editors like
17219@emph{GPS} will be able to create extra menus to spawn or debug the
17220corresponding executables.
17221
17222@c code-block: ada-project
17223@c 
17224@c project Build is
17225@c    for Source_Dirs use ("common");
17226@c    for Object_Dir use "obj";
17227@c    for Exec_Dir use ".";
17228@c    for Main use ("proc.adb");  --   <<<<
17229@c end Build;
17230
17231If this attribute is defined in the project, then spawning the builder
17232with a command such as
17233
17234@example
17235gprbuild -Pbuild
17236@end example
17237
17238automatically builds all the executables corresponding to the files
17239listed in the @emph{Main} attribute. It is possible to specify one
17240or more executables on the command line to build a subset of them.
17241
17242@node Tools Options in Project Files,Compiling with Project Files,Main Subprograms,Building With Projects
17243@anchor{gnat_ugn/gnat_project_manager tools-options-in-project-files}@anchor{15e}@anchor{gnat_ugn/gnat_project_manager id7}@anchor{15f}
17244@subsection Tools Options in Project Files
17245
17246
17247We now have a project file that fully describes our environment, and can be
17248used to build the application with a simple @emph{gprbuild} command as seen
17249in the previous section. In fact, the empty project we showed immediately at
17250the beginning (with no attribute at all) could already fulfill that need if it
17251was put in the @code{common} directory.
17252
17253Of course, we might want more control. This section shows you how to specify
17254the compilation switches that the various tools involved in the building of the
17255executable should use.
17256
17257@geindex command line length (GNAT Project Manager)
17258
17259Since source names and locations are described in the project file, it is not
17260necessary to use switches on the command line for this purpose (switches such
17261as -I for gcc). This removes a major source of command line length overflow.
17262Clearly, the builders will have to communicate this information one way or
17263another to the underlying compilers and tools they call but they usually use
17264response files for this and thus are not subject to command line overflows.
17265
17266Several tools participate to the creation of an executable: the compiler
17267produces object files from the source files; the binder (in the Ada case)
17268creates a "source" file that takes care, among other things, of elaboration
17269issues and global variable initialization; and the linker gathers everything
17270into a single executable that users can execute. All these tools are known to
17271the project manager and will be called with user defined switches from the
17272project files. However, we need to introduce a new project file concept to
17273express the switches to be used for any of the tools involved in the build.
17274
17275@geindex project file packages (GNAT Project Manager)
17276
17277A project file is subdivided into zero or more @strong{packages}, each of which
17278contains the attributes specific to one tool (or one set of tools). Project
17279files use an Ada-like syntax for packages. Package names permitted in project
17280files are restricted to a predefined set (see @ref{153,,Packages}), and the contents
17281of packages are limited to a small set of constructs and attributes
17282(see @ref{152,,Attributes}).
17283
17284Our example project file can be extended with the following empty packages. At
17285this stage, they could all be omitted since they are empty, but they show which
17286packages would be involved in the build process.
17287
17288@c code-block: ada-project
17289@c 
17290@c project Build is
17291@c    for Source_Dirs use ("common");
17292@c    for Object_Dir use "obj";
17293@c    for Exec_Dir use ".";
17294@c    for Main use ("proc.adb");
17295@c 
17296@c    package Builder is  --<<<  for gnatmake and gprbuild
17297@c    end Builder;
17298@c 
17299@c    package Compiler is --<<<  for the compiler
17300@c    end Compiler;
17301@c 
17302@c    package Binder is   --<<<  for the binder
17303@c    end Binder;
17304@c 
17305@c    package Linker is   --<<<  for the linker
17306@c    end Linker;
17307@c end Build;
17308
17309Let's first examine the compiler switches. As stated in the initial description
17310of the example, we want to compile all files with @emph{-O2}. This is a
17311compiler switch, although it is usual, on the command line, to pass it to the
17312builder which then passes it to the compiler. It is recommended to use directly
17313the right package, which will make the setup easier to understand for other
17314people.
17315
17316Several attributes can be used to specify the switches:
17317
17318@geindex Default_Switches (GNAT Project Manager)
17319
17320@strong{Default_Switches}:
17321
17322@quotation
17323
17324This is the first mention in this manual of an @strong{indexed attribute}. When
17325this attribute is defined, one must supply an @emph{index} in the form of a
17326literal string.
17327In the case of @emph{Default_Switches}, the index is the name of the
17328language to which the switches apply (since a different compiler will
17329likely be used for each language, and each compiler has its own set of
17330switches). The value of the attribute is a list of switches.
17331
17332In this example, we want to compile all Ada source files with the switch
17333@emph{-O2}, and the resulting project file is as follows
17334(only the @cite{Compiler} package is shown):
17335
17336@c code-block: ada-project
17337@c 
17338@c package Compiler is
17339@c   for Default_Switches ("Ada") use ("-O2");
17340@c end Compiler;
17341@end quotation
17342
17343@geindex Switches (GNAT Project Manager)
17344
17345@strong{Switches}:
17346
17347@quotation
17348
17349In some cases, we might want to use specific switches
17350for one or more files. For instance, compiling @code{proc.adb} might not be
17351possible at high level of optimization because of a compiler issue.
17352In such a case, the @emph{Switches}
17353attribute (indexed on the file name) can be used and will override the
17354switches defined by @emph{Default_Switches}. Our project file would
17355become:
17356
17357@c code-block: ada-project
17358@c 
17359@c 
17360@c package Compiler is
17361@c    for Default_Switches ("Ada")
17362@c        use ("-O2");
17363@c    for Switches ("proc.adb")
17364@c        use ("-O0");
17365@c end Compiler;
17366
17367@cite{Switches} may take a pattern as an index, such as in:
17368
17369@c code-block: ada-project
17370@c 
17371@c package Compiler is
17372@c   for Default_Switches ("Ada")
17373@c       use ("-O2");
17374@c   for Switches ("pkg*")
17375@c       use ("-O0");
17376@c end Compiler;
17377
17378Sources @code{pkg.adb} and @code{pkg-child.adb} would be compiled with -O0,
17379not -O2.
17380
17381@cite{Switches} can also be given a language name as index instead of a file
17382name in which case it has the same semantics as @emph{Default_Switches}.
17383However, indexes with wild cards are never valid for language name.
17384@end quotation
17385
17386@geindex Local_Configuration_Pragmas (GNAT Project Manager)
17387
17388@strong{Local_Configuration_Pragmas}:
17389
17390@quotation
17391
17392This attribute may specify the path
17393of a file containing configuration pragmas for use by the Ada compiler,
17394such as @cite{pragma Restrictions (No_Tasking)}. These pragmas will be
17395used for all the sources of the project.
17396@end quotation
17397
17398The switches for the other tools are defined in a similar manner through the
17399@strong{Default_Switches} and @strong{Switches} attributes, respectively in the
17400@emph{Builder} package (for @emph{gnatmake} and @emph{gprbuild}),
17401the @emph{Binder} package (binding Ada executables) and the @emph{Linker}
17402package (for linking executables).
17403
17404@node Compiling with Project Files,Executable File Names,Tools Options in Project Files,Building With Projects
17405@anchor{gnat_ugn/gnat_project_manager compiling-with-project-files}@anchor{160}@anchor{gnat_ugn/gnat_project_manager id8}@anchor{161}
17406@subsection Compiling with Project Files
17407
17408
17409Now that our project files are written, let's build our executable.
17410Here is the command we would use from the command line:
17411
17412@example
17413gnatmake -Pbuild
17414@end example
17415
17416This will automatically build the executables specified through the
17417@emph{Main} attribute: for each, it will compile or recompile the
17418sources for which the object file does not exist or is not up-to-date; it
17419will then run the binder; and finally run the linker to create the
17420executable itself.
17421
17422@emph{gnatmake} only knows how to handle Ada files. By using
17423@emph{gprbuild} as a builder, you could automatically manage C files the
17424same way: create the file @code{utils.c} in the @code{common} directory,
17425set the attribute @emph{Languages} to @cite{"(Ada@comma{} C)"}, and run
17426
17427@example
17428gprbuild -Pbuild
17429@end example
17430
17431Gprbuild knows how to recompile the C files and will
17432recompile them only if one of their dependencies has changed. No direct
17433indication on how to build the various elements is given in the
17434project file, which describes the project properties rather than a
17435set of actions to be executed. Here is the invocation of
17436@emph{gprbuild} when building a multi-language program:
17437
17438@example
17439$ gprbuild -Pbuild
17440gcc -c proc.adb
17441gcc -c pack.adb
17442gcc -c utils.c
17443gprbind proc
17444...
17445gcc proc.o -o proc
17446@end example
17447
17448Notice the three steps described earlier:
17449
17450
17451@itemize *
17452
17453@item 
17454The first three gcc commands correspond to the compilation phase.
17455
17456@item 
17457The gprbind command corresponds to the post-compilation phase.
17458
17459@item 
17460The last gcc command corresponds to the final link.
17461@end itemize
17462
17463@geindex -v option (for GPRbuild)
17464
17465The default output of GPRbuild's execution is kept reasonably simple and easy
17466to understand. In particular, some of the less frequently used commands are not
17467shown, and some parameters are abbreviated. So it is not possible to rerun the
17468effect of the @emph{gprbuild} command by cut-and-pasting its output.
17469GPRbuild's option @cite{-v} provides a much more verbose output which includes,
17470among other information, more complete compilation, post-compilation and link
17471commands.
17472
17473@node Executable File Names,Avoid Duplication With Variables,Compiling with Project Files,Building With Projects
17474@anchor{gnat_ugn/gnat_project_manager executable-file-names}@anchor{162}@anchor{gnat_ugn/gnat_project_manager id9}@anchor{163}
17475@subsection Executable File Names
17476
17477
17478@geindex Executable (GNAT Project Manager)
17479
17480By default, the executable name corresponding to a main file is
17481computed from the main source file name. Through the attribute
17482@strong{Builder.Executable}, it is possible to change this default.
17483
17484For instance, instead of building @emph{proc} (or @emph{proc.exe}
17485on Windows), we could configure our project file to build "proc1"
17486(resp proc1.exe) with the following addition:
17487
17488@example
17489project Build is
17490   ...  --  same as before
17491   package Builder is
17492      for Executable ("proc.adb") use "proc1";
17493   end Builder
17494end Build;
17495@end example
17496
17497@geindex Executable_Suffix (GNAT Project Manager)
17498
17499Attribute @strong{Executable_Suffix}, when specified, may change the suffix
17500of the executable files, when no attribute @cite{Executable} applies:
17501its value replaces the platform-specific executable suffix.
17502The default executable suffix is empty on UNIX and ".exe" on Windows.
17503
17504It is also possible to change the name of the produced executable by using the
17505command line switch @emph{-o}. When several mains are defined in the project,
17506it is not possible to use the @emph{-o} switch and the only way to change the
17507names of the executable is provided by Attributes @cite{Executable} and
17508@cite{Executable_Suffix}.
17509
17510@node Avoid Duplication With Variables,Naming Schemes,Executable File Names,Building With Projects
17511@anchor{gnat_ugn/gnat_project_manager id10}@anchor{164}@anchor{gnat_ugn/gnat_project_manager avoid-duplication-with-variables}@anchor{165}
17512@subsection Avoid Duplication With Variables
17513
17514
17515To illustrate some other project capabilities, here is a slightly more complex
17516project using similar sources and a main program in C:
17517
17518@example
17519project C_Main is
17520   for Languages    use ("Ada", "C");
17521   for Source_Dirs  use ("common");
17522   for Object_Dir   use  "obj";
17523   for Main         use ("main.c");
17524   package Compiler is
17525      C_Switches := ("-pedantic");
17526      for Default_Switches ("C")   use C_Switches;
17527      for Default_Switches ("Ada") use ("-gnaty");
17528      for Switches ("main.c") use C_Switches & ("-g");
17529   end Compiler;
17530end C_Main;
17531@end example
17532
17533This project has many similarities with the previous one.
17534As expected, its @cite{Main} attribute now refers to a C source.
17535The attribute @emph{Exec_Dir} is now omitted, thus the resulting
17536executable will be put in the directory @code{obj}.
17537
17538The most noticeable difference is the use of a variable in the
17539@emph{Compiler} package to store settings used in several attributes.
17540This avoids text duplication, and eases maintenance (a single place to
17541modify if we want to add new switches for C files). We will revisit
17542the use of variables in the context of scenarios (see @ref{14c,,Scenarios in Projects}).
17543
17544In this example, we see how the file @code{main.c} can be compiled with
17545the switches used for all the other C files, plus @emph{-g}.
17546In this specific situation the use of a variable could have been
17547replaced by a reference to the @cite{Default_Switches} attribute:
17548
17549@example
17550for Switches ("c_main.c") use Compiler'Default_Switches ("C") & ("-g");
17551@end example
17552
17553Note the tick (@emph{'}) used to refer to attributes defined in a package.
17554
17555Here is the output of the GPRbuild command using this project:
17556
17557@example
17558$ gprbuild -Pc_main
17559gcc -c -pedantic -g main.c
17560gcc -c -gnaty proc.adb
17561gcc -c -gnaty pack.adb
17562gcc -c -pedantic utils.c
17563gprbind main.bexch
17564...
17565gcc main.o -o main
17566@end example
17567
17568The default switches for Ada sources,
17569the default switches for C sources (in the compilation of @code{lib.c}),
17570and the specific switches for @code{main.c} have all been taken into
17571account.
17572
17573@node Naming Schemes,Installation,Avoid Duplication With Variables,Building With Projects
17574@anchor{gnat_ugn/gnat_project_manager id11}@anchor{166}@anchor{gnat_ugn/gnat_project_manager naming-schemes}@anchor{14b}
17575@subsection Naming Schemes
17576
17577
17578Sometimes an Ada software system is ported from one compilation environment to
17579another (say GNAT), and the file are not named using the default GNAT
17580conventions. Instead of changing all the file names, which for a variety of
17581reasons might not be possible, you can define the relevant file naming scheme
17582in the @strong{Naming} package of your project file.
17583
17584The naming scheme has two distinct goals for the project manager: it
17585allows finding of source files when searching in the source
17586directories, and given a source file name it makes it possible to guess
17587the associated language, and thus the compiler to use.
17588
17589Note that the use by the Ada compiler of pragmas Source_File_Name is not
17590supported when using project files. You must use the features described in this
17591paragraph. You can however specify other configuration pragmas.
17592
17593The following attributes can be defined in package @cite{Naming}:
17594
17595@geindex Casing (GNAT Project Manager)
17596
17597@strong{Casing}:
17598
17599@quotation
17600
17601Its value must be one of @cite{"lowercase"} (the default if
17602unspecified), @cite{"uppercase"} or @cite{"mixedcase"}. It describes the
17603casing of file names with regards to the Ada unit name. Given an Ada unit
17604My_Unit, the file name will respectively be @code{my_unit.adb} (lowercase),
17605@code{MY_UNIT.ADB} (uppercase) or @code{My_Unit.adb} (mixedcase).
17606On Windows, file names are case insensitive, so this attribute is
17607irrelevant.
17608@end quotation
17609
17610@geindex Dot_Replacement (GNAT Project Manager)
17611
17612@strong{Dot_Replacement}:
17613
17614@quotation
17615
17616This attribute specifies the string that should replace the "." in unit
17617names. Its default value is @cite{"-"} so that a unit
17618@cite{Parent.Child} is expected to be found in the file
17619@code{parent-child.adb}. The replacement string must satisfy the following
17620requirements to avoid ambiguities in the naming scheme:
17621
17622
17623@itemize *
17624
17625@item 
17626It must not be empty
17627
17628@item 
17629It cannot start or end with an alphanumeric character
17630
17631@item 
17632It cannot be a single underscore
17633
17634@item 
17635It cannot start with an underscore followed by an alphanumeric
17636
17637@item 
17638It cannot contain a dot @cite{'.'} except if the entire string is @cite{"."}
17639@end itemize
17640@end quotation
17641
17642@geindex Spec_Suffix (GNAT Project Manager)
17643
17644@geindex Specification_Suffix (GNAT Project Manager)
17645
17646@strong{Spec_Suffix} and @strong{Specification_Suffix}:
17647
17648@quotation
17649
17650For Ada, these attributes give the suffix used in file names that contain
17651specifications. For other languages, they give the extension for files
17652that contain declaration (header files in C for instance). The attribute
17653is indexed on the language.
17654The two attributes are equivalent, but the latter is obsolescent.
17655
17656If the value of the attribute is the empty string, it indicates to the
17657Project Manager that the only specifications/header files for the language
17658are those specified with attributes @cite{Spec} or
17659@cite{Specification_Exceptions}.
17660
17661If @cite{Spec_Suffix ("Ada")} is not specified, then the default is
17662@cite{".ads"}.
17663
17664A non empty value must satisfy the following requirements:
17665
17666
17667@itemize *
17668
17669@item 
17670It must include at least one dot
17671
17672@item 
17673If @cite{Dot_Replacement} is a single dot, then it cannot include
17674more than one dot.
17675@end itemize
17676@end quotation
17677
17678@geindex Body_Suffix (GNAT Project Manager)
17679
17680@geindex Implementation_Suffix (GNAT Project Manager)
17681
17682@strong{Body_Suffix} and @strong{Implementation_Suffix}:
17683
17684@quotation
17685
17686These attributes give the extension used for file names that contain
17687code (bodies in Ada). They are indexed on the language. The second
17688version is obsolescent and fully replaced by the first attribute.
17689
17690For each language of a project, one of these two attributes need to be
17691specified, either in the project itself or in the configuration project file.
17692
17693If the value of the attribute is the empty string, it indicates to the
17694Project Manager that the only source files for the language
17695are those specified with attributes @cite{Body} or
17696@cite{Implementation_Exceptions}.
17697
17698These attributes must satisfy the same requirements as @cite{Spec_Suffix}.
17699In addition, they must be different from any of the values in
17700@cite{Spec_Suffix}.
17701If @cite{Body_Suffix ("Ada")} is not specified, then the default is
17702@cite{".adb"}.
17703
17704If @cite{Body_Suffix ("Ada")} and @cite{Spec_Suffix ("Ada")} end with the
17705same string, then a file name that ends with the longest of these two
17706suffixes will be a body if the longest suffix is @cite{Body_Suffix ("Ada")}
17707or a spec if the longest suffix is @cite{Spec_Suffix ("Ada")}.
17708
17709If the suffix does not start with a '.', a file with a name exactly equal to
17710the suffix will also be part of the project (for instance if you define the
17711suffix as @cite{Makefile.in}, a file called @code{Makefile.in} will be part
17712of the project. This capability is usually not interesting when building.
17713However, it might become useful when a project is also used to
17714find the list of source files in an editor, like the GNAT Programming System
17715(GPS).
17716@end quotation
17717
17718@geindex Separate_Suffix (GNAT Project Manager)
17719
17720@strong{Separate_Suffix}:
17721
17722@quotation
17723
17724This attribute is specific to Ada. It denotes the suffix used in file names
17725that contain separate bodies. If it is not specified, then it defaults to
17726same value as @cite{Body_Suffix ("Ada")}.
17727
17728The value of this attribute cannot be the empty string.
17729
17730Otherwise, the same rules apply as for the
17731@cite{Body_Suffix} attribute. The only accepted index is "Ada".
17732@end quotation
17733
17734@strong{Spec} or @strong{Specification}:
17735
17736@quotation
17737
17738@geindex Spec (GNAT Project Manager)
17739
17740@geindex Specification (GNAT Project Manager)
17741
17742This attribute @cite{Spec} can be used to define the source file name for a
17743given Ada compilation unit's spec. The index is the literal name of the Ada
17744unit (case insensitive). The value is the literal base name of the file that
17745contains this unit's spec (case sensitive or insensitive depending on the
17746operating system). This attribute allows the definition of exceptions to the
17747general naming scheme, in case some files do not follow the usual
17748convention.
17749
17750When a source file contains several units, the relative position of the unit
17751can be indicated. The first unit in the file is at position 1
17752
17753@example
17754for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
17755for Spec ("top") use "foo.a" at 1;
17756for Spec ("foo") use "foo.a" at 2;
17757@end example
17758@end quotation
17759
17760@geindex Body (GNAT Project Manager)
17761
17762@geindex Implementation (GNAT Project Manager)
17763
17764@strong{Body} or @strong{Implementation}:
17765
17766@quotation
17767
17768These attribute play the same role as @emph{Spec} for Ada bodies.
17769@end quotation
17770
17771@geindex Specification_Exceptions (GNAT Project Manager)
17772
17773@geindex Implementation_Exceptions (GNAT Project Manager)
17774
17775@strong{Specification_Exceptions} and @strong{Implementation_Exceptions}:
17776
17777@quotation
17778
17779These attributes define exceptions to the naming scheme for languages
17780other than Ada. They are indexed on the language name, and contain
17781a list of file names respectively for headers and source code.
17782@end quotation
17783
17784For example, the following package models the Apex file naming rules:
17785
17786@example
17787package Naming is
17788  for Casing               use "lowercase";
17789  for Dot_Replacement      use ".";
17790  for Spec_Suffix ("Ada")  use ".1.ada";
17791  for Body_Suffix ("Ada")  use ".2.ada";
17792end Naming;
17793@end example
17794
17795@node Installation,Distributed support,Naming Schemes,Building With Projects
17796@anchor{gnat_ugn/gnat_project_manager id12}@anchor{167}@anchor{gnat_ugn/gnat_project_manager installation}@anchor{168}
17797@subsection Installation
17798
17799
17800After building an application or a library it is often required to
17801install it into the development environment. For instance this step is
17802required if the library is to be used by another application.
17803The @emph{gprinstall} tool provides an easy way to install
17804libraries, executable or object code generated during the build. The
17805@strong{Install} package can be used to change the default locations.
17806
17807The following attributes can be defined in package @cite{Install}:
17808
17809@geindex Active (GNAT Project Manager)
17810
17811
17812@table @asis
17813
17814@item @strong{Active}
17815
17816Whether the project is to be installed, values are @cite{true}
17817(default) or @cite{false}.
17818@end table
17819
17820@geindex Artifacts (GNAT Project Manager)
17821
17822@strong{Artifacts}
17823
17824@quotation
17825
17826An array attribute to declare a set of files not part of the sources
17827to be installed. The array discriminant is the directory where the
17828file is to be installed. If a relative directory then Prefix (see
17829below) is prepended.
17830@end quotation
17831
17832@geindex Prefix (GNAT Project Manager)
17833
17834@strong{Prefix}:
17835
17836@quotation
17837
17838Root directory for the installation.
17839@end quotation
17840
17841@strong{Exec_Subdir}
17842
17843@quotation
17844
17845Subdirectory of @strong{Prefix} where executables are to be
17846installed. Default is @strong{bin}.
17847@end quotation
17848
17849@strong{Lib_Subdir}
17850
17851@quotation
17852
17853Subdirectory of @strong{Prefix} where directory with the library or object
17854files is to be installed. Default is @strong{lib}.
17855@end quotation
17856
17857@strong{Sources_Subdir}
17858
17859@quotation
17860
17861Subdirectory of @strong{Prefix} where directory with sources is to be
17862installed. Default is @strong{include}.
17863@end quotation
17864
17865@strong{Project_Subdir}
17866
17867@quotation
17868
17869Subdirectory of @strong{Prefix} where the generated project file is to be
17870installed. Default is @strong{share/gpr}.
17871@end quotation
17872
17873@strong{Mode}
17874
17875@quotation
17876
17877The installation mode, it is either @strong{dev} (default) or @strong{usage}.
17878See @strong{gprbuild} user's guide for details.
17879@end quotation
17880
17881@strong{Install_Name}
17882
17883@quotation
17884
17885Specify the name to use for recording the installation. The default is
17886the project name without the extension.
17887@end quotation
17888
17889@node Distributed support,,Installation,Building With Projects
17890@anchor{gnat_ugn/gnat_project_manager id13}@anchor{169}@anchor{gnat_ugn/gnat_project_manager distributed-support}@anchor{16a}
17891@subsection Distributed support
17892
17893
17894For large projects the compilation time can become a limitation in
17895the development cycle. To cope with that, GPRbuild supports
17896distributed compilation.
17897
17898The following attributes can be defined in package @cite{Remote}:
17899
17900@geindex Root_Dir (GNAT Project Manager)
17901
17902@strong{Root_Dir}:
17903
17904@quotation
17905
17906Root directory of the project's sources. The default value is the
17907project's directory.
17908@end quotation
17909
17910@node Organizing Projects into Subsystems,Scenarios in Projects,Building With Projects,GNAT Project Manager
17911@anchor{gnat_ugn/gnat_project_manager organizing-projects-into-subsystems}@anchor{14e}@anchor{gnat_ugn/gnat_project_manager id14}@anchor{16b}
17912@section Organizing Projects into Subsystems
17913
17914
17915A @strong{subsystem} is a coherent part of the complete system to be built. It is
17916represented by a set of sources and one single object directory. A system can
17917be composed of a single subsystem when it is simple as we have seen in the
17918first section. Complex systems are usually composed of several interdependent
17919subsystems. A subsystem is dependent on another subsystem if knowledge of the
17920other one is required to build it, and in particular if visibility on some of
17921the sources of this other subsystem is required. Each subsystem is usually
17922represented by its own project file.
17923
17924In this section, the previous example is being extended. Let's assume some
17925sources of our @cite{Build} project depend on other sources.
17926For instance, when building a graphical interface, it is usual to depend upon
17927a graphical library toolkit such as GtkAda. Furthermore, we also need
17928sources from a logging module we had previously written.
17929
17930@menu
17931* Project Dependencies:: 
17932* Cyclic Project Dependencies:: 
17933* Sharing Between Projects:: 
17934* Global Attributes:: 
17935
17936@end menu
17937
17938@node Project Dependencies,Cyclic Project Dependencies,,Organizing Projects into Subsystems
17939@anchor{gnat_ugn/gnat_project_manager project-dependencies}@anchor{16c}@anchor{gnat_ugn/gnat_project_manager id15}@anchor{16d}
17940@subsection Project Dependencies
17941
17942
17943GtkAda comes with its own project file (appropriately called
17944@code{gtkada.gpr}), and we will assume we have already built a project
17945called @code{logging.gpr} for the logging module. With the information provided
17946so far in @code{build.gpr}, building the application would fail with an error
17947indicating that the gtkada and logging units that are relied upon by the sources
17948of this project cannot be found.
17949
17950This is solved by adding the following @strong{with} clauses at the beginning of our
17951project:
17952
17953@example
17954with "gtkada.gpr";
17955with "a/b/logging.gpr";
17956project Build is
17957  ...  --  as before
17958end Build;
17959@end example
17960
17961@geindex Externally_Built (GNAT Project Manager)
17962
17963When such a project is compiled, @emph{gprbuild} will automatically check
17964the other projects and recompile their sources when needed. It will also
17965recompile the sources from @cite{Build} when needed, and finally create the
17966executable. In some cases, the implementation units needed to recompile a
17967project are not available, or come from some third party and you do not want to
17968recompile it yourself. In this case, set the attribute @strong{Externally_Built} to
17969"true", indicating to the builder that this project can be assumed to be
17970up-to-date, and should not be considered for recompilation. In Ada, if the
17971sources of this externally built project were compiled with another version of
17972the compiler or with incompatible options, the binder will issue an error.
17973
17974The project's @emph{with} clause has several effects. It provides source
17975visibility between projects during the compilation process. It also guarantees
17976that the necessary object files from @cite{Logging} and @cite{GtkAda} are
17977available when linking @cite{Build}.
17978
17979As can be seen in this example, the syntax for importing projects is similar
17980to the syntax for importing compilation units in Ada. However, project files
17981use literal strings instead of names, and the @emph{with} clause identifies
17982project files rather than packages.
17983
17984Each literal string after @emph{with} is the path
17985(absolute or relative) to a project file. The @cite{.gpr} extension is
17986optional, although we recommend adding it. If no extension is specified,
17987and no project file with the @code{.gpr} extension is found, then
17988the file is searched for exactly as written in the @emph{with} clause,
17989that is with no extension.
17990
17991As mentioned above, the path after a @emph{with} has to be a literal
17992string, and you cannot use concatenation, or lookup the value of external
17993variables to change the directories from which a project is loaded.
17994A solution if you need something like this is to use aggregate projects
17995(see @ref{16e,,Aggregate Projects}).
17996
17997@geindex project path (GNAT Project Manager)
17998
17999When a relative path or a base name is used, the
18000project files are searched relative to each of the directories in the
18001@strong{project path}. This path includes all the directories found with the
18002following algorithm, in this order; the first matching file is used:
18003
18004
18005@itemize *
18006
18007@item 
18008First, the file is searched relative to the directory that contains the
18009current project file.
18010
18011@geindex GPR_PROJECT_PATH_FILE (GNAT Project Manager)
18012
18013@geindex GPR_PROJECT_PATH (GNAT Project Manager)
18014
18015@geindex ADA_PROJECT_PATH (GNAT Project Manager)
18016
18017@item 
18018Then it is searched relative to all the directories specified in the
18019environment variables @strong{GPR_PROJECT_PATH_FILE},
18020@strong{GPR_PROJECT_PATH} and @strong{ADA_PROJECT_PATH} (in that order) if they exist.
18021The value of @strong{GPR_PROJECT_PATH_FILE}, when defined, is the path name of
18022a text file that contains project directory path names, one per line.
18023@strong{GPR_PROJECT_PATH} and @strong{ADA_PROJECT_PATH}, when defined, contain
18024project directory path names separated by directory separators.
18025@strong{ADA_PROJECT_PATH} is used for compatibility, it is recommended to
18026use @strong{GPR_PROJECT_PATH_FILE} or @strong{GPR_PROJECT_PATH}.
18027
18028@item 
18029Finally, it is searched relative to the default project directories.
18030Such directories depend on the tool used. The locations searched in the
18031specified order are:
18032
18033
18034@itemize *
18035
18036@item 
18037@code{<prefix>/<target>/lib/gnat}
18038(for @emph{gnatmake} in all cases, and for @emph{gprbuild} if option
18039@emph{--target} is specified)
18040
18041@item 
18042@code{<prefix>/<target>/share/gpr}
18043(for @emph{gnatmake} in all cases, and for @emph{gprbuild} if option
18044@emph{--target} is specified)
18045
18046@item 
18047@code{<prefix>/share/gpr/}
18048(for @emph{gnatmake} and @emph{gprbuild})
18049
18050@item 
18051@code{<prefix>/lib/gnat/}
18052(for @emph{gnatmake} and @emph{gprbuild})
18053@end itemize
18054
18055In our example, @code{gtkada.gpr} is found in the predefined directory if
18056it was installed at the same root as GNAT.
18057@end itemize
18058
18059Some tools also support extending the project path from the command line,
18060generally through the @emph{-aP}. You can see the value of the project
18061path by using the @emph{gnatls -v} command.
18062
18063Any symbolic link will be fully resolved in the directory of the
18064importing project file before the imported project file is examined.
18065
18066Any source file in the imported project can be used by the sources of the
18067importing project, transitively.
18068Thus if @cite{A} imports @cite{B}, which imports @cite{C}, the sources of
18069@cite{A} may depend on the sources of @cite{C}, even if @cite{A} does not
18070import @cite{C} explicitly. However, this is not recommended, because if
18071and when @cite{B} ceases to import @cite{C}, some sources in @cite{A} will
18072no longer compile. @emph{gprbuild} has a switch @emph{--no-indirect-imports}
18073that will report such indirect dependencies.
18074
18075@cartouche
18076@quotation Note 
18077One very important aspect of a project hierarchy is that
18078@strong{a given source can only belong to one project} (otherwise the project manager
18079would not know which settings apply to it and when to recompile it). It means
18080that different project files do not usually share source directories or
18081when they do, they need to specify precisely which project owns which sources
18082using attribute @cite{Source_Files} or equivalent. By contrast, 2 projects
18083can each own a source with the same base file name as long as they live in
18084different directories. The latter is not true for Ada Sources because of the
18085correlation between source files and Ada units.
18086@end quotation
18087@end cartouche
18088
18089@node Cyclic Project Dependencies,Sharing Between Projects,Project Dependencies,Organizing Projects into Subsystems
18090@anchor{gnat_ugn/gnat_project_manager id16}@anchor{16f}@anchor{gnat_ugn/gnat_project_manager cyclic-project-dependencies}@anchor{170}
18091@subsection Cyclic Project Dependencies
18092
18093
18094Cyclic dependencies are mostly forbidden:
18095if @cite{A} imports @cite{B} (directly or indirectly) then @cite{B}
18096is not allowed to import @cite{A}. However, there are cases when cyclic
18097dependencies would be beneficial. For these cases, another form of import
18098between projects exists: the @strong{limited with}.  A project @cite{A} that
18099imports a project @cite{B} with a straight @emph{with} may also be imported,
18100directly or indirectly, by @cite{B} through a @cite{limited with}.
18101
18102The difference between straight @emph{with} and @cite{limited with} is that
18103the name of a project imported with a @cite{limited with} cannot be used in the
18104project importing it. In particular, its packages cannot be renamed and
18105its variables cannot be referred to.
18106
18107@example
18108with "b.gpr";
18109with "c.gpr";
18110project A is
18111    for Exec_Dir use B'Exec_Dir; -- ok
18112end A;
18113
18114limited with "a.gpr";   --  Cyclic dependency: A -> B -> A
18115project B is
18116   for Exec_Dir use A'Exec_Dir; -- not ok
18117end B;
18118
18119with "d.gpr";
18120project C is
18121end C;
18122
18123limited with "a.gpr";  --  Cyclic dependency: A -> C -> D -> A
18124project D is
18125   for Exec_Dir use A'Exec_Dir; -- not ok
18126end D;
18127@end example
18128
18129@node Sharing Between Projects,Global Attributes,Cyclic Project Dependencies,Organizing Projects into Subsystems
18130@anchor{gnat_ugn/gnat_project_manager sharing-between-projects}@anchor{171}@anchor{gnat_ugn/gnat_project_manager id17}@anchor{172}
18131@subsection Sharing Between Projects
18132
18133
18134When building an application, it is common to have similar needs in several of
18135the projects corresponding to the subsystems under construction. For instance,
18136they will all have the same compilation switches.
18137
18138As seen before (see @ref{15e,,Tools Options in Project Files}), setting compilation
18139switches for all sources of a subsystem is simple: it is just a matter of
18140adding a @cite{Compiler.Default_Switches} attribute to each project files with
18141the same value. Of course, that means duplication of data, and both places need
18142to be changed in order to recompile the whole application with different
18143switches. It can become a real problem if there are many subsystems and thus
18144many project files to edit.
18145
18146There are two main approaches to avoiding this duplication:
18147
18148
18149@itemize *
18150
18151@item 
18152Since @code{build.gpr} imports @code{logging.gpr}, we could change it
18153to reference the attribute in Logging, either through a package renaming,
18154or by referencing the attribute. The following example shows both cases:
18155
18156@example
18157project Logging is
18158   package Compiler is
18159      for Switches ("Ada")
18160          use ("-O2");
18161   end Compiler;
18162   package Binder is
18163      for Switches ("Ada")
18164          use ("-E");
18165   end Binder;
18166end Logging;
18167
18168with "logging.gpr";
18169project Build is
18170   package Compiler renames Logging.Compiler;
18171   package Binder is
18172      for Switches ("Ada") use Logging.Binder'Switches ("Ada");
18173   end Binder;
18174end Build;
18175@end example
18176
18177The solution used for @cite{Compiler} gets the same value for all
18178attributes of the package, but you cannot modify anything from the
18179package (adding extra switches or some exceptions). The second
18180version is more flexible, but more verbose.
18181
18182If you need to refer to the value of a variable in an imported
18183project, rather than an attribute, the syntax is similar but uses
18184a "." rather than an apostrophe. For instance:
18185
18186@example
18187with "imported";
18188project Main is
18189   Var1 := Imported.Var;
18190end Main;
18191@end example
18192
18193@item 
18194The second approach is to define the switches in a third project.
18195That project is set up without any sources (so that, as opposed to
18196the first example, none of the project plays a special role), and
18197will only be used to define the attributes. Such a project is
18198typically called @code{shared.gpr}.
18199
18200@example
18201abstract project Shared is
18202   for Source_Files use ();   --  no sources
18203   package Compiler is
18204      for Switches ("Ada")
18205          use ("-O2");
18206   end Compiler;
18207end Shared;
18208
18209with "shared.gpr";
18210project Logging is
18211   package Compiler renames Shared.Compiler;
18212end Logging;
18213
18214with "shared.gpr";
18215project Build is
18216   package Compiler renames Shared.Compiler;
18217end Build;
18218@end example
18219
18220As for the first example, we could have chosen to set the attributes
18221one by one rather than to rename a package. The reason we explicitly
18222indicate that @cite{Shared} has no sources is so that it can be created
18223in any directory and we are sure it shares no sources with @cite{Build}
18224or @cite{Logging}, which of course would be invalid.
18225
18226@geindex project qualifier (GNAT Project Manager)
18227
18228Note the additional use of the @strong{abstract} qualifier in @code{shared.gpr}.
18229This qualifier is optional, but helps convey the message that we do not
18230intend this project to have sources (see @ref{173,,Qualified Projects} for
18231more qualifiers).
18232@end itemize
18233
18234@node Global Attributes,,Sharing Between Projects,Organizing Projects into Subsystems
18235@anchor{gnat_ugn/gnat_project_manager global-attributes}@anchor{174}@anchor{gnat_ugn/gnat_project_manager id18}@anchor{175}
18236@subsection Global Attributes
18237
18238
18239We have already seen many examples of attributes used to specify a special
18240option of one of the tools involved in the build process. Most of those
18241attributes are project specific. That it to say, they only affect the invocation
18242of tools on the sources of the project where they are defined.
18243
18244There are a few additional attributes that apply to all projects in a
18245hierarchy as long as they are defined on the "main" project.
18246The main project is the project explicitly mentioned on the command-line.
18247The project hierarchy is the "with"-closure of the main project.
18248
18249Here is a list of commonly used global attributes:
18250
18251@geindex Global_Configuration_Pragmas (GNAT Project Manager)
18252
18253@strong{Builder.Global_Configuration_Pragmas}:
18254
18255@quotation
18256
18257This attribute points to a file that contains configuration pragmas
18258to use when building executables. These pragmas apply for all
18259executables built from this project hierarchy. As we have seen before,
18260additional pragmas can be specified on a per-project basis by setting the
18261@cite{Compiler.Local_Configuration_Pragmas} attribute.
18262@end quotation
18263
18264@geindex Global_Compilation_Switches (GNAT Project Manager)
18265
18266@strong{Builder.Global_Compilation_Switches}:
18267
18268@quotation
18269
18270This attribute is a list of compiler switches to use when compiling any
18271source file in the project hierarchy. These switches are used in addition
18272to the ones defined in the @cite{Compiler} package, which only apply to
18273the sources of the corresponding project. This attribute is indexed on
18274the name of the language.
18275@end quotation
18276
18277Using such global capabilities is convenient. It can also lead to unexpected
18278behavior. Especially when several subsystems are shared among different main
18279projects and the different global attributes are not
18280compatible. Note that using aggregate projects can be a safer and more powerful
18281replacement to global attributes.
18282
18283@node Scenarios in Projects,Library Projects,Organizing Projects into Subsystems,GNAT Project Manager
18284@anchor{gnat_ugn/gnat_project_manager id19}@anchor{176}@anchor{gnat_ugn/gnat_project_manager scenarios-in-projects}@anchor{14c}
18285@section Scenarios in Projects
18286
18287
18288Various aspects of the projects can be modified based on @strong{scenarios}. These
18289are user-defined modes that change the behavior of a project. Typical
18290examples are the setup of platform-specific compiler options, or the use of
18291a debug and a release mode (the former would activate the generation of debug
18292information, while the second will focus on improving code optimization).
18293
18294Let's enhance our example to support debug and release modes. The issue is to
18295let the user choose what kind of system he is building: use @emph{-g} as
18296compiler switches in debug mode and @emph{-O2} in release mode. We will also
18297set up the projects so that we do not share the same object directory in both
18298modes; otherwise switching from one to the other might trigger more
18299recompilations than needed or mix objects from the two modes.
18300
18301One naive approach is to create two different project files, say
18302@code{build_debug.gpr} and @code{build_release.gpr}, that set the appropriate
18303attributes as explained in previous sections. This solution does not scale
18304well, because in the presence of multiple projects depending on each other, you
18305will also have to duplicate the complete hierarchy and adapt the project files
18306to point to the right copies.
18307
18308@geindex scenarios (GNAT Project Manager)
18309
18310Instead, project files support the notion of scenarios controlled
18311by external values. Such values can come from several sources (in decreasing
18312order of priority):
18313
18314@geindex -X (usage with GNAT Project Manager)
18315
18316
18317@table @asis
18318
18319@item @strong{Command line}:
18320
18321When launching @emph{gnatmake} or @emph{gprbuild}, the user can pass
18322extra @emph{-X} switches to define the external value. In
18323our case, the command line might look like
18324
18325@example
18326gnatmake -Pbuild.gpr -Xmode=debug
18327@end example
18328
18329or
18330
18331@example
18332gnatmake -Pbuild.gpr -Xmode=release
18333@end example
18334
18335@item @strong{Environment variables}:
18336
18337When the external value does not come from the command line, it can come from
18338the value of environment variables of the appropriate name.
18339In our case, if an environment variable called "mode"
18340exists, its value will be taken into account.
18341@end table
18342
18343@geindex external (GNAT Project Manager)
18344
18345@strong{External function second parameter}.
18346
18347We now need to get that value in the project. The general form is to use
18348the predefined function @strong{external} which returns the current value of
18349the external. For instance, we could set up the object directory to point to
18350either @code{obj/debug} or @code{obj/release} by changing our project to
18351
18352@example
18353project Build is
18354    for Object_Dir use "obj/" & external ("mode", "debug");
18355    ... --  as before
18356end Build;
18357@end example
18358
18359The second parameter to @cite{external} is optional, and is the default
18360value to use if "mode" is not set from the command line or the environment.
18361
18362In order to set the switches according to the different scenarios, other
18363constructs have to be introduced such as typed variables and case constructions.
18364
18365@geindex typed variable (GNAT Project Manager)
18366
18367@geindex case construction (GNAT Project Manager)
18368
18369A @strong{typed variable} is a variable that
18370can take only a limited number of values, similar to an enumeration in Ada.
18371Such a variable can then be used in a @strong{case construction} and create conditional
18372sections in the project. The following example shows how this can be done:
18373
18374@example
18375project Build is
18376   type Mode_Type is ("debug", "release");  --  all possible values
18377   Mode : Mode_Type := external ("mode", "debug"); -- a typed variable
18378
18379   package Compiler is
18380      case Mode is
18381         when "debug" =>
18382            for Switches ("Ada")
18383                use ("-g");
18384         when "release" =>
18385            for Switches ("Ada")
18386                use ("-O2");
18387      end case;
18388   end Compiler;
18389end Build;
18390@end example
18391
18392The project has suddenly grown in size, but has become much more flexible.
18393@cite{Mode_Type} defines the only valid values for the @cite{mode} variable. If
18394any other value is read from the environment, an error is reported and the
18395project is considered as invalid.
18396
18397The @cite{Mode} variable is initialized with an external value
18398defaulting to @cite{"debug"}. This default could be omitted and that would
18399force the user to define the value. Finally, we can use a case construction to set the
18400switches depending on the scenario the user has chosen.
18401
18402Most aspects of the projects can depend on scenarios. The notable exception
18403are project dependencies (@emph{with} clauses), which cannot depend on a scenario.
18404
18405Scenarios work the same way with @strong{project hierarchies}: you can either
18406duplicate a variable similar to @cite{Mode} in each of the project (as long
18407as the first argument to @cite{external} is always the same and the type is
18408the same), or simply set the variable in the @code{shared.gpr} project
18409(see @ref{171,,Sharing Between Projects}).
18410
18411@node Library Projects,Project Extension,Scenarios in Projects,GNAT Project Manager
18412@anchor{gnat_ugn/gnat_project_manager library-projects}@anchor{8a}@anchor{gnat_ugn/gnat_project_manager id20}@anchor{177}
18413@section Library Projects
18414
18415
18416So far, we have seen examples of projects that create executables. However,
18417it is also possible to create libraries instead. A @strong{library} is a specific
18418type of subsystem where, for convenience, objects are grouped together
18419using system-specific means such as archives or windows DLLs.
18420
18421Library projects provide a system- and language-independent way of building
18422both @strong{static} and @strong{dynamic} libraries. They also support the concept of
18423@strong{standalone libraries} (SAL) which offer two significant properties: the
18424elaboration (e.g. initialization) of the library is either automatic or
18425very simple; a change in the
18426implementation part of the library implies minimal post-compilation actions on
18427the complete system and potentially no action at all for the rest of the
18428system in the case of dynamic SALs.
18429
18430There is a restriction on shared library projects: by default, they are only
18431allowed to import other shared library projects. They are not allowed to
18432import non library projects or static library projects.
18433
18434The GNAT Project Manager takes complete care of the library build, rebuild and
18435installation tasks, including recompilation of the source files for which
18436objects do not exist or are not up to date, assembly of the library archive, and
18437installation of the library (i.e., copying associated source, object and
18438@code{ALI} files to the specified location).
18439
18440@menu
18441* Building Libraries:: 
18442* Using Library Projects:: 
18443* Stand-alone Library Projects:: 
18444* Installing a library with project files:: 
18445
18446@end menu
18447
18448@node Building Libraries,Using Library Projects,,Library Projects
18449@anchor{gnat_ugn/gnat_project_manager id21}@anchor{178}@anchor{gnat_ugn/gnat_project_manager building-libraries}@anchor{179}
18450@subsection Building Libraries
18451
18452
18453Let's enhance our example and transform the @cite{logging} subsystem into a
18454library.  In order to do so, a few changes need to be made to
18455@code{logging.gpr}.  Some attributes need to be defined: at least
18456@cite{Library_Name} and @cite{Library_Dir}; in addition, some other attributes
18457can be used to specify specific aspects of the library. For readability, it is
18458also recommended (although not mandatory), to use the qualifier @cite{library}
18459in front of the @cite{project} keyword.
18460
18461@geindex Library_Name (GNAT Project Manager)
18462
18463@strong{Library_Name}:
18464
18465@quotation
18466
18467This attribute is the name of the library to be built. There is no
18468restriction on the name of a library imposed by the project manager, except
18469for stand-alone libraries whose names must follow the syntax of Ada
18470identifiers; however, there may be system-specific restrictions on the name.
18471In general, it is recommended to stick to alphanumeric characters (and
18472possibly single underscores) to help portability.
18473@end quotation
18474
18475@geindex Library_Dir (GNAT Project Manager)
18476
18477@strong{Library_Dir}:
18478
18479@quotation
18480
18481This attribute  is the path (absolute or relative) of the directory where
18482the library is to be installed. In the process of building a library,
18483the sources are compiled, the object files end up  in the explicit or
18484implicit @cite{Object_Dir} directory. When all sources of a library
18485are compiled, some of the compilation artifacts, including the library itself,
18486are copied to the library_dir directory. This directory must exist and be
18487writable. It must also be different from the object directory so that cleanup
18488activities in the Library_Dir do not affect recompilation needs.
18489@end quotation
18490
18491Here is the new version of @code{logging.gpr} that makes it a library:
18492
18493@example
18494library project Logging is          --  "library" is optional
18495   for Library_Name use "logging";  --  will create "liblogging.a" on Unix
18496   for Object_Dir   use "obj";
18497   for Library_Dir  use "lib";      --  different from object_dir
18498end Logging;
18499@end example
18500
18501Once the above two attributes are defined, the library project is valid and
18502is enough for building a library with default characteristics.
18503Other library-related attributes can be used to change the defaults:
18504
18505@geindex Library_Kind (GNAT Project Manager)
18506
18507@strong{Library_Kind}:
18508
18509@quotation
18510
18511The value of this attribute must be either @cite{"static"}, @cite{"dynamic"} or
18512@cite{"relocatable"} (the latter is a synonym for dynamic). It indicates
18513which kind of library should be built (the default is to build a
18514static library, that is an archive of object files that can potentially
18515be linked into a static executable). When the library is set to be dynamic,
18516a separate image is created that will be loaded independently, usually
18517at the start of the main program execution. Support for dynamic libraries is
18518very platform specific, for instance on Windows it takes the form of a DLL
18519while on GNU/Linux, it is a dynamic elf image whose suffix is usually
18520@code{.so}. Library project files, on the other hand, can be written in
18521a platform independent way so that the same project file can be used to build
18522a library on different operating systems.
18523
18524If you need to build both a static and a dynamic library, it is recommended
18525to use two different object directories, since in some cases some extra code
18526needs to be generated for the latter. For such cases, one can either define
18527two different project files, or a single one that uses scenarios to indicate
18528the various kinds of library to be built and their corresponding object_dir.
18529@end quotation
18530
18531@geindex Library_ALI_Dir (GNAT Project Manager)
18532
18533@strong{Library_ALI_Dir}:
18534
18535@quotation
18536
18537This attribute may be specified to indicate the directory where the ALI
18538files of the library are installed. By default, they are copied into the
18539@cite{Library_Dir} directory, but as for the executables where we have a
18540separate @cite{Exec_Dir} attribute, you might want to put them in a separate
18541directory since there can be hundreds of them. The same restrictions as for
18542the @cite{Library_Dir} attribute apply.
18543@end quotation
18544
18545@geindex Library_Version (GNAT Project Manager)
18546
18547@strong{Library_Version}:
18548
18549@quotation
18550
18551This attribute is platform dependent, and has no effect on Windows.
18552On Unix, it is used only for dynamic libraries as the internal
18553name of the library (the @cite{"soname"}). If the library file name (built
18554from the @cite{Library_Name}) is different from the @cite{Library_Version},
18555then the library file will be a symbolic link to the actual file whose name
18556will be @cite{Library_Version}. This follows the usual installation schemes
18557for dynamic libraries on many Unix systems.
18558
18559@example
18560project Logging is
18561   Version := "1";
18562   for Library_Dir use "lib";
18563   for Library_Name use "logging";
18564   for Library_Kind use "dynamic";
18565   for Library_Version use "liblogging.so." & Version;
18566end Logging;
18567@end example
18568
18569After the compilation, the directory @code{lib} will contain both a
18570@code{libdummy.so.1} library and a symbolic link to it called
18571@code{libdummy.so}.
18572@end quotation
18573
18574@geindex Library_GCC (GNAT Project Manager)
18575
18576@strong{Library_GCC}:
18577
18578@quotation
18579
18580This attribute is the name of the tool to use instead of "gcc" to link shared
18581libraries. A common use of this attribute is to define a wrapper script that
18582accomplishes specific actions before calling gcc (which itself calls the
18583linker to build the library image).
18584@end quotation
18585
18586@geindex Library_Options (GNAT Project Manager)
18587
18588@strong{Library_Options}:
18589
18590@quotation
18591
18592This attribute may be used to specify additional switches (last switches)
18593when linking a shared library.
18594
18595It may also be used to add foreign object files to a static library.
18596Each string in Library_Options is an absolute or relative path of an object
18597file. When a relative path, it is relative to the object directory.
18598@end quotation
18599
18600@geindex Leading_Library_Options (GNAT Project Manager)
18601
18602@strong{Leading_Library_Options}:
18603
18604@quotation
18605
18606This attribute, that is taken into account only by @emph{gprbuild}, may be
18607used to specified leading options (first switches) when linking a shared
18608library.
18609@end quotation
18610
18611@geindex Linker_Options (GNAT Project Manager)
18612
18613@strong{Linker.Linker_Options}:
18614
18615@quotation
18616
18617This attribute specifies additional switches to be given to the linker when
18618linking an executable. It is ignored when defined in the main project and
18619taken into account in all other projects that are imported directly or
18620indirectly. These switches complement the @cite{Linker.Switches}
18621defined in the main project. This is useful when a particular subsystem
18622depends on an external library: adding this dependency as a
18623@cite{Linker_Options} in the project of the subsystem is more convenient than
18624adding it to all the @cite{Linker.Switches} of the main projects that depend
18625upon this subsystem.
18626@end quotation
18627
18628@node Using Library Projects,Stand-alone Library Projects,Building Libraries,Library Projects
18629@anchor{gnat_ugn/gnat_project_manager id22}@anchor{17a}@anchor{gnat_ugn/gnat_project_manager using-library-projects}@anchor{17b}
18630@subsection Using Library Projects
18631
18632
18633When the builder detects that a project file is a library project file, it
18634recompiles all sources of the project that need recompilation and rebuild the
18635library if any of the sources have been recompiled. It then groups all object
18636files into a single file, which is a shared or a static library. This library
18637can later on be linked with multiple executables. Note that the use
18638of shard libraries reduces the size of the final executable and can also reduce
18639the memory footprint at execution time when the library is shared among several
18640executables.
18641
18642It is also possible to build @strong{multi-language libraries}. When using
18643@emph{gprbuild} as a builder, multi-language library projects allow naturally
18644the creation of multi-language libraries . @emph{gnatmake}, does not try to
18645compile non Ada sources. However, when the project is multi-language, it will
18646automatically link all object files found in the object directory, whether or
18647not they were compiled from an Ada source file. This specific behavior does not
18648apply to Ada-only projects which only take into account the objects
18649corresponding to the sources of the project.
18650
18651A non-library project can import a library project. When the builder is invoked
18652on the former, the library of the latter is only rebuilt when absolutely
18653necessary. For instance, if a unit of the library is not up-to-date but none of
18654the executables need this unit, then the unit is not recompiled and the library
18655is not reassembled.  For instance, let's assume in our example that logging has
18656the following sources: @code{log1.ads}, @code{log1.adb}, @code{log2.ads} and
18657@code{log2.adb}. If @code{log1.adb} has been modified, then the library
18658@code{liblogging} will be rebuilt when compiling all the sources of
18659@cite{Build} only if @code{proc.ads}, @code{pack.ads} or @code{pack.adb}
18660include a @cite{"with Log1"}.
18661
18662To ensure that all the sources in the @cite{Logging} library are
18663up to date, and that all the sources of @cite{Build} are also up to date,
18664the following two commands need to be used:
18665
18666@example
18667gnatmake -Plogging.gpr
18668gnatmake -Pbuild.gpr
18669@end example
18670
18671All @code{ALI} files will also be copied from the object directory to the
18672library directory. To build executables, @emph{gnatmake} will use the
18673library rather than the individual object files.
18674
18675Library projects can also be useful to describe a library that needs to be used
18676but, for some reason, cannot be rebuilt. For instance, it is the case when some
18677of the library sources are not available. Such library projects need to use the
18678@cite{Externally_Built} attribute as in the example below:
18679
18680@c code-block: ada-project
18681@c 
18682@c library project Extern_Lib is
18683@c    for Languages    use ("Ada", "C");
18684@c    for Source_Dirs  use ("lib_src");
18685@c    for Library_Dir  use "lib2";
18686@c    for Library_Kind use "dynamic";
18687@c    for Library_Name use "l2";
18688@c    for Externally_Built use "true";  --  <<<<
18689@c end Extern_Lib;
18690
18691In the case of externally built libraries, the @cite{Object_Dir}
18692attribute does not need to be specified because it will never be
18693used.
18694
18695The main effect of using such an externally built library project is mostly to
18696affect the linker command in order to reference the desired library. It can
18697also be achieved by using @cite{Linker.Linker_Options} or @cite{Linker.Switches}
18698in the project corresponding to the subsystem needing this external library.
18699This latter method is more straightforward in simple cases but when several
18700subsystems depend upon the same external library, finding the proper place
18701for the @cite{Linker.Linker_Options} might not be easy and if it is
18702not placed properly, the final link command is likely to present ordering issues.
18703In such a situation, it is better to use the externally built library project
18704so that all other subsystems depending on it can declare this dependency thanks
18705to a project @emph{with} clause, which in turn will trigger the builder to find
18706the proper order of libraries in the final link command.
18707
18708@node Stand-alone Library Projects,Installing a library with project files,Using Library Projects,Library Projects
18709@anchor{gnat_ugn/gnat_project_manager id23}@anchor{17c}@anchor{gnat_ugn/gnat_project_manager stand-alone-library-projects}@anchor{97}
18710@subsection Stand-alone Library Projects
18711
18712
18713@geindex standalone libraries (usage with GNAT Project Manager)
18714
18715A @strong{stand-alone library} is a library that contains the necessary code to
18716elaborate the Ada units that are included in the library. A stand-alone
18717library is a convenient way to add an Ada subsystem to a more global system
18718whose main is not in Ada since it makes the elaboration of the Ada part mostly
18719transparent. However, stand-alone libraries are also useful when the main is in
18720Ada: they provide a means for minimizing relinking & redeployment of complex
18721systems when localized changes are made.
18722
18723The name of a stand-alone library, specified with attribute
18724@cite{Library_Name}, must have the syntax of an Ada identifier.
18725
18726The most prominent characteristic of a stand-alone library is that it offers a
18727distinction between interface units and implementation units. Only the former
18728are visible to units outside the library. A stand-alone library project is thus
18729characterised by a third attribute, usually @strong{Library_Interface}, in addition
18730to the two attributes that make a project a Library Project
18731(@cite{Library_Name} and @cite{Library_Dir}). This third attribute may also be
18732@strong{Interfaces}. @strong{Library_Interface} only works when the interface is in Ada
18733and takes a list of units as parameter. @strong{Interfaces} works for any supported
18734language and takes a list of sources as parameter.
18735
18736@geindex Library_Interface (GNAT Project Manager)
18737
18738@strong{Library_Interface}:
18739
18740@quotation
18741
18742This attribute defines an explicit subset of the units of the project. Units
18743from projects importing this library project may only "with" units whose
18744sources are listed in the @cite{Library_Interface}. Other sources are
18745considered implementation units.
18746
18747@example
18748for Library_Dir use "lib";
18749for Library_Name use "logging";
18750for Library_Interface use ("lib1", "lib2");  --  unit names
18751@end example
18752@end quotation
18753
18754@strong{Interfaces}
18755
18756@quotation
18757
18758This attribute defines an explicit subset of the source files of a project.
18759Sources from projects importing this project, can only depend on sources from
18760this subset. This attribute can be used on non library projects. It can also
18761be used as a replacement for attribute @cite{Library_Interface}, in which
18762case, units have to be replaced by source files. For multi-language library
18763projects, it is the only way to make the project a Stand-Alone Library project
18764whose interface is not purely Ada.
18765@end quotation
18766
18767@geindex Library_Standalone (GNAT Project Manager)
18768
18769@strong{Library_Standalone}:
18770
18771@quotation
18772
18773This attribute defines the kind of standalone library to
18774build. Values are either @cite{standard} (the default), @cite{no} or
18775@cite{encapsulated}. When @cite{standard} is used the code to elaborate and
18776finalize the library is embedded, when @cite{encapsulated} is used the
18777library can furthermore depend only on static libraries (including
18778the GNAT runtime). This attribute can be set to @cite{no} to make it clear
18779that the library should not be standalone in which case the
18780@cite{Library_Interface} should not defined. Note that this attribute
18781only applies to shared libraries, so @cite{Library_Kind} must be set
18782to @cite{dynamic}.
18783
18784@example
18785for Library_Dir use "lib";
18786for Library_Name use "logging";
18787for Library_Kind use "dynamic";
18788for Library_Interface use ("lib1", "lib2");  --  unit names
18789for Library_Standalone use "encapsulated";
18790@end example
18791@end quotation
18792
18793In order to include the elaboration code in the stand-alone library, the binder
18794is invoked on the closure of the library units creating a package whose name
18795depends on the library name (b~logging.ads/b in the example).
18796This binder-generated package includes @strong{initialization} and @strong{finalization}
18797procedures whose names depend on the library name (@cite{logginginit} and
18798@cite{loggingfinal} in the example). The object corresponding to this package is
18799included in the library.
18800
18801@geindex Library_Auto_Init (GNAT Project Manager)
18802
18803@strong{Library_Auto_Init}:
18804
18805@quotation
18806
18807A dynamic stand-alone Library is automatically initialized
18808if automatic initialization of Stand-alone Libraries is supported on the
18809platform and if attribute @strong{Library_Auto_Init} is not specified or
18810is specified with the value "true". A static Stand-alone Library is never
18811automatically initialized. Specifying "false" for this attribute
18812prevents automatic initialization.
18813
18814When a non-automatically initialized stand-alone library is used in an
18815executable, its initialization procedure must be called before any service of
18816the library is used. When the main subprogram is in Ada, it may mean that the
18817initialization procedure has to be called during elaboration of another
18818package.
18819@end quotation
18820
18821@geindex Library_Dir (GNAT Project Manager)
18822
18823@strong{Library_Dir}:
18824
18825@quotation
18826
18827For a stand-alone library, only the @code{ALI} files of the interface units
18828(those that are listed in attribute @cite{Library_Interface}) are copied to
18829the library directory. As a consequence, only the interface units may be
18830imported from Ada units outside of the library. If other units are imported,
18831the binding phase will fail.
18832@end quotation
18833
18834@strong{Binder.Default_Switches}:
18835
18836@quotation
18837
18838When a stand-alone library is bound, the switches that are specified in
18839the attribute @strong{Binder.Default_Switches ("Ada")} are
18840used in the call to @emph{gnatbind}.
18841@end quotation
18842
18843@geindex Library_Src_Dir (GNAT Project Manager)
18844
18845@strong{Library_Src_Dir}:
18846
18847@quotation
18848
18849This attribute defines the location (absolute or relative to the project
18850directory) where the sources of the interface units are copied at
18851installation time.
18852These sources includes the specs of the interface units along with the
18853closure of sources necessary to compile them successfully. That may include
18854bodies and subunits, when pragmas @cite{Inline} are used, or when there are
18855generic units in specs. This directory cannot point to the object directory
18856or one of the source directories, but it can point to the library directory,
18857which is the default value for this attribute.
18858@end quotation
18859
18860@geindex Library_Symbol_Policy (GNAT Project Manager)
18861
18862@strong{Library_Symbol_Policy}:
18863
18864@quotation
18865
18866This attribute controls the export of symbols and, on some platforms (like
18867VMS) that have the notions of major and minor IDs built in the library
18868files, it controls the setting of these IDs. It is not supported on all
18869platforms (where it will just have no effect). It may have one of the
18870following values:
18871
18872
18873@itemize *
18874
18875@item 
18876@cite{"autonomous"} or @cite{"default"}: exported symbols are not controlled
18877
18878@item 
18879@cite{"compliant"}: if attribute @strong{Library_Reference_Symbol_File}
18880is not defined, then it is equivalent to policy "autonomous". If there
18881are exported symbols in the reference symbol file that are not in the
18882object files of the interfaces, the major ID of the library is increased.
18883If there are symbols in the object files of the interfaces that are not
18884in the reference symbol file, these symbols are put at the end of the list
18885in the newly created symbol file and the minor ID is increased.
18886
18887@item 
18888@cite{"controlled"}: the attribute @strong{Library_Reference_Symbol_File} must be
18889defined. The library will fail to build if the exported symbols in the
18890object files of the interfaces do not match exactly the symbol in the
18891symbol file.
18892
18893@item 
18894@cite{"restricted"}: The attribute @strong{Library_Symbol_File} must be defined.
18895The library will fail to build if there are symbols in the symbol file that
18896are not in the exported symbols of the object files of the interfaces.
18897Additional symbols in the object files are not added to the symbol file.
18898
18899@item 
18900@cite{"direct"}: The attribute @strong{Library_Symbol_File} must be defined and
18901must designate an existing file in the object directory. This symbol file
18902is passed directly to the underlying linker without any symbol processing.
18903@end itemize
18904@end quotation
18905
18906@geindex Library_Reference_Symbol_File (GNAT Project Manager)
18907
18908@strong{Library_Reference_Symbol_File}
18909
18910@quotation
18911
18912This attribute may define the path name of a reference symbol file that is
18913read when the symbol policy is either "compliant" or "controlled", on
18914platforms that support symbol control, such as VMS, when building a
18915stand-alone library. The path may be an absolute path or a path relative
18916to the project directory.
18917@end quotation
18918
18919@geindex Library_Symbol_File (GNAT Project Manager)
18920
18921@strong{Library_Symbol_File}
18922
18923@quotation
18924
18925This attribute may define the name of the symbol file to be created when
18926building a stand-alone library when the symbol policy is either "compliant",
18927"controlled" or "restricted", on platforms that support symbol control,
18928such as VMS. When symbol policy is "direct", then a file with this name
18929must exist in the object directory.
18930@end quotation
18931
18932@node Installing a library with project files,,Stand-alone Library Projects,Library Projects
18933@anchor{gnat_ugn/gnat_project_manager installing-a-library-with-project-files}@anchor{8d}@anchor{gnat_ugn/gnat_project_manager id24}@anchor{17d}
18934@subsection Installing a library with project files
18935
18936
18937When using project files, a usable version of the library is created in the
18938directory specified by the @cite{Library_Dir} attribute of the library
18939project file. Thus no further action is needed in order to make use of
18940the libraries that are built as part of the general application build.
18941
18942You may want to install a library in a context different from where the library
18943is built. This situation arises with third party suppliers, who may want
18944to distribute a library in binary form where the user is not expected to be
18945able to recompile the library. The simplest option in this case is to provide
18946a project file slightly different from the one used to build the library, by
18947using the @cite{externally_built} attribute. See @ref{17b,,Using Library Projects}
18948
18949Another option is to use @emph{gprinstall} to install the library in a
18950different context than the build location. @emph{gprinstall} automatically
18951generates a project to use this library, and also copies the minimum set of
18952sources needed to use the library to the install location.
18953@ref{168,,Installation}
18954
18955@node Project Extension,Aggregate Projects,Library Projects,GNAT Project Manager
18956@anchor{gnat_ugn/gnat_project_manager id25}@anchor{17e}@anchor{gnat_ugn/gnat_project_manager project-extension}@anchor{14f}
18957@section Project Extension
18958
18959
18960During development of a large system, it is sometimes necessary to use
18961modified versions of some of the source files, without changing the original
18962sources. This can be achieved through the @strong{project extension} facility.
18963
18964Suppose for instance that our example @cite{Build} project is built every night
18965for the whole team, in some shared directory. A developer usually needs to work
18966on a small part of the system, and might not want to have a copy of all the
18967sources and all the object files (mostly because that would require too much
18968disk space, time to recompile everything). He prefers to be able to override
18969some of the source files in his directory, while taking advantage of all the
18970object files generated at night.
18971
18972Another example can be taken from large software systems, where it is common to have
18973multiple implementations of a common interface; in Ada terms, multiple
18974versions of a package body for the same spec.  For example, one implementation
18975might be safe for use in tasking programs, while another might be used only
18976in sequential applications.  This can be modeled in GNAT using the concept
18977of @emph{project extension}.  If one project (the 'child') @emph{extends}
18978another project (the 'parent') then by default all source files of the
18979parent project are inherited by the child, but the child project can
18980override any of the parent's source files with new versions, and can also
18981add new files or remove unnecessary ones.
18982This facility is the project analog of a type extension in
18983object-oriented programming.  Project hierarchies are permitted (an extending
18984project may itself be extended), and a project that
18985extends a project can also import other projects.
18986
18987A third example is that of using project extensions to provide different
18988versions of the same system. For instance, assume that a @cite{Common}
18989project is used by two development branches. One of the branches has now
18990been frozen, and no further change can be done to it or to @cite{Common}.
18991However, the other development branch still needs evolution of @cite{Common}.
18992Project extensions provide a flexible solution to create a new version
18993of a subsystem while sharing and reusing as much as possible from the original
18994one.
18995
18996A project extension implicitly inherits all the sources and objects from the
18997project it extends. It is possible to create a new version of some of the
18998sources in one of the additional source directories of the extending
18999project. Those new versions hide the original versions. Adding new sources or
19000removing existing ones is also possible. Here is an example on how to extend
19001the project @cite{Build} from previous examples:
19002
19003@example
19004project Work extends "../bld/build.gpr" is
19005end Work;
19006@end example
19007
19008The project after @strong{extends} is the one being extended. As usual, it can be
19009specified using an absolute path, or a path relative to any of the directories
19010in the project path (see @ref{16c,,Project Dependencies}). This project does not
19011specify source or object directories, so the default values for these
19012attributes will be used that is to say the current directory (where project
19013@cite{Work} is placed). We can compile that project with
19014
19015@example
19016gprbuild -Pwork
19017@end example
19018
19019If no sources have been placed in the current directory, this command
19020won't do anything, since this project does not change the
19021sources it inherited from @cite{Build}, therefore all the object files
19022in @cite{Build} and its dependencies are still valid and are reused
19023automatically.
19024
19025Suppose we now want to supply an alternate version of @code{pack.adb} but use
19026the existing versions of @code{pack.ads} and @code{proc.adb}.  We can create
19027the new file in Work's current directory (likely by copying the one from the
19028@cite{Build} project and making changes to it. If new packages are needed at
19029the same time, we simply create new files in the source directory of the
19030extending project.
19031
19032When we recompile, @emph{gprbuild} will now automatically recompile
19033this file (thus creating @code{pack.o} in the current directory) and
19034any file that depends on it (thus creating @code{proc.o}). Finally, the
19035executable is also linked locally.
19036
19037Note that we could have obtained the desired behavior using project import
19038rather than project inheritance. A @cite{base} project would contain the
19039sources for @code{pack.ads} and @code{proc.adb}, and @cite{Work} would
19040import @cite{base} and add @code{pack.adb}. In this scenario,  @cite{base}
19041cannot contain the original version of @code{pack.adb} otherwise there would be
190422 versions of the same unit in the closure of the project and this is not
19043allowed. Generally speaking, it is not recommended to put the spec and the
19044body of a unit in different projects since this affects their autonomy and
19045reusability.
19046
19047In a project file that extends another project, it is possible to
19048indicate that an inherited source is @strong{not part} of the sources of the
19049extending project. This is necessary sometimes when a package spec has
19050been overridden and no longer requires a body: in this case, it is
19051necessary to indicate that the inherited body is not part of the sources
19052of the project, otherwise there will be a compilation error
19053when compiling the spec.
19054
19055@geindex Excluded_Source_Files (GNAT Project Manager)
19056
19057@geindex Excluded_Source_List_File (GNAT Project Manager)
19058
19059For that purpose, the attribute @strong{Excluded_Source_Files} is used.
19060Its value is a list of file names.
19061It is also possible to use attribute @cite{Excluded_Source_List_File}.
19062Its value is the path of a text file containing one file name per
19063line.
19064
19065@example
19066project Work extends "../bld/build.gpr" is
19067   for Source_Files use ("pack.ads");
19068   --  New spec of Pkg does not need a completion
19069   for Excluded_Source_Files use ("pack.adb");
19070end Work;
19071@end example
19072
19073All packages that are not declared in the extending project are inherited from
19074the project being extended, with their attributes, with the exception of
19075@cite{Linker'Linker_Options} which is never inherited. In particular, an
19076extending project retains all the switches specified in the project being
19077extended.
19078
19079At the project level, if they are not declared in the extending project, some
19080attributes are inherited from the project being extended. They are:
19081@cite{Languages}, @cite{Main} (for a root non library project) and
19082@cite{Library_Name} (for a project extending a library project).
19083
19084@menu
19085* Project Hierarchy Extension:: 
19086
19087@end menu
19088
19089@node Project Hierarchy Extension,,,Project Extension
19090@anchor{gnat_ugn/gnat_project_manager project-hierarchy-extension}@anchor{17f}@anchor{gnat_ugn/gnat_project_manager id26}@anchor{180}
19091@subsection Project Hierarchy Extension
19092
19093
19094One of the fundamental restrictions in project extension is the following:
19095@strong{A project is not allowed to import directly or indirectly at the same time an extending project and one of its ancestors}.
19096
19097For example, consider the following hierarchy of projects.
19098
19099@example
19100a.gpr  contains package A1
19101b.gpr, imports a.gpr and contains B1, which depends on A1
19102c.gpr, imports b.gpr and contains C1, which depends on B1
19103@end example
19104
19105If we want to locally extend the packages @cite{A1} and @cite{C1}, we need to
19106create several extending projects:
19107
19108@example
19109a_ext.gpr which extends a.gpr, and overrides A1
19110b_ext.gpr which extends b.gpr and imports a_ext.gpr
19111c_ext.gpr which extends c.gpr, imports b_ext.gpr and overrides C1
19112@end example
19113
19114@example
19115project A_Ext extends "a.gpr" is
19116   for Source_Files use ("a1.adb", "a1.ads");
19117end A_Ext;
19118
19119with "a_ext.gpr";
19120project B_Ext extends "b.gpr" is
19121end B_Ext;
19122
19123with "b_ext.gpr";
19124project C_Ext extends "c.gpr" is
19125   for Source_Files use ("c1.adb");
19126end C_Ext;
19127@end example
19128
19129The extension @code{b_ext.gpr} is required, even though we are not overriding
19130any of the sources of @code{b.gpr} because otherwise @code{c_expr.gpr} would
19131import @code{b.gpr} which itself knows nothing about @code{a_ext.gpr}.
19132
19133@geindex extends all (GNAT Project Manager)
19134
19135When extending a large system spanning multiple projects, it is often
19136inconvenient to extend every project in the hierarchy that is impacted by a
19137small change introduced in a low layer. In such cases, it is possible to create
19138an @strong{implicit extension} of an entire hierarchy using @strong{extends all}
19139relationship.
19140
19141When the project is extended using @cite{extends all} inheritance, all projects
19142that are imported by it, both directly and indirectly, are considered virtually
19143extended. That is, the project manager creates implicit projects
19144that extend every project in the hierarchy; all these implicit projects do not
19145control sources on their own and use the object directory of
19146the "extending all" project.
19147
19148It is possible to explicitly extend one or more projects in the hierarchy
19149in order to modify the sources. These extending projects must be imported by
19150the "extending all" project, which will replace the corresponding virtual
19151projects with the explicit ones.
19152
19153When building such a project hierarchy extension, the project manager will
19154ensure that both modified sources and sources in implicit extending projects
19155that depend on them are recompiled.
19156
19157Thus, in our example we could create the following projects instead:
19158
19159@example
19160a_ext.gpr, extends a.gpr and overrides A1
19161c_ext.gpr, "extends all" c.gpr, imports a_ext.gpr and overrides C1
19162@end example
19163
19164@example
19165project A_Ext extends "a.gpr" is
19166   for Source_Files use ("a1.adb", "a1.ads");
19167end A_Ext;
19168
19169with "a_ext.gpr";
19170project C_Ext extends all "c.gpr" is
19171  for Source_Files use ("c1.adb");
19172end C_Ext;
19173@end example
19174
19175When building project @code{c_ext.gpr}, the entire modified project space is
19176considered for recompilation, including the sources of @code{b.gpr} that are
19177impacted by the changes in @cite{A1} and @cite{C1}.
19178
19179@node Aggregate Projects,Aggregate Library Projects,Project Extension,GNAT Project Manager
19180@anchor{gnat_ugn/gnat_project_manager aggregate-projects}@anchor{16e}@anchor{gnat_ugn/gnat_project_manager id27}@anchor{181}
19181@section Aggregate Projects
19182
19183
19184Aggregate projects are an extension of the project paradigm, and are
19185meant to solve a few specific use cases that cannot be solved directly
19186using standard projects. This section will go over a few of these use
19187cases to try to explain what you can use aggregate projects for.
19188
19189@menu
19190* Building all main programs from a single project tree:: 
19191* Building a set of projects with a single command:: 
19192* Define a build environment:: 
19193* Performance improvements in builder:: 
19194* Syntax of aggregate projects:: 
19195* package Builder in aggregate projects:: 
19196
19197@end menu
19198
19199@node Building all main programs from a single project tree,Building a set of projects with a single command,,Aggregate Projects
19200@anchor{gnat_ugn/gnat_project_manager id28}@anchor{182}@anchor{gnat_ugn/gnat_project_manager building-all-main-programs-from-a-single-project-tree}@anchor{183}
19201@subsection Building all main programs from a single project tree
19202
19203
19204Most often, an application is organized into modules and submodules,
19205which are very conveniently represented as a project tree or graph
19206(the root project A @emph{with}s the projects for each modules (say B and C),
19207which in turn @emph{with} projects for submodules.
19208
19209Very often, modules will build their own executables (for testing
19210purposes for instance), or libraries (for easier reuse in various
19211contexts).
19212
19213However, if you build your project through @emph{gnatmake} or
19214@emph{gprbuild}, using a syntax similar to
19215
19216@example
19217gprbuild -PA.gpr
19218@end example
19219
19220this will only rebuild the main programs of project A, not those of the
19221imported projects B and C. Therefore you have to spawn several
19222@emph{gnatmake} commands, one per project, to build all executables.
19223This is a little inconvenient, but more importantly is inefficient
19224because @emph{gnatmake} needs to do duplicate work to ensure that sources are
19225up-to-date, and cannot easily compile things in parallel when using
19226the -j switch.
19227
19228Also libraries are always rebuilt when building a project.
19229
19230You could therefore define an aggregate project Agg that groups A, B
19231and C. Then, when you build with
19232
19233@example
19234gprbuild -PAgg.gpr
19235@end example
19236
19237this will build all mains from A, B and C.
19238
19239@example
19240aggregate project Agg is
19241   for Project_Files use ("a.gpr", "b.gpr", "c.gpr");
19242end Agg;
19243@end example
19244
19245If B or C do not define any main program (through their Main
19246attribute), all their sources are built. When you do not group them
19247in the aggregate project, only those sources that are needed by A
19248will be built.
19249
19250If you add a main to a project P not already explicitly referenced in the
19251aggregate project, you will need to add "p.gpr" in the list of project
19252files for the aggregate project, or the main will not be built when
19253building the aggregate project.
19254
19255Aggregate projects are supported only with @emph{gprbuild}, not with
19256@emph{gnatmake}.
19257
19258@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
19259@anchor{gnat_ugn/gnat_project_manager building-a-set-of-projects-with-a-single-command}@anchor{184}@anchor{gnat_ugn/gnat_project_manager id29}@anchor{185}
19260@subsection Building a set of projects with a single command
19261
19262
19263One other case is when you have multiple applications and libraries
19264that are built independently from each other (but can be built in
19265parallel). For instance, you have a project tree rooted at A, and
19266another one (which might share some subprojects) rooted at B.
19267
19268Using only @emph{gprbuild}, you could do
19269
19270@example
19271gprbuild -PA.gpr
19272gprbuild -PB.gpr
19273@end example
19274
19275to build both. But again, @emph{gprbuild} has to do some duplicate work for
19276those files that are shared between the two, and cannot truly build
19277things in parallel efficiently.
19278
19279If the two projects are really independent, share no sources other
19280than through a common subproject, and have no source files with a
19281common basename, you could create a project C that imports A and
19282B. But these restrictions are often too strong, and one has to build
19283them independently. An aggregate project does not have these
19284limitations and can aggregate two project trees that have common
19285sources.
19286
19287This scenario is particularly useful in environments like VxWorks 653
19288where the applications running in the multiple partitions can be built
19289in parallel through a single @emph{gprbuild} command. This also works nicely
19290with Annex E.
19291
19292@node Define a build environment,Performance improvements in builder,Building a set of projects with a single command,Aggregate Projects
19293@anchor{gnat_ugn/gnat_project_manager id30}@anchor{186}@anchor{gnat_ugn/gnat_project_manager define-a-build-environment}@anchor{187}
19294@subsection Define a build environment
19295
19296
19297The environment variables at the time you launch @emph{gprbuild}
19298will influence the view these tools have of the project
19299(PATH to find the compiler, ADA_PROJECT_PATH or GPR_PROJECT_PATH to find the
19300projects, environment variables that are referenced in project files
19301through the "external" built-in function, ...). Several command line switches
19302can be used to override those (-X or -aP), but on some systems and
19303with some projects, this might make the command line too long, and on
19304all systems often make it hard to read.
19305
19306An aggregate project can be used to set the environment for all
19307projects built through that aggregate. One of the nice aspects is that
19308you can put the aggregate project under configuration management, and
19309make sure all your user have a consistent environment when
19310building. The syntax looks like
19311
19312@example
19313aggregate project Agg is
19314   for Project_Files use ("A.gpr", "B.gpr");
19315   for Project_Path use ("../dir1", "../dir1/dir2");
19316   for External ("BUILD") use "PRODUCTION";
19317
19318   package Builder is
19319      for Switches ("Ada") use ("-q");
19320   end Builder;
19321end Agg;
19322@end example
19323
19324One of the often requested features in projects is to be able to
19325reference external variables in @emph{with} declarations, as in
19326
19327@example
19328with external("SETUP") & "path/prj.gpr";   --  ILLEGAL
19329project MyProject is
19330   ...
19331end MyProject;
19332@end example
19333
19334For various reasons, this is not allowed. But using aggregate projects provide
19335an elegant solution. For instance, you could use a project file like:
19336
19337@example
19338aggregate project Agg is
19339    for Project_Path use (external("SETUP") & "path");
19340    for Project_Files use ("myproject.gpr");
19341end Agg;
19342
19343with "prj.gpr";  --  searched on Agg'Project_Path
19344project MyProject is
19345   ...
19346end MyProject;
19347@end example
19348
19349@node Performance improvements in builder,Syntax of aggregate projects,Define a build environment,Aggregate Projects
19350@anchor{gnat_ugn/gnat_project_manager performance-improvements-in-builder}@anchor{188}@anchor{gnat_ugn/gnat_project_manager id31}@anchor{189}
19351@subsection Performance improvements in builder
19352
19353
19354The loading of aggregate projects is optimized in @emph{gprbuild},
19355so that all files are searched for only once on the disk
19356(thus reducing the number of system calls and contributing to faster
19357compilation times, especially on systems with sources on remote
19358servers). As part of the loading, @emph{gprbuild}
19359computes how and where a source file should be compiled, and even if it is
19360found several times in the aggregated projects it will be compiled only
19361once.
19362
19363Since there is no ambiguity as to which switches should be used, files
19364can be compiled in parallel (through the usual -j switch) and this can
19365be done while maximizing the use of CPUs (compared to launching
19366multiple @emph{gprbuild} and @emph{gnatmake} commands in parallel).
19367
19368@node Syntax of aggregate projects,package Builder in aggregate projects,Performance improvements in builder,Aggregate Projects
19369@anchor{gnat_ugn/gnat_project_manager id32}@anchor{18a}@anchor{gnat_ugn/gnat_project_manager syntax-of-aggregate-projects}@anchor{18b}
19370@subsection Syntax of aggregate projects
19371
19372
19373An aggregate project follows the general syntax of project files. The
19374recommended extension is still @code{.gpr}. However, a special
19375@cite{aggregate} qualifier must be put before the keyword
19376@cite{project}.
19377
19378An aggregate project cannot @emph{with} any other project (standard or
19379aggregate), except an abstract project which can be used to share attribute
19380values. Also, aggregate projects cannot be extended or imported though a
19381@emph{with} clause by any other project. Building other aggregate projects from
19382an aggregate project is done through the Project_Files attribute (see below).
19383
19384An aggregate project does not have any source files directly (only
19385through other standard projects). Therefore a number of the standard
19386attributes and packages are forbidden in an aggregate project. Here is the
19387(non exhaustive) list:
19388
19389
19390@itemize *
19391
19392@item 
19393Languages
19394
19395@item 
19396Source_Files, Source_List_File and other attributes dealing with
19397list of sources.
19398
19399@item 
19400Source_Dirs, Exec_Dir and Object_Dir
19401
19402@item 
19403Library_Dir, Library_Name and other library-related attributes
19404
19405@item 
19406Main
19407
19408@item 
19409Roots
19410
19411@item 
19412Externally_Built
19413
19414@item 
19415Inherit_Source_Path
19416
19417@item 
19418Excluded_Source_Dirs
19419
19420@item 
19421Locally_Removed_Files
19422
19423@item 
19424Excluded_Source_Files
19425
19426@item 
19427Excluded_Source_List_File
19428
19429@item 
19430Interfaces
19431@end itemize
19432
19433The only package that is authorized (albeit optional) is
19434Builder. Other packages (in particular Compiler, Binder and Linker)
19435are forbidden.
19436
19437The following three attributes can be used only in an aggregate project:
19438
19439@geindex Project_Files (GNAT Project Manager)
19440
19441@strong{Project_Files}:
19442
19443@quotation
19444
19445This attribute is compulsory (or else we are not aggregating any project,
19446and thus not doing anything). It specifies a list of @code{.gpr} files
19447that are grouped in the aggregate. The list may be empty. The project
19448files can be either other aggregate projects, or standard projects. When
19449grouping standard projects, you can have both the root of a project tree
19450(and you do not need to specify all its imported projects), and any project
19451within the tree.
19452
19453Basically, the idea is to specify all those projects that have
19454main programs you want to build and link, or libraries you want to
19455build. You can even specify projects that do not use the Main
19456attribute nor the @cite{Library_*} attributes, and the result will be to
19457build all their source files (not just the ones needed by other
19458projects).
19459
19460The file can include paths (absolute or relative). Paths are relative to
19461the location of the aggregate project file itself (if you use a base name,
19462we expect to find the .gpr file in the same directory as the aggregate
19463project file). The environment variables @cite{ADA_PROJECT_PATH},
19464@cite{GPR_PROJECT_PATH} and @cite{GPR_PROJECT_PATH_FILE} are not used to find
19465the project files. The extension @code{.gpr} is mandatory, since this attribute
19466contains file names, not project names.
19467
19468Paths can also include the @cite{"*"} and @cite{"**"} globbing patterns. The
19469latter indicates that any subdirectory (recursively) will be
19470searched for matching files. The latter (@cite{"**"}) can only occur at the
19471last position in the directory part (ie @cite{"a/**/*.gpr"} is supported, but
19472not @cite{"**/a/*.gpr"}). Starting the pattern with @cite{"**"} is equivalent
19473to starting with @cite{"./**"}.
19474
19475For now, the pattern @cite{"*"} is only allowed in the filename part, not
19476in the directory part. This is mostly for efficiency reasons to limit the
19477number of system calls that are needed.
19478
19479Here are a few valid examples:
19480
19481@example
19482for Project_Files use ("a.gpr", "subdir/b.gpr");
19483--  two specific projects relative to the directory of agg.gpr
19484
19485for Project_Files use ("/.gpr");
19486--  all projects recursively
19487@end example
19488@end quotation
19489
19490@geindex Project_Path (GNAT Project Manager)
19491
19492@strong{Project_Path}:
19493
19494@quotation
19495
19496This attribute can be used to specify a list of directories in
19497which to look for project files in @emph{with} declarations.
19498
19499When you specify a project in Project_Files (say @cite{x/y/a.gpr}), and
19500@cite{a.gpr} imports a project @cite{b.gpr}, only @cite{b.gpr} is searched in
19501the project path. @cite{a.gpr} must be exactly at
19502@cite{<dir of the aggregate>/x/y/a.gpr}.
19503
19504This attribute, however, does not affect the search for the aggregated
19505project files specified with @cite{Project_Files}.
19506
19507Each aggregate project has its own @cite{Project_Path} (that is if
19508@cite{agg1.gpr} includes @cite{agg2.gpr}, they can potentially both have a
19509different @cite{Project_Path}).
19510
19511This project path is defined as the concatenation, in that order, of:
19512
19513
19514@itemize *
19515
19516@item 
19517the current directory;
19518
19519@item 
19520followed by the command line -aP switches;
19521
19522@item 
19523then the directories from the GPR_PROJECT_PATH and ADA_PROJECT_PATH environment
19524variables;
19525
19526@item 
19527then the directories from the Project_Path attribute;
19528
19529@item 
19530and finally the predefined directories.
19531@end itemize
19532
19533In the example above, agg2.gpr's project path is not influenced by
19534the attribute agg1'Project_Path, nor is agg1 influenced by
19535agg2'Project_Path.
19536
19537This can potentially lead to errors. Consider the following example:
19538
19539@example
19540--
19541--  +---------------+                  +----------------+
19542--  | Agg1.gpr      |-=--includes--=-->| Agg2.gpr       |
19543--  |  'project_path|                  |  'project_path |
19544--  |               |                  |                |
19545--  +---------------+                  +----------------+
19546--        :                                   :
19547--        includes                        includes
19548--        :                                   :
19549--        v                                   v
19550--    +-------+                          +---------+
19551--    | P.gpr |<---------- withs --------|  Q.gpr  |
19552--    +-------+---------\                +---------+
19553--        |             |
19554--        withs         |
19555--        |             |
19556--        v             v
19557--    +-------+      +---------+
19558--    | R.gpr |      | R'.gpr  |
19559--    +-------+      +---------+
19560@end example
19561
19562When looking for p.gpr, both aggregates find the same physical file on
19563the disk. However, it might happen that with their different project
19564paths, both aggregate projects would in fact find a different r.gpr.
19565Since we have a common project (p.gpr) "with"ing two different r.gpr,
19566this will be reported as an error by the builder.
19567
19568Directories are relative to the location of the aggregate project file.
19569
19570Example:
19571
19572@example
19573for Project_Path use ("/usr/local/gpr", "gpr/");
19574@end example
19575@end quotation
19576
19577@geindex External (GNAT Project Manager)
19578
19579@strong{External}:
19580
19581@quotation
19582
19583This attribute can be used to set the value of environment
19584variables as retrieved through the @cite{external} function
19585in projects. It does not affect the environment variables
19586themselves (so for instance you cannot use it to change the value
19587of your PATH as seen from the spawned compiler).
19588
19589This attribute affects the external values as seen in the rest of
19590the aggregate project, and in the aggregated projects.
19591
19592The exact value of external a variable comes from one of three
19593sources (each level overrides the previous levels):
19594
19595
19596@itemize *
19597
19598@item 
19599An External attribute in aggregate project, for instance
19600@cite{for External ("BUILD_MODE") use "DEBUG"};
19601
19602@item 
19603Environment variables.
19604These override the value given by the attribute, so that
19605users can override the value set in the (presumably shared
19606with others team members) aggregate project.
19607
19608@item 
19609The -X command line switch to @emph{gprbuild}.
19610This always takes precedence.
19611@end itemize
19612
19613This attribute is only taken into account in the main aggregate
19614project (i.e. the one specified on the command line to @emph{gprbuild}),
19615and ignored in other aggregate projects. It is invalid
19616in standard projects.
19617The goal is to have a consistent value in all
19618projects that are built through the aggregate, which would not
19619be the case in the diamond case: A groups the aggregate
19620projects B and C, which both (either directly or indirectly)
19621build the project P. If B and C could set different values for
19622the environment variables, we would have two different views of
19623P, which in particular might impact the list of source files in P.
19624@end quotation
19625
19626@node package Builder in aggregate projects,,Syntax of aggregate projects,Aggregate Projects
19627@anchor{gnat_ugn/gnat_project_manager package-builder-in-aggregate-projects}@anchor{18c}@anchor{gnat_ugn/gnat_project_manager id33}@anchor{18d}
19628@subsection package Builder in aggregate projects
19629
19630
19631As mentioned above, only the package Builder can be specified in
19632an aggregate project. In this package, only the following attributes
19633are valid:
19634
19635@geindex Switches (GNAT Project Manager)
19636
19637@strong{Switches}:
19638
19639@quotation
19640
19641This attribute gives the list of switches to use for @emph{gprbuild}.
19642Because no mains can be specified for aggregate projects, the only possible
19643index for attribute @cite{Switches} is @cite{others}. All other indexes will
19644be ignored.
19645
19646Example:
19647
19648@example
19649for Switches (others) use ("-v", "-k", "-j8");
19650@end example
19651
19652These switches are only read from the main aggregate project (the
19653one passed on the command line), and ignored in all other aggregate
19654projects or projects.
19655
19656It can only contain builder switches, not compiler switches.
19657@end quotation
19658
19659@geindex Global_Compilation_Switches (GNAT Project Manager)
19660
19661@strong{Global_Compilation_Switches}
19662
19663@quotation
19664
19665This attribute gives the list of compiler switches for the various
19666languages. For instance,
19667
19668@example
19669for Global_Compilation_Switches ("Ada") use ("O1", "-g");
19670for Global_Compilation_Switches ("C")   use ("-O2");
19671@end example
19672
19673This attribute is only taken into account in the aggregate project
19674specified on the command line, not in other aggregate projects.
19675
19676In the projects grouped by that aggregate, the attribute
19677Builder.Global_Compilation_Switches is also ignored. However, the
19678attribute Compiler.Default_Switches will be taken into account (but
19679that of the aggregate have higher priority). The attribute
19680Compiler.Switches is also taken into account and can be used to
19681override the switches for a specific file. As a result, it always
19682has priority.
19683
19684The rules are meant to avoid ambiguities when compiling. For
19685instance, aggregate project Agg groups the projects A and B, that
19686both depend on C. Here is an extra for all of these projects:
19687
19688@example
19689aggregate project Agg is
19690    for Project_Files use ("a.gpr", "b.gpr");
19691    package Builder is
19692       for Global_Compilation_Switches ("Ada") use ("-O2");
19693    end Builder;
19694end Agg;
19695
19696with "c.gpr";
19697project A is
19698    package Builder is
19699       for Global_Compilation_Switches ("Ada") use ("-O1");
19700       --  ignored
19701    end Builder;
19702
19703    package Compiler is
19704       for Default_Switches ("Ada")
19705           use ("-O1", "-g");
19706       for Switches ("a_file1.adb")
19707           use ("-O0");
19708    end Compiler;
19709end A;
19710
19711with "c.gpr";
19712project B is
19713    package Compiler is
19714       for Default_Switches ("Ada") use ("-O0");
19715    end Compiler;
19716end B;
19717
19718project C is
19719    package Compiler is
19720       for Default_Switches ("Ada")
19721           use ("-O3",
19722                "-gnatn");
19723       for Switches ("c_file1.adb")
19724           use ("-O0", "-g");
19725    end Compiler;
19726end C;
19727@end example
19728
19729then the following switches are used:
19730
19731
19732@itemize *
19733
19734@item 
19735all files from project A except a_file1.adb are compiled
19736with "-O2 -g", since the aggregate project has priority.
19737
19738@item 
19739the file a_file1.adb is compiled with
19740"-O0", since the Compiler.Switches has priority
19741
19742@item 
19743all files from project B are compiled with
19744"-O2", since the aggregate project has priority
19745
19746@item 
19747all files from C are compiled with "-O2 -gnatn", except for
19748c_file1.adb which is compiled with "-O0 -g"
19749@end itemize
19750
19751Even though C is seen through two paths (through A and through
19752B), the switches used by the compiler are unambiguous.
19753@end quotation
19754
19755@geindex Global_Configuration_Pragmas (GNAT Project Manager)
19756
19757@strong{Global_Configuration_Pragmas}
19758
19759@quotation
19760
19761This attribute can be used to specify a file containing
19762configuration pragmas, to be passed to the Ada compiler.  Since we
19763ignore the package Builder in other aggregate projects and projects,
19764only those pragmas defined in the main aggregate project will be
19765taken into account.
19766
19767Projects can locally add to those by using the
19768@cite{Compiler.Local_Configuration_Pragmas} attribute if they need.
19769@end quotation
19770
19771@geindex Global_Config_File (GNAT Project Manager)
19772
19773@strong{Global_Config_File}
19774
19775@quotation
19776
19777This attribute, indexed with a language name, can be used to specify a config
19778when compiling sources of the language. For Ada, these files are configuration
19779pragmas files.
19780@end quotation
19781
19782For projects that are built through the aggregate, the package Builder
19783is ignored, except for the Executable attribute which specifies the
19784name of the executables resulting from the link of the main programs, and
19785for the Executable_Suffix.
19786
19787@node Aggregate Library Projects,Project File Reference,Aggregate Projects,GNAT Project Manager
19788@anchor{gnat_ugn/gnat_project_manager id34}@anchor{18e}@anchor{gnat_ugn/gnat_project_manager aggregate-library-projects}@anchor{18f}
19789@section Aggregate Library Projects
19790
19791
19792Aggregate library projects make it possible to build a single library
19793using object files built using other standard or library
19794projects. This gives the flexibility to describe an application as
19795having multiple modules (a GUI, database access, ...) using different
19796project files (so possibly built with different compiler options) and
19797yet create a single library (static or relocatable) out of the
19798corresponding object files.
19799
19800@menu
19801* Building aggregate library projects:: 
19802* Syntax of aggregate library projects:: 
19803
19804@end menu
19805
19806@node Building aggregate library projects,Syntax of aggregate library projects,,Aggregate Library Projects
19807@anchor{gnat_ugn/gnat_project_manager building-aggregate-library-projects}@anchor{190}@anchor{gnat_ugn/gnat_project_manager id35}@anchor{191}
19808@subsection Building aggregate library projects
19809
19810
19811For example, we can define an aggregate project Agg that groups A, B
19812and C:
19813
19814@example
19815aggregate library project Agg is
19816   for Project_Files use ("a.gpr", "b.gpr", "c.gpr");
19817   for Library_Name use ("agg");
19818   for Library_Dir use ("lagg");
19819end Agg;
19820@end example
19821
19822Then, when you build with:
19823
19824@example
19825gprbuild agg.gpr
19826@end example
19827
19828This will build all units from projects A, B and C and will create a
19829static library named @code{libagg.a} in the @code{lagg}
19830directory. An aggregate library project has the same set of
19831restriction as a standard library project.
19832
19833Note that a shared aggregate library project cannot aggregate a
19834static library project. In platforms where a compiler option is
19835required to create relocatable object files, a Builder package in the
19836aggregate library project may be used:
19837
19838@example
19839aggregate library project Agg is
19840   for Project_Files use ("a.gpr", "b.gpr", "c.gpr");
19841   for Library_Name use ("agg");
19842   for Library_Dir use ("lagg");
19843   for Library_Kind use "relocatable";
19844
19845   package Builder is
19846      for Global_Compilation_Switches ("Ada") use ("-fPIC");
19847   end Builder;
19848end Agg;
19849@end example
19850
19851With the above aggregate library Builder package, the @cite{-fPIC}
19852option will be passed to the compiler when building any source code
19853from projects @code{a.gpr}, @code{b.gpr} and @code{c.gpr}.
19854
19855@node Syntax of aggregate library projects,,Building aggregate library projects,Aggregate Library Projects
19856@anchor{gnat_ugn/gnat_project_manager syntax-of-aggregate-library-projects}@anchor{192}@anchor{gnat_ugn/gnat_project_manager id36}@anchor{193}
19857@subsection Syntax of aggregate library projects
19858
19859
19860An aggregate library project follows the general syntax of project
19861files. The recommended extension is still @code{.gpr}. However, a special
19862@cite{aggregate library} qualifier must be put before the keyword
19863@cite{project}.
19864
19865An aggregate library project cannot @emph{with} any other project
19866(standard or aggregate), except an abstract project which can be used
19867to share attribute values.
19868
19869An aggregate library project does not have any source files directly (only
19870through other standard projects). Therefore a number of the standard
19871attributes and packages are forbidden in an aggregate library
19872project. Here is the (non exhaustive) list:
19873
19874
19875@itemize *
19876
19877@item 
19878Languages
19879
19880@item 
19881Source_Files, Source_List_File and other attributes dealing with
19882list of sources.
19883
19884@item 
19885Source_Dirs, Exec_Dir and Object_Dir
19886
19887@item 
19888Main
19889
19890@item 
19891Roots
19892
19893@item 
19894Externally_Built
19895
19896@item 
19897Inherit_Source_Path
19898
19899@item 
19900Excluded_Source_Dirs
19901
19902@item 
19903Locally_Removed_Files
19904
19905@item 
19906Excluded_Source_Files
19907
19908@item 
19909Excluded_Source_List_File
19910
19911@item 
19912Interfaces
19913@end itemize
19914
19915The only package that is authorized (albeit optional) is Builder.
19916
19917The Project_Files attribute (See @ref{16e,,Aggregate Projects}) is used to
19918described the aggregated projects whose object files have to be
19919included into the aggregate library. The environment variables
19920@cite{ADA_PROJECT_PATH}, @cite{GPR_PROJECT_PATH} and
19921@cite{GPR_PROJECT_PATH_FILE} are not used to find the project files.
19922
19923@node Project File Reference,,Aggregate Library Projects,GNAT Project Manager
19924@anchor{gnat_ugn/gnat_project_manager id37}@anchor{194}@anchor{gnat_ugn/gnat_project_manager project-file-reference}@anchor{14d}
19925@section Project File Reference
19926
19927
19928This section describes the syntactic structure of project files, the various
19929constructs that can be used. Finally, it ends with a summary of all available
19930attributes.
19931
19932@menu
19933* Project Declaration:: 
19934* Qualified Projects:: 
19935* Declarations:: 
19936* Packages:: 
19937* Expressions:: 
19938* External Values:: 
19939* Typed String Declaration:: 
19940* Variables:: 
19941* Case Constructions:: 
19942* Attributes:: 
19943
19944@end menu
19945
19946@node Project Declaration,Qualified Projects,,Project File Reference
19947@anchor{gnat_ugn/gnat_project_manager id38}@anchor{195}@anchor{gnat_ugn/gnat_project_manager project-declaration}@anchor{196}
19948@subsection Project Declaration
19949
19950
19951Project files have an Ada-like syntax. The minimal project file is:
19952
19953@example
19954project Empty is
19955end Empty;
19956@end example
19957
19958The identifier @cite{Empty} is the name of the project.
19959This project name must be present after the reserved
19960word @cite{end} at the end of the project file, followed by a semi-colon.
19961
19962@strong{Identifiers} (i.e., the user-defined names such as project or variable names)
19963have the same syntax as Ada identifiers: they must start with a letter,
19964and be followed by zero or more letters, digits or underscore characters;
19965it is also illegal to have two underscores next to each other. Identifiers
19966are always case-insensitive ("Name" is the same as "name").
19967
19968@example
19969simple_name ::= identifier
19970name        ::= simple_name @{ . simple_name @}
19971@end example
19972
19973@strong{Strings} are used for values of attributes or as indexes for these
19974attributes. They are in general case sensitive, except when noted
19975otherwise (in particular, strings representing file names will be case
19976insensitive on some systems, so that "file.adb" and "File.adb" both
19977represent the same file).
19978
19979@strong{Reserved words} are the same as for standard Ada 95, and cannot
19980be used for identifiers. In particular, the following words are currently
19981used in project files, but others could be added later on. In bold are the
19982extra reserved words in project files:
19983@code{all}, @code{at}, @code{case}, @code{end}, @code{for}, @code{is}, @code{limited},
19984@code{null}, @code{others}, @code{package}, @code{renames}, @code{type}, @code{use}, @code{when},
19985@code{with}, @strong{extends}, @strong{external}, @strong{project}.
19986
19987@strong{Comments} in project files have the same syntax as in Ada, two consecutive
19988hyphens through the end of the line.
19989
19990A project may be an @strong{independent project}, entirely defined by a single
19991project file. Any source file in an independent project depends only
19992on the predefined library and other source files in the same project.
19993But a project may also depend on other projects, either by importing them
19994through @strong{with clauses}, or by @strong{extending} at most one other project. Both
19995types of dependency can be used in the same project.
19996
19997A path name denotes a project file. It can be absolute or relative.
19998An absolute path name includes a sequence of directories, in the syntax of
19999the host operating system, that identifies uniquely the project file in the
20000file system. A relative path name identifies the project file, relative
20001to the directory that contains the current project, or relative to a
20002directory listed in the environment variables ADA_PROJECT_PATH and
20003GPR_PROJECT_PATH. Path names are case sensitive if file names in the host
20004operating system are case sensitive. As a special case, the directory
20005separator can always be "/" even on Windows systems, so that project files
20006can be made portable across architectures.
20007The syntax of the environment variables ADA_PROJECT_PATH and
20008GPR_PROJECT_PATH is a list of directory names separated by colons on UNIX and
20009semicolons on Windows.
20010
20011A given project name can appear only once in a context clause.
20012
20013It is illegal for a project imported by a context clause to refer, directly
20014or indirectly, to the project in which this context clause appears (the
20015dependency graph cannot contain cycles), except when one of the with clauses
20016in the cycle is a @strong{limited with}.
20017
20018@example
20019with "other_project.gpr";
20020project My_Project extends "extended.gpr" is
20021end My_Project;
20022@end example
20023
20024These dependencies form a @strong{directed graph}, potentially cyclic when using
20025@strong{limited with}. The subgraph reflecting the @strong{extends} relations is a tree.
20026
20027A project's @strong{immediate sources} are the source files directly defined by
20028that project, either implicitly by residing in the project source directories,
20029or explicitly through any of the source-related attributes.
20030More generally, a project's @strong{sources} are the immediate sources of the
20031project together with the immediate sources (unless overridden) of any project
20032on which it depends directly or indirectly.
20033
20034A @strong{project hierarchy} can be created, where projects are children of
20035other projects. The name of such a child project must be @cite{Parent.Child},
20036where @cite{Parent} is the name of the parent project. In particular, this
20037makes all @emph{with} clauses of the parent project automatically visible
20038in the child project.
20039
20040@example
20041project        ::= context_clause project_declaration
20042
20043context_clause ::= @{with_clause@}
20044with_clause    ::= *with* path_name @{ , path_name @} ;
20045path_name      ::= string_literal
20046
20047project_declaration ::= simple_project_declaration | project_extension
20048simple_project_declaration ::=
20049  project <project_>name is
20050    @{declarative_item@}
20051  end <project_>simple_name;
20052@end example
20053
20054@node Qualified Projects,Declarations,Project Declaration,Project File Reference
20055@anchor{gnat_ugn/gnat_project_manager qualified-projects}@anchor{173}@anchor{gnat_ugn/gnat_project_manager id39}@anchor{197}
20056@subsection Qualified Projects
20057
20058
20059Before the reserved @cite{project}, there may be one or two @strong{qualifiers}, that
20060is identifiers or reserved words, to qualify the project.
20061The current list of qualifiers is:
20062
20063
20064@table @asis
20065
20066@item @strong{abstract}:
20067
20068Qualifies a project with no sources.
20069Such a   project must either have no declaration of attributes @cite{Source_Dirs},
20070@cite{Source_Files}, @cite{Languages} or @cite{Source_List_File}, or one of
20071@cite{Source_Dirs}, @cite{Source_Files}, or @cite{Languages} must be declared
20072as empty. If it extends another project, the project it extends must also be a
20073qualified abstract project.
20074
20075@item @strong{standard}:
20076
20077A standard project is a non library project with sources.
20078This is the default (implicit) qualifier.
20079
20080@item @strong{aggregate}:
20081
20082A project whose sources are aggregated from other project files.
20083
20084@item @strong{aggregate library}:
20085
20086A library whose sources are aggregated from other project
20087or library project files.
20088
20089@item @strong{library}:
20090
20091A library project must declare both attributes
20092Library_Name` and @cite{Library_Dir}.
20093
20094@item @strong{configuration}:
20095
20096A configuration project cannot be in a project tree.
20097It describes compilers and other tools to @emph{gprbuild}.
20098@end table
20099
20100@node Declarations,Packages,Qualified Projects,Project File Reference
20101@anchor{gnat_ugn/gnat_project_manager declarations}@anchor{198}@anchor{gnat_ugn/gnat_project_manager id40}@anchor{199}
20102@subsection Declarations
20103
20104
20105Declarations introduce new entities that denote types, variables, attributes,
20106and packages. Some declarations can only appear immediately within a project
20107declaration. Others can appear within a project or within a package.
20108
20109@example
20110declarative_item ::= simple_declarative_item
20111  | typed_string_declaration
20112  | package_declaration
20113
20114simple_declarative_item ::= variable_declaration
20115  | typed_variable_declaration
20116  | attribute_declaration
20117  | case_construction
20118  | empty_declaration
20119
20120empty_declaration ::= *null* ;
20121@end example
20122
20123An empty declaration is allowed anywhere a declaration is allowed. It has
20124no effect.
20125
20126@node Packages,Expressions,Declarations,Project File Reference
20127@anchor{gnat_ugn/gnat_project_manager packages}@anchor{153}@anchor{gnat_ugn/gnat_project_manager id41}@anchor{19a}
20128@subsection Packages
20129
20130
20131A project file may contain @strong{packages}, that group attributes (typically
20132all the attributes that are used by one of the GNAT tools).
20133
20134A package with a given name may only appear once in a project file.
20135The following packages are currently supported in project files
20136(See @ref{152,,Attributes} for the list of attributes that each can contain).
20137
20138
20139@table @asis
20140
20141@item @emph{Binder}
20142
20143This package specifies characteristics useful when invoking the binder either
20144directly via the @emph{gnat} driver or when using a builder such as
20145@emph{gnatmake} or @emph{gprbuild}. See @ref{15d,,Main Subprograms}.
20146
20147@item @emph{Builder}
20148
20149This package specifies the compilation options used when building an
20150executable or a library for a project. Most of the options should be
20151set in one of @cite{Compiler}, @cite{Binder} or @cite{Linker} packages,
20152but there are some general options that should be defined in this
20153package. See @ref{15d,,Main Subprograms}, and @ref{162,,Executable File Names} in
20154particular.
20155@end table
20156
20157
20158
20159@table @asis
20160
20161@item @emph{Clean}
20162
20163This package specifies the options used when cleaning a project or a project
20164tree using the tools @emph{gnatclean} or @emph{gprclean}.
20165
20166@item @emph{Compiler}
20167
20168This package specifies the compilation options used by the compiler for
20169each languages. See @ref{15e,,Tools Options in Project Files}.
20170
20171@item @emph{Cross_Reference}
20172
20173This package specifies the options used when calling the library tool
20174@emph{gnatxref} via the @emph{gnat} driver. Its attributes
20175@strong{Default_Switches} and @strong{Switches} have the same semantics as for the
20176package @cite{Builder}.
20177@end table
20178
20179
20180
20181@table @asis
20182
20183@item @emph{Finder}
20184
20185This package specifies the options used when calling the search tool
20186@emph{gnatfind} via the @emph{gnat} driver. Its attributes
20187@strong{Default_Switches} and @strong{Switches} have the same semantics as for the
20188package @cite{Builder}.
20189
20190@item @emph{Gnatls}
20191
20192This package specifies the options to use when invoking @emph{gnatls}
20193via the @emph{gnat} driver.
20194@end table
20195
20196
20197
20198@table @asis
20199
20200@item @emph{IDE}
20201
20202This package specifies the options used when starting an integrated
20203development environment, for instance @emph{GPS} or @emph{Gnatbench}.
20204
20205@item @emph{Install}
20206
20207This package specifies the options used when installing a project
20208with @emph{gprinstall}. See @ref{168,,Installation}.
20209
20210@item @emph{Linker}
20211
20212This package specifies the options used by the linker.
20213See @ref{15d,,Main Subprograms}.
20214@end table
20215
20216
20217
20218@table @asis
20219
20220@item @emph{Naming}
20221
20222@quotation
20223
20224This package specifies the naming conventions that apply
20225to the source files in a project. In particular, these conventions are
20226used to automatically find all source files in the source directories,
20227or given a file name to find out its language for proper processing.
20228See @ref{14b,,Naming Schemes}.
20229@end quotation
20230
20231@c only: PRO or GPL
20232@c 
20233@c *Pretty_Printer*
20234@c   This package specifies the options used when calling the formatting tool
20235@c   *gnatpp* via the *gnat* driver. Its attributes
20236@c   **Default_Switches** and **Switches** have the same semantics as for the
20237@c   package `Builder`.
20238
20239@item @emph{Remote}
20240
20241This package is used by @emph{gprbuild} to describe how distributed
20242compilation should be done.
20243
20244@item @emph{Stack}
20245
20246This package specifies the options used when calling the tool
20247@emph{gnatstack} via the @emph{gnat} driver. Its attributes
20248@strong{Default_Switches} and @strong{Switches} have the same semantics as for the
20249package @cite{Builder}.
20250
20251@item @emph{Synchronize}
20252
20253This package specifies the options used when calling the tool
20254@emph{gnatsync} via the @emph{gnat} driver.
20255@end table
20256
20257In its simplest form, a package may be empty:
20258
20259@example
20260project Simple is
20261  package Builder is
20262  end Builder;
20263end Simple;
20264@end example
20265
20266A package may contain @strong{attribute declarations},
20267@strong{variable declarations} and @strong{case constructions}, as will be
20268described below.
20269
20270When there is ambiguity between a project name and a package name,
20271the name always designates the project. To avoid possible confusion, it is
20272always a good idea to avoid naming a project with one of the
20273names allowed for packages or any name that starts with @cite{gnat}.
20274
20275A package can also be defined by a @strong{renaming declaration}. The new package
20276renames a package declared in a different project file, and has the same
20277attributes as the package it renames. The name of the renamed package
20278must be the same as the name of the renaming package. The project must
20279contain a package declaration with this name, and the project
20280must appear in the context clause of the current project, or be its parent
20281project. It is not possible to add or override attributes to the renaming
20282project. If you need to do so, you should use an @strong{extending declaration}
20283(see below).
20284
20285Packages that are renamed in other project files often come from project files
20286that have no sources: they are just used as templates. Any modification in the
20287template will be reflected automatically in all the project files that rename
20288a package from the template. This is a very common way to share settings
20289between projects.
20290
20291Finally, a package can also be defined by an @strong{extending declaration}. This is
20292similar to a @strong{renaming declaration}, except that it is possible to add or
20293override attributes.
20294
20295@example
20296package_declaration ::= package_spec | package_renaming | package_extension
20297package_spec ::=
20298  package <package_>simple_name is
20299    @{simple_declarative_item@}
20300  end package_identifier ;
20301package_renaming ::==
20302  package <package_>simple_name renames <project_>simple_name.package_identifier ;
20303package_extension ::==
20304  package <package_>simple_name extends <project_>simple_name.package_identifier is
20305    @{simple_declarative_item@}
20306  end package_identifier ;
20307@end example
20308
20309@node Expressions,External Values,Packages,Project File Reference
20310@anchor{gnat_ugn/gnat_project_manager expressions}@anchor{19b}@anchor{gnat_ugn/gnat_project_manager id42}@anchor{19c}
20311@subsection Expressions
20312
20313
20314An expression is any value that can be assigned to an attribute or a
20315variable. It is either a literal value, or a construct requiring runtime
20316computation by the project manager. In a project file, the computed value of
20317an expression is either a string or a list of strings.
20318
20319A string value is one of:
20320
20321
20322@itemize *
20323
20324@item 
20325A literal string, for instance @cite{"comm/my_proj.gpr"}
20326
20327@item 
20328The name of a variable that evaluates to a string (see @ref{155,,Variables})
20329
20330@item 
20331The name of an attribute that evaluates to a string (see @ref{152,,Attributes})
20332
20333@item 
20334An external reference (see @ref{154,,External Values})
20335
20336@item 
20337A concatenation of the above, as in @cite{"prefix_" & Var}.
20338@end itemize
20339
20340A list of strings is one of the following:
20341
20342
20343@itemize *
20344
20345@item 
20346A parenthesized comma-separated list of zero or more string expressions, for
20347instance @cite{(File_Name@comma{} "gnat.adc"@comma{} File_Name & ".orig")} or @cite{()}.
20348
20349@item 
20350The name of a variable that evaluates to a list of strings
20351
20352@item 
20353The name of an attribute that evaluates to a list of strings
20354
20355@item 
20356A concatenation of a list of strings and a string (as defined above), for
20357instance @cite{("A"@comma{} "B") & "C"}
20358
20359@item 
20360A concatenation of two lists of strings
20361@end itemize
20362
20363The following is the grammar for expressions
20364
20365@example
20366string_literal ::= "@{string_element@}"  --  Same as Ada
20367string_expression ::= string_literal
20368    | *variable_*name
20369    | external_value
20370    | attribute_reference
20371    | ( string_expression @{ & string_expression @} )
20372string_list  ::= ( string_expression @{ , string_expression @} )
20373   | *string_variable*_name
20374   | *string_*attribute_reference
20375term ::= string_expression | string_list
20376expression ::= term @{ & term @}     --  Concatenation
20377@end example
20378
20379Concatenation involves strings and list of strings. As soon as a list of
20380strings is involved, the result of the concatenation is a list of strings. The
20381following Ada declarations show the existing operators:
20382
20383@example
20384function "&" (X : String;      Y : String)      return String;
20385function "&" (X : String_List; Y : String)      return String_List;
20386function "&" (X : String_List; Y : String_List) return String_List;
20387@end example
20388
20389Here are some specific examples:
20390
20391@example
20392List := () & File_Name; --  One string in this list
20393List2 := List & (File_Name & ".orig"); -- Two strings
20394Big_List := List & Lists2;  --  Three strings
20395Illegal := "gnat.adc" & List2;  --  Illegal, must start with list
20396@end example
20397
20398@node External Values,Typed String Declaration,Expressions,Project File Reference
20399@anchor{gnat_ugn/gnat_project_manager external-values}@anchor{154}@anchor{gnat_ugn/gnat_project_manager id43}@anchor{19d}
20400@subsection External Values
20401
20402
20403An external value is an expression whose value is obtained from the command
20404that invoked the processing of the current project file (typically a
20405@emph{gnatmake} or @emph{gprbuild} command).
20406
20407There are two kinds of external values, one that returns a single string, and
20408one that returns a string list.
20409
20410The syntax of a single string external value is:
20411
20412@example
20413external_value ::= *external* ( string_literal [, string_literal] )
20414@end example
20415
20416The first string_literal is the string to be used on the command line or
20417in the environment to specify the external value. The second string_literal,
20418if present, is the default to use if there is no specification for this
20419external value either on the command line or in the environment.
20420
20421Typically, the external value will either exist in the
20422environment variables
20423or be specified on the command line through the
20424@code{-X@emph{vbl}=@emph{value}} switch. If both
20425are specified, then the command line value is used, so that a user can more
20426easily override the value.
20427
20428The function @cite{external} always returns a string. It is an error if the
20429value was not found in the environment and no default was specified in the
20430call to @cite{external}.
20431
20432An external reference may be part of a string expression or of a string
20433list expression, and can therefore appear in a variable declaration or
20434an attribute declaration.
20435
20436Most of the time, this construct is used to initialize typed variables, which
20437are then used in @strong{case} constructions to control the value assigned to
20438attributes in various scenarios. Thus such variables are often called
20439@strong{scenario variables}.
20440
20441The syntax for a string list external value is:
20442
20443@example
20444external_value ::= *external_as_list* ( string_literal , string_literal )
20445@end example
20446
20447The first string_literal is the string to be used on the command line or
20448in the environment to specify the external value. The second string_literal is
20449the separator between each component of the string list.
20450
20451If the external value does not exist in the environment or on the command line,
20452the result is an empty list. This is also the case, if the separator is an
20453empty string or if the external value is only one separator.
20454
20455Any separator at the beginning or at the end of the external value is
20456discarded. Then, if there is no separator in the external value, the result is
20457a string list with only one string. Otherwise, any string between the beginning
20458and the first separator, between two consecutive separators and between the
20459last separator and the end are components of the string list.
20460
20461@example
20462*external_as_list* ("SWITCHES", ",")
20463@end example
20464
20465If the external value is "-O2,-g",
20466the result is ("-O2", "-g").
20467
20468If the external value is ",-O2,-g,",
20469the result is also ("-O2", "-g").
20470
20471if the external value is "-gnatv",
20472the result is ("-gnatv").
20473
20474If the external value is ",,", the result is ("").
20475
20476If the external value is ",", the result is (), the empty string list.
20477
20478@node Typed String Declaration,Variables,External Values,Project File Reference
20479@anchor{gnat_ugn/gnat_project_manager id44}@anchor{19e}@anchor{gnat_ugn/gnat_project_manager typed-string-declaration}@anchor{19f}
20480@subsection Typed String Declaration
20481
20482
20483A @strong{type declaration} introduces a discrete set of string literals.
20484If a string variable is declared to have this type, its value
20485is restricted to the given set of literals. These are the only named
20486types in project files. A string type may only be declared at the project
20487level, not inside a package.
20488
20489@example
20490typed_string_declaration ::=
20491  *type* *<typed_string_>*_simple_name *is* ( string_literal @{, string_literal@} );
20492@end example
20493
20494The string literals in the list are case sensitive and must all be different.
20495They may include any graphic characters allowed in Ada, including spaces.
20496Here is an example of a string type declaration:
20497
20498@example
20499type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
20500@end example
20501
20502Variables of a string type are called @strong{typed variables}; all other
20503variables are called @strong{untyped variables}. Typed variables are
20504particularly useful in @cite{case} constructions, to support conditional
20505attribute declarations. (See @ref{1a0,,Case Constructions}).
20506
20507A string type may be referenced by its name if it has been declared in the same
20508project file, or by an expanded name whose prefix is the name of the project
20509in which it is declared.
20510
20511@node Variables,Case Constructions,Typed String Declaration,Project File Reference
20512@anchor{gnat_ugn/gnat_project_manager variables}@anchor{155}@anchor{gnat_ugn/gnat_project_manager id45}@anchor{1a1}
20513@subsection Variables
20514
20515
20516@strong{Variables} store values (strings or list of strings) and can appear
20517as part of an expression. The declaration of a variable creates the
20518variable and assigns the value of the expression to it. The name of the
20519variable is available immediately after the assignment symbol, if you
20520need to reuse its old value to compute the new value. Before the completion
20521of its first declaration, the value of a variable defaults to the empty
20522string ("").
20523
20524A @strong{typed} variable can be used as part of a @strong{case} expression to
20525compute the value, but it can only be declared once in the project file,
20526so that all case constructions see the same value for the variable. This
20527provides more consistency and makes the project easier to understand.
20528The syntax for its declaration is identical to the Ada syntax for an
20529object declaration. In effect, a typed variable acts as a constant.
20530
20531An @strong{untyped} variable can be declared and overridden multiple times
20532within the same project. It is declared implicitly through an Ada
20533assignment. The first declaration establishes the kind of the variable
20534(string or list of strings) and successive declarations must respect
20535the initial kind. Assignments are executed in the order in which they
20536appear, so the new value replaces the old one and any subsequent reference
20537to the variable uses the new value.
20538
20539A variable may be declared at the project file level, or within a package.
20540
20541@example
20542typed_variable_declaration ::=
20543  *<typed_variable_>*simple_name : *<typed_string_>*name := string_expression;
20544
20545variable_declaration ::= *<variable_>*simple_name := expression;
20546@end example
20547
20548Here are some examples of variable declarations:
20549
20550@example
20551This_OS : OS := external ("OS"); --  a typed variable declaration
20552That_OS := "GNU/Linux";          --  an untyped variable declaration
20553
20554Name      := "readme.txt";
20555Save_Name := Name & ".saved";
20556
20557Empty_List := ();
20558List_With_One_Element := ("-gnaty");
20559List_With_Two_Elements := List_With_One_Element & "-gnatg";
20560Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada");
20561@end example
20562
20563A @strong{variable reference} may take several forms:
20564
20565
20566@itemize *
20567
20568@item 
20569The simple variable name, for a variable in the current package (if any)
20570or in the current project
20571
20572@item 
20573An expanded name, whose prefix is a context name.
20574@end itemize
20575
20576A @strong{context} may be one of the following:
20577
20578
20579@itemize *
20580
20581@item 
20582The name of an existing package in the current project
20583
20584@item 
20585The name of an imported project of the current project
20586
20587@item 
20588The name of an ancestor project (i.e., a project extended by the current
20589project, either directly or indirectly)
20590
20591@item 
20592An expanded name whose prefix is an imported/parent project name, and
20593whose selector is a package name in that project.
20594@end itemize
20595
20596@node Case Constructions,Attributes,Variables,Project File Reference
20597@anchor{gnat_ugn/gnat_project_manager id46}@anchor{1a2}@anchor{gnat_ugn/gnat_project_manager case-constructions}@anchor{1a0}
20598@subsection Case Constructions
20599
20600
20601A @strong{case} construction is used in a project file to effect conditional
20602behavior. Through this construction, you can set the value of attributes
20603and variables depending on the value previously assigned to a typed
20604variable.
20605
20606All choices in a choice list must be distinct. Unlike Ada, the choice
20607lists of all alternatives do not need to include all values of the type.
20608An @cite{others} choice must appear last in the list of alternatives.
20609
20610The syntax of a @cite{case} construction is based on the Ada case construction
20611(although the @cite{null} declaration for empty alternatives is optional).
20612
20613The case expression must be a string variable, either typed or not, whose value
20614is often given by an external reference (see @ref{154,,External Values}).
20615
20616Each alternative starts with the reserved word @cite{when}, either a list of
20617literal strings separated by the @cite{"|"} character or the reserved word
20618@cite{others}, and the @cite{"=>"} token.
20619When the case expression is a typed string variable, each literal string must
20620belong to the string type that is the type of the case variable.
20621After each @cite{=>}, there are zero or more declarations.  The only
20622declarations allowed in a case construction are other case constructions,
20623attribute declarations and variable declarations. String type declarations and
20624package declarations are not allowed. Variable declarations are restricted to
20625variables that have already been declared before the case construction.
20626
20627@example
20628case_construction ::=
20629  *case* *<variable_>*name *is* @{case_item@} *end case* ;
20630
20631case_item ::=
20632  *when* discrete_choice_list =>
20633    @{case_declaration
20634      | attribute_declaration
20635      | variable_declaration
20636      | empty_declaration@}
20637
20638discrete_choice_list ::= string_literal @{| string_literal@} | *others*
20639@end example
20640
20641Here is a typical example, with a typed string variable:
20642
20643@example
20644project MyProj is
20645   type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
20646   OS : OS_Type := external ("OS", "GNU/Linux");
20647
20648   package Compiler is
20649     case OS is
20650       when "GNU/Linux" | "Unix" =>
20651         for Switches ("Ada")
20652             use ("-gnath");
20653       when "NT" =>
20654         for Switches ("Ada")
20655             use ("-gnatP");
20656       when others =>
20657         null;
20658     end case;
20659   end Compiler;
20660end MyProj;
20661@end example
20662
20663@node Attributes,,Case Constructions,Project File Reference
20664@anchor{gnat_ugn/gnat_project_manager id47}@anchor{1a3}@anchor{gnat_ugn/gnat_project_manager attributes}@anchor{152}
20665@subsection Attributes
20666
20667
20668A project (and its packages) may have @strong{attributes} that define
20669the project's properties.  Some attributes have values that are strings;
20670others have values that are string lists.
20671
20672@example
20673attribute_declaration ::=
20674   simple_attribute_declaration | indexed_attribute_declaration
20675
20676simple_attribute_declaration ::= *for* attribute_designator *use* expression ;
20677
20678indexed_attribute_declaration ::=
20679  *for* *<indexed_attribute_>*simple_name ( string_literal) *use* expression ;
20680
20681attribute_designator ::=
20682  *<simple_attribute_>*simple_name
20683  | *<indexed_attribute_>*simple_name ( string_literal )
20684@end example
20685
20686There are two categories of attributes: @strong{simple attributes}
20687and @strong{indexed attributes}.
20688Each simple attribute has a default value: the empty string (for string
20689attributes) and the empty list (for string list attributes).
20690An attribute declaration defines a new value for an attribute, and overrides
20691the previous value. The syntax of a simple attribute declaration is similar to
20692that of an attribute definition clause in Ada.
20693
20694Some attributes are indexed. These attributes are mappings whose
20695domain is a set of strings. They are declared one association
20696at a time, by specifying a point in the domain and the corresponding image
20697of the attribute.
20698Like untyped variables and simple attributes, indexed attributes
20699may be declared several times. Each declaration supplies a new value for the
20700attribute, and replaces the previous setting.
20701
20702Here are some examples of attribute declarations:
20703
20704@example
20705--  simple attributes
20706for Object_Dir use "objects";
20707for Source_Dirs use ("units", "test/drivers");
20708
20709--  indexed attributes
20710for Body ("main") use "Main.ada";
20711for Switches ("main.ada")
20712    use ("-v", "-gnatv");
20713for Switches ("main.ada") use Builder'Switches ("main.ada") & "-g";
20714
20715--  indexed attributes copy (from package Builder in project Default)
20716--  The package name must always be specified, even if it is the current
20717--  package.
20718for Default_Switches use Default.Builder'Default_Switches;
20719@end example
20720
20721Attributes references may appear anywhere in expressions, and are used
20722to retrieve the value previously assigned to the attribute. If an attribute
20723has not been set in a given package or project, its value defaults to the
20724empty string or the empty list, with some exceptions.
20725
20726@example
20727attribute_reference ::=
20728  attribute_prefix ' *<simple_attribute>_*simple_name [ (string_literal) ]
20729attribute_prefix ::= *project*
20730  | *<project_>*simple_name
20731  | package_identifier
20732  | *<project_>*simple_name . package_identifier
20733@end example
20734
20735Examples are:
20736
20737@example
20738<project>'Object_Dir
20739Naming'Dot_Replacement
20740Imported_Project'Source_Dirs
20741Imported_Project.Naming'Casing
20742Builder'Default_Switches ("Ada")
20743@end example
20744
20745The exceptions to the empty defaults are:
20746
20747
20748@itemize *
20749
20750@item 
20751Object_Dir: default is "."
20752
20753@item 
20754Exec_Dir: default is 'Object_Dir, that is the value of attribute
20755Object_Dir in the same project, declared or defaulted.
20756
20757@item 
20758Source_Dirs: default is (".")
20759@end itemize
20760
20761The prefix of an attribute may be:
20762
20763
20764@itemize *
20765
20766@item 
20767@cite{project} for an attribute of the current project
20768
20769@item 
20770The name of an existing package of the current project
20771
20772@item 
20773The name of an imported project
20774
20775@item 
20776The name of a parent project that is extended by the current project
20777
20778@item 
20779An expanded name whose prefix is imported/parent project name,
20780and whose selector is a package name
20781@end itemize
20782
20783In the following sections, all predefined attributes are succinctly described,
20784first the project level attributes, that is those attributes that are not in a
20785package, then the attributes in the different packages.
20786
20787It is possible for different tools to dynamically create new packages with
20788attributes, or new attributes in predefined packages. These attributes are
20789not documented here.
20790
20791The attributes under Configuration headings are usually found only in
20792configuration project files.
20793
20794The characteristics of each attribute are indicated as follows:
20795
20796
20797@itemize *
20798
20799@item 
20800@strong{Type of value}
20801
20802The value of an attribute may be a single string, indicated by the word
20803"single", or a string list, indicated by the word "list".
20804
20805@item 
20806@strong{Read-only}
20807
20808When the attribute is read-only, that is when it is not allowed to declare
20809the attribute, this is indicated by the words "read-only".
20810
20811@item 
20812@strong{Optional index}
20813
20814If it is allowed in the value of the attribute (both single and list) to have
20815an optional index, this is indicated by the words "optional index".
20816
20817@item 
20818@strong{Indexed attribute}
20819
20820When it is an indexed attribute, this is indicated by the word "indexed".
20821
20822@item 
20823@strong{Case-sensitivity of the index}
20824
20825For an indexed attribute, if the index is case-insensitive, this is indicated
20826by the words "case-insensitive index".
20827
20828@item 
20829@strong{File name index}
20830
20831For an indexed attribute, when the index is a file name, this is indicated by
20832the words "file name index". The index may or may not be case-sensitive,
20833depending on the platform.
20834
20835@item 
20836@strong{others allowed in index}
20837
20838For an indexed attribute, if it is allowed to use @strong{others} as the index,
20839this is indicated by the words "others allowed".
20840
20841When @strong{others} is used as the index of an indexed attribute, the value of
20842the attribute indexed by @strong{others} is used when no other index would apply.
20843@end itemize
20844
20845@menu
20846* Project Level Attributes:: 
20847* Package Binder Attributes:: 
20848* Package Builder Attributes:: 
20849* Package Clean Attributes:: 
20850* Package Compiler Attributes:: 
20851* Package Cross_Reference Attributes:: 
20852* Package Finder Attributes:: 
20853* Package gnatls Attributes:: 
20854* Package IDE Attributes:: 
20855* Package Install Attributes:: 
20856* Package Linker Attributes:: 
20857* Package Naming Attributes:: 
20858* Package Remote Attributes:: 
20859* Package Stack Attributes:: 
20860* Package Synchronize Attributes:: 
20861
20862@end menu
20863
20864@node Project Level Attributes,Package Binder Attributes,,Attributes
20865@anchor{gnat_ugn/gnat_project_manager project-level-attributes}@anchor{1a4}@anchor{gnat_ugn/gnat_project_manager id48}@anchor{1a5}
20866@subsubsection Project Level Attributes
20867
20868
20869
20870@itemize *
20871
20872@item 
20873@strong{General}
20874
20875
20876@itemize *
20877
20878@item 
20879@strong{Name}: single, read-only
20880
20881The name of the project.
20882
20883@item 
20884@strong{Project_Dir}: single, read-only
20885
20886The path name of the project directory.
20887
20888@item 
20889@strong{Main}: list, optional index
20890
20891The list of main sources for the executables.
20892
20893@item 
20894@strong{Languages}: list
20895
20896The list of languages of the sources of the project.
20897
20898@item 
20899@strong{Roots}: list, indexed, file name index
20900
20901The index is the file name of an executable source. Indicates the list of units
20902from the main project that need to be bound and linked with their closures
20903with the executable. The index is either a file name, a language name or "*".
20904The roots for an executable source are those in @strong{Roots} with an index that
20905is the executable source file name, if declared. Otherwise, they are those in
20906@strong{Roots} with an index that is the language name of the executable source,
20907if present. Otherwise, they are those in @strong{Roots ("*")}, if declared. If none
20908of these three possibilities are declared, then there are no roots for the
20909executable source.
20910
20911@item 
20912@strong{Externally_Built}: single
20913
20914Indicates if the project is externally built.
20915Only case-insensitive values allowed are "true" and "false", the default.
20916@end itemize
20917
20918@item 
20919@strong{Directories}
20920
20921
20922@itemize *
20923
20924@item 
20925@strong{Object_Dir}: single
20926
20927Indicates the object directory for the project.
20928
20929@item 
20930@strong{Exec_Dir}: single
20931
20932Indicates the exec directory for the project, that is the directory where the
20933executables are.
20934
20935@item 
20936@strong{Source_Dirs}: list
20937
20938The list of source directories of the project.
20939
20940@item 
20941@strong{Inherit_Source_Path}: list, indexed, case-insensitive index
20942
20943Index is a language name. Value is a list of language names. Indicates that
20944in the source search path of the index language the source directories of
20945the languages in the list should be included.
20946
20947Example:
20948
20949@example
20950for Inherit_Source_Path ("C++") use ("C");
20951@end example
20952
20953@item 
20954@strong{Exclude_Source_Dirs}: list
20955
20956The list of directories that are included in Source_Dirs but are not source
20957directories of the project.
20958
20959@item 
20960@strong{Ignore_Source_Sub_Dirs}: list
20961
20962Value is a list of simple names for subdirectories that are removed from the
20963list of source directories, including theur subdirectories.
20964@end itemize
20965
20966@item 
20967@strong{Source Files}
20968
20969
20970@itemize *
20971
20972@item 
20973@strong{Source_Files}: list
20974
20975Value is a list of source file simple names.
20976
20977@item 
20978@strong{Locally_Removed_Files}: list
20979
20980Obsolescent. Equivalent to Excluded_Source_Files.
20981
20982@item 
20983@strong{Excluded_Source_Files}: list
20984
20985Value is a list of simple file names that are not sources of the project.
20986Allows to remove sources that are inherited or found in the source directories
20987and that match the naming scheme.
20988
20989@item 
20990@strong{Source_List_File}: single
20991
20992Value is a text file name that contains a list of source file simple names,
20993one on each line.
20994
20995@item 
20996@strong{Excluded_Source_List_File}: single
20997
20998Value is a text file name that contains a list of file simple names that
20999are not sources of the project.
21000
21001@item 
21002@strong{Interfaces}: list
21003
21004Value is a list of file names that constitutes the interfaces of the project.
21005@end itemize
21006
21007@item 
21008@strong{Aggregate Projects}
21009
21010
21011@itemize *
21012
21013@item 
21014@strong{Project_Files}: list
21015
21016Value is the list of aggregated projects.
21017
21018@item 
21019@strong{Project_Path}: list
21020
21021Value is a list of directories that are added to the project search path when
21022looking for the aggregated projects.
21023
21024@item 
21025@strong{External}: single, indexed
21026
21027Index is the name of an external reference. Value is the value of the
21028external reference to be used when parsing the aggregated projects.
21029@end itemize
21030
21031@item 
21032@strong{Libraries}
21033
21034
21035@itemize *
21036
21037@item 
21038@strong{Library_Dir}: single
21039
21040Value is the name of the library directory. This attribute needs to be
21041declared for each library project.
21042
21043@item 
21044@strong{Library_Name}: single
21045
21046Value is the name of the library. This attribute needs to be declared or
21047inherited for each library project.
21048
21049@item 
21050@strong{Library_Kind}: single
21051
21052Specifies the kind of library: static library (archive) or shared library.
21053Case-insensitive values must be one of "static" for archives (the default) or
21054"dynamic" or "relocatable" for shared libraries.
21055
21056@item 
21057@strong{Library_Version}: single
21058
21059Value is the name of the library file.
21060
21061@item 
21062@strong{Library_Interface}: list
21063
21064Value is the list of unit names that constitutes the interfaces
21065of a Stand-Alone Library project.
21066
21067@item 
21068@strong{Library_Standalone}: single
21069
21070Specifies if a Stand-Alone Library (SAL) is encapsulated or not.
21071Only authorized case-insensitive values are "standard" for non encapsulated
21072SALs, "encapsulated" for encapsulated SALs or "no" for non SAL library project.
21073
21074@item 
21075@strong{Library_Encapsulated_Options}: list
21076
21077Value is a list of options that need to be used when linking an encapsulated
21078Stand-Alone Library.
21079
21080@item 
21081@strong{Library_Encapsulated_Supported}: single
21082
21083Indicates if encapsulated Stand-Alone Libraries are supported. Only
21084authorized case-insensitive values are "true" and "false" (the default).
21085
21086@item 
21087@strong{Library_Auto_Init}: single
21088
21089Indicates if a Stand-Alone Library is auto-initialized. Only authorized
21090case-insentive values are "true" and "false".
21091
21092@item 
21093@strong{Leading_Library_Options}: list
21094
21095Value is a list of options that are to be used at the beginning of
21096the command line when linking a shared library.
21097
21098@item 
21099@strong{Library_Options}: list
21100
21101Value is a list of options that are to be used when linking a shared library.
21102
21103@item 
21104@strong{Library_Rpath_Options}: list, indexed, case-insensitive index
21105
21106Index is a language name. Value is a list of options for an invocation of the
21107compiler of the language. This invocation is done for a shared library project
21108with sources of the language. The output of the invocation is the path name
21109of a shared library file. The directory name is to be put in the run path
21110option switch when linking the shared library for the project.
21111
21112@item 
21113@strong{Library_Src_Dir}: single
21114
21115Value is the name of the directory where copies of the sources of the
21116interfaces of a Stand-Alone Library are to be copied.
21117
21118@item 
21119@strong{Library_ALI_Dir}: single
21120
21121Value is the name of the directory where the ALI files of the interfaces
21122of a Stand-Alone Library are to be copied. When this attribute is not declared,
21123the directory is the library directory.
21124
21125@item 
21126@strong{Library_gcc}: single
21127
21128Obsolescent attribute. Specify the linker driver used to link a shared library.
21129Use instead attribute Linker'Driver.
21130
21131@item 
21132@strong{Library_Symbol_File}: single
21133
21134Value is the name of the library symbol file.
21135
21136@item 
21137@strong{Library_Symbol_Policy}: single
21138
21139Indicates the symbol policy kind. Only authorized case-insensitive values are
21140"autonomous", "default", "compliant", "controlled" or "direct".
21141
21142@item 
21143@strong{Library_Reference_Symbol_File}: single
21144
21145Value is the name of the reference symbol file.
21146@end itemize
21147
21148@item 
21149@strong{Configuration - General}
21150
21151
21152@itemize *
21153
21154@item 
21155@strong{Default_Language}: single
21156
21157Value is the case-insensitive name of the language of a project when attribute
21158Languages is not specified.
21159
21160@item 
21161@strong{Run_Path_Option}: list
21162
21163Value is the list of switches to be used when specifying the run path option
21164in an executable.
21165
21166@item 
21167@strong{Run_Path_Origin}: single
21168
21169Value is the the string that may replace the path name of the executable
21170directory in the run path options.
21171
21172@item 
21173@strong{Separate_Run_Path_Options}: single
21174
21175Indicates if there may be several run path options specified when linking an
21176executable. Only authorized case-insensitive values are "true" or "false" (the
21177default).
21178
21179@item 
21180@strong{Toolchain_Version}: single, indexed, case-insensitive index
21181
21182Index is a language name. Specify the version of a toolchain for a language.
21183
21184@item 
21185@strong{Toolchain_Description}: single, indexed, case-insensitive index
21186
21187Obsolescent. No longer used.
21188
21189@item 
21190@strong{Object_Generated}: single, indexed, case-insensitive index
21191
21192Index is a language name. Indicates if invoking the compiler for a language
21193produces an object file. Only authorized case-insensitive values are "false"
21194and "true" (the default).
21195
21196@item 
21197@strong{Objects_Linked}: single, indexed, case-insensitive index
21198
21199Index is a language name. Indicates if the object files created by the compiler
21200for a language need to be linked in the executable. Only authorized
21201case-insensitive values are "false" and "true" (the default).
21202
21203@item 
21204@strong{Target}: single
21205
21206Value is the name of the target platform. Taken into account only in the main
21207project.
21208
21209@item 
21210@strong{Runtime}: single, indexed, case-insensitive index
21211
21212Index is a language name. Indicates the runtime directory that is to be used
21213when using the compiler of the language. Taken into account only in the main
21214project.
21215@end itemize
21216
21217@item 
21218@strong{Configuration - Libraries}
21219
21220
21221@itemize *
21222
21223@item 
21224@strong{Library_Builder}: single
21225
21226Value is the path name of the application that is to be used to build
21227libraries. Usually the path name of "gprlib".
21228
21229@item 
21230@strong{Library_Support}: single
21231
21232Indicates the level of support of libraries. Only authorized case-insensitive
21233values are "static_only", "full" or "none" (the default).
21234@end itemize
21235
21236@item 
21237@strong{Configuration - Archives}
21238
21239
21240@itemize *
21241
21242@item 
21243@strong{Archive_Builder}: list
21244
21245Value is the name of the application to be used to create a static library
21246(archive), followed by the options to be used.
21247
21248@item 
21249@strong{Archive_Builder_Append_Option}: list
21250
21251Value is the list of options to be used when invoking the archive builder
21252to add project files into an archive.
21253
21254@item 
21255@strong{Archive_Indexer}: list
21256
21257Value is the name of the archive indexer, followed by the required options.
21258
21259@item 
21260@strong{Archive_Suffix}: single
21261
21262Value is the extension of archives. When not declared, the extension is ".a".
21263
21264@item 
21265@strong{Library_Partial_Linker}: list
21266
21267Value is the name of the partial linker executable, followed by the required
21268options.
21269@end itemize
21270
21271@item 
21272@strong{Configuration - Shared Libraries}
21273
21274
21275@itemize *
21276
21277@item 
21278@strong{Shared_Library_Prefix}: single
21279
21280Value is the prefix in the name of shared library files. When not declared,
21281the prefix is "lib".
21282
21283@item 
21284@strong{Shared_Library_Suffix}: single
21285
21286Value is the the extension of the name of shared library files. When not
21287declared, the extension is ".so".
21288
21289@item 
21290@strong{Symbolic_Link_Supported}: single
21291
21292Indicates if symbolic links are supported on the platform. Only authorized
21293case-insensitive values are "true" and "false" (the default).
21294
21295@item 
21296@strong{Library_Major_Minor_Id_Supported}: single
21297
21298Indicates if major and minor ids for shared library names are supported on
21299the platform. Only authorized case-insensitive values are "true" and "false"
21300(the default).
21301
21302@item 
21303@strong{Library_Auto_Init_Supported}: single
21304
21305Indicates if auto-initialization of Stand-Alone Libraries is supported. Only
21306authorized case-insensitive values are "true" and "false" (the default).
21307
21308@item 
21309@strong{Shared_Library_Minimum_Switches}: list
21310
21311Value is the list of required switches when linking a shared library.
21312
21313@item 
21314@strong{Library_Version_Switches}: list
21315
21316Value is the list of switches to specify a internal name for a shared library.
21317
21318@item 
21319@strong{Library_Install_Name_Option}: single
21320
21321Value is the name of the option that needs to be used, concatenated with the
21322path name of the library file, when linking a shared library.
21323
21324@item 
21325@strong{Runtime_Library_Dir}: single, indexed, case-insensitive index
21326
21327Index is a language name. Value is the path name of the directory where the
21328runtime libraries are located.
21329
21330@item 
21331@strong{Runtime_Source_Dir}: single, indexed, case-insensitive index
21332
21333Index is a language name. Value is the path name of the directory where the
21334sources of runtime libraries are located.
21335@end itemize
21336@end itemize
21337
21338@node Package Binder Attributes,Package Builder Attributes,Project Level Attributes,Attributes
21339@anchor{gnat_ugn/gnat_project_manager package-binder-attributes}@anchor{1a6}@anchor{gnat_ugn/gnat_project_manager id49}@anchor{1a7}
21340@subsubsection Package Binder Attributes
21341
21342
21343
21344@itemize *
21345
21346@item 
21347@strong{General}
21348
21349
21350@itemize *
21351
21352@item 
21353@strong{Default_Switches}: list, indexed, case-insensitive index
21354
21355Index is a language name. Value is the list of switches to be used when binding
21356code of the language, if there is no applicable attribute Switches.
21357
21358@item 
21359@strong{Switches}: list, optional index, indexed,
21360case-insensitive index, others allowed
21361
21362Index is either a language name or a source file name. Value is the list of
21363switches to be used when binding code. Index is either the source file name
21364of the executable to be bound or the language name of the code to be bound.
21365@end itemize
21366
21367@item 
21368@strong{Configuration - Binding}
21369
21370
21371@itemize *
21372
21373@item 
21374@strong{Driver}: single, indexed, case-insensitive index
21375
21376Index is a language name. Value is the name of the application to be used when
21377binding code of the language.
21378
21379@item 
21380@strong{Required_Switches}: list, indexed, case-insensitive index
21381
21382Index is a language name. Value is the list of the required switches to be
21383used when binding code of the language.
21384
21385@item 
21386@strong{Prefix}: single, indexed, case-insensitive index
21387
21388Index is a language name. Value is a prefix to be used for the binder exchange
21389file name for the language. Used to have different binder exchange file names
21390when binding different languages.
21391
21392@item 
21393@strong{Objects_Path}: single,indexed, case-insensitive index
21394
21395Index is a language name. Value is the name of the environment variable that
21396contains the path for the object directories.
21397
21398@item 
21399@strong{Object_Path_File}: single,indexed, case-insensitive index
21400
21401Index is a language name. Value is the name of the environment variable. The
21402value of the environment variable is the path name of a text file that
21403contains the list of object directories.
21404@end itemize
21405@end itemize
21406
21407@node Package Builder Attributes,Package Clean Attributes,Package Binder Attributes,Attributes
21408@anchor{gnat_ugn/gnat_project_manager package-builder-attributes}@anchor{1a8}@anchor{gnat_ugn/gnat_project_manager id50}@anchor{1a9}
21409@subsubsection Package Builder Attributes
21410
21411
21412
21413@itemize *
21414
21415@item 
21416@strong{Default_Switches}: list, indexed, case-insensitive index
21417
21418Index is a language name. Value is the list of builder switches to be used when
21419building an executable of the language, if there is no applicable attribute
21420Switches.
21421
21422@item 
21423@strong{Switches}: list, optional index, indexed, case-insensitive index,
21424others allowed
21425
21426Index is either a language name or a source file name. Value is the list of
21427builder switches to be used when building an executable. Index is either the
21428source file name of the executable to be built or its language name.
21429
21430@item 
21431@strong{Global_Compilation_Switches}: list, optional index, indexed,
21432case-insensitive index
21433
21434Index is either a language name or a source file name. Value is the list of
21435compilation switches to be used when building an executable. Index is either
21436the source file name of the executable to be built or its language name.
21437
21438@item 
21439@strong{Executable}: single, indexed, case-insensitive index
21440
21441Index is an executable source file name. Value is the simple file name of the
21442executable to be built.
21443
21444@item 
21445@strong{Executable_Suffix}: single
21446
21447Value is the extension of the file names of executable. When not specified,
21448the extension is the default extension of executables on the platform.
21449
21450@item 
21451@strong{Global_Configuration_Pragmas}: single
21452
21453Value is the file name of a configuration pragmas file that is specified to
21454the Ada compiler when compiling any Ada source in the project tree.
21455
21456@item 
21457@strong{Global_Config_File}: single, indexed, case-insensitive index
21458
21459Index is a language name. Value is the file name of a configuration file that
21460is specified to the compiler when compiling any source of the language in the
21461project tree.
21462@end itemize
21463
21464
21465@node Package Clean Attributes,Package Compiler Attributes,Package Builder Attributes,Attributes
21466@anchor{gnat_ugn/gnat_project_manager package-clean-attributes}@anchor{1aa}@anchor{gnat_ugn/gnat_project_manager id52}@anchor{1ab}
21467@subsubsection Package Clean Attributes
21468
21469
21470
21471@itemize *
21472
21473@item 
21474@strong{Switches}: list
21475
21476Value is a list of switches to be used by the cleaning application.
21477
21478@item 
21479@strong{Source_Artifact_Extensions}: list, indexed, case-insensitive index
21480
21481Index is a language names. Value is the list of extensions for file names
21482derived from object file names that need to be cleaned in the object
21483directory of the project.
21484
21485@item 
21486@strong{Object_Artifact_Extensions}: list, indexed, case-insensitive index
21487
21488Index is a language names. Value is the list of extensions for file names
21489derived from source file names that need to be cleaned in the object
21490directory of the project.
21491
21492@item 
21493@strong{Artifacts_In_Object_Dir}: single
21494
21495Value is a list of file names expressed as regular expressions that are to be
21496deleted by gprclean in the object directory of the project.
21497
21498@item 
21499@strong{Artifacts_In_Exec_Dir}: single
21500
21501Value is list of file names expressed as regular expressions that are to be
21502deleted by gprclean in the exec directory of the main project.
21503@end itemize
21504
21505@node Package Compiler Attributes,Package Cross_Reference Attributes,Package Clean Attributes,Attributes
21506@anchor{gnat_ugn/gnat_project_manager id53}@anchor{1ac}@anchor{gnat_ugn/gnat_project_manager package-compiler-attributes}@anchor{1ad}
21507@subsubsection Package Compiler Attributes
21508
21509
21510
21511@itemize *
21512
21513@item 
21514@strong{General}
21515
21516
21517@itemize *
21518
21519@item 
21520@strong{Default_Switches}: list, indexed, case-insensitive index
21521
21522Index is a language name. Value is a list of switches to be used when invoking
21523the compiler for the language for a source of the project, if there is no
21524applicable attribute Switches.
21525
21526@item 
21527@strong{Switches}: list, optional index, indexed, case-insensitive index,
21528others allowed
21529
21530Index is a source file name or a language name. Value is the list of switches
21531to be used when invoking the compiler for the source or for its language.
21532
21533@item 
21534@strong{Local_Configuration_Pragmas}: single
21535
21536Value is the file name of a configuration pragmas file that is specified to
21537the Ada compiler when compiling any Ada source in the project.
21538
21539@item 
21540@strong{Local_Config_File}: single, indexed, case-insensitive index
21541
21542Index is a language name. Value is the file name of a configuration file that
21543is specified to the compiler when compiling any source of the language in the
21544project.
21545@end itemize
21546
21547@item 
21548@strong{Configuration - Compiling}
21549
21550
21551@itemize *
21552
21553@item 
21554@strong{Driver}: single, indexed, case-insensitive index
21555
21556Index is a language name. Value is the name of the executable for the compiler
21557of the language.
21558
21559@item 
21560@strong{Language_Kind}: single, indexed, case-insensitive index
21561
21562Index is a language name. Indicates the kind of the language, either file based
21563or unit based. Only authorized case-insensitive values are "unit_based" and
21564"file_based" (the default).
21565
21566@item 
21567@strong{Dependency_Kind}: single, indexed, case-insensitive index
21568
21569Index is a language name. Indicates how the dependencies are handled for the
21570language. Only authorized case-insensitive values are "makefile", "ali_file",
21571"ali_closure" or "none" (the default).
21572
21573@item 
21574@strong{Required_Switches}: list, indexed, case-insensitive index
21575
21576Equivalent to attribute Leading_Required_Switches.
21577
21578@item 
21579@strong{Leading_Required_Switches}: list, indexed, case-insensitive index
21580
21581Index is a language name. Value is the list of the minimum switches to be used
21582at the beginning of the command line when invoking the compiler for the
21583language.
21584
21585@item 
21586@strong{Trailing_Required_Switches}: list, indexed, case-insensitive index
21587
21588Index is a language name. Value is the list of the minimum switches to be used
21589at the end of the command line when invoking the compiler for the language.
21590
21591@item 
21592@strong{PIC_Option}: list, indexed, case-insensitive index
21593
21594Index is a language name. Value is the list of switches to be used when
21595compiling a source of the language when the project is a shared library
21596project.
21597
21598@item 
21599@strong{Path_Syntax}: single, indexed, case-insensitive index
21600
21601Index is a language name. Value is the kind of path syntax to be used when
21602invoking the compiler for the language. Only authorized case-insensitive
21603values are "canonical" and "host" (the default).
21604
21605@item 
21606@strong{Source_File_Switches}: single, indexed, case-insensitive index
21607
21608Index is a language name. Value is a list of switches to be used just before
21609the path name of the source to compile when invoking the compiler for a source
21610of the language.
21611
21612@item 
21613@strong{Object_File_Suffix}: single, indexed, case-insensitive index
21614
21615Index is a language name. Value is the extension of the object files created
21616by the compiler of the language. When not specified, the extension is the
21617default one for the platform.
21618
21619@item 
21620@strong{Object_File_Switches}: list, indexed, case-insensitive index
21621
21622Index is a language name. Value is the list of switches to be used by the
21623compiler of the language to specify the path name of the object file. When not
21624specified, the switch used is "-o".
21625
21626@item 
21627@strong{Multi_Unit_Switches}: list, indexed, case-insensitive index
21628
21629Index is a language name. Value is the list of switches to be used to compile
21630a unit in a multi unit source of the language. The index of the unit in the
21631source is concatenated with the last switches in the list.
21632
21633@item 
21634@strong{Multi_Unit_Object_Separator}: single, indexed, case-insensitive index
21635
21636Index is a language name. Value is the string to be used in the object file
21637name before the index of the unit, when compiling a unit in a multi unit source
21638of the language.
21639@end itemize
21640
21641@item 
21642@strong{Configuration - Mapping Files}
21643
21644
21645@itemize *
21646
21647@item 
21648@strong{Mapping_File_Switches}: list, indexed, case-insensitive index
21649
21650Index is a language name. Value is the list of switches to be used to specify
21651a mapping file when invoking the compiler for a source of the language.
21652
21653@item 
21654@strong{Mapping_Spec_Suffix}: single, indexed, case-insensitive index
21655
21656Index is a language name. Value is the suffix to be used in a mapping file
21657to indicate that the source is a spec.
21658
21659@item 
21660@strong{Mapping_Body_Suffix}: single, indexed, case-insensitive index
21661
21662Index is a language name. Value is the suffix to be used in a mapping file
21663to indicate that the source is a body.
21664@end itemize
21665
21666@item 
21667@strong{Configuration - Config Files}
21668
21669
21670@itemize *
21671
21672@item 
21673@strong{Config_File_Switches}: list: single, indexed, case-insensitive index
21674
21675Index is a language name. Value is the list of switches to specify to the
21676compiler of the language a configuration file.
21677
21678@item 
21679@strong{Config_Body_File_Name}: single, indexed, case-insensitive index
21680
21681Index is a language name. Value is the template to be used to indicate a
21682configuration specific to a body of the language in a configuration
21683file.
21684
21685@item 
21686@strong{Config_Body_File_Name_Index}: single, indexed, case-insensitive index
21687
21688Index is a language name. Value is the template to be used to indicate a
21689configuration specific to the body a unit in a multi unit source of the
21690language in a configuration file.
21691
21692@item 
21693@strong{Config_Body_File_Name_Pattern}: single, indexed,
21694case-insensitive index
21695
21696Index is a language name. Value is the template to be used to indicate a
21697configuration for all bodies of the languages in a configuration file.
21698
21699@item 
21700@strong{Config_Spec_File_Name}: single, indexed, case-insensitive index
21701
21702Index is a language name. Value is the template to be used to indicate a
21703configuration specific to a spec of the language in a configuration
21704file.
21705
21706@item 
21707@strong{Config_Spec_File_Name_Index}: single, indexed, case-insensitive index
21708
21709Index is a language name. Value is the template to be used to indicate a
21710configuration specific to the spec a unit in a multi unit source of the
21711language in a configuration file.
21712
21713@item 
21714@strong{Config_Spec_File_Name_Pattern}: single, indexed,
21715case-insensitive index
21716
21717Index is a language name. Value is the template to be used to indicate a
21718configuration for all specs of the languages in a configuration file.
21719
21720@item 
21721@strong{Config_File_Unique}: single, indexed, case-insensitive index
21722
21723Index is a language name. Indicates if there should be only one configuration
21724file specified to the compiler of the language. Only authorized
21725case-insensitive values are "true" and "false" (the default).
21726@end itemize
21727
21728@item 
21729@strong{Configuration - Dependencies}
21730
21731
21732@itemize *
21733
21734@item 
21735@strong{Dependency_Switches}: list, indexed, case-insensitive index
21736
21737Index is a language name. Value is the list of switches to be used to specify
21738to the compiler the dependency file when the dependency kind of the language is
21739file based, and when Dependency_Driver is not specified for the language.
21740
21741@item 
21742@strong{Dependency_Driver}: list, indexed, case-insensitive index
21743
21744Index is a language name. Value is the name of the executable to be used to
21745create the dependency file for a source of the language, followed by the
21746required switches.
21747@end itemize
21748
21749@item 
21750@strong{Configuration - Search Paths}
21751
21752
21753@itemize *
21754
21755@item 
21756@strong{Include_Switches}: list, indexed, case-insensitive index
21757
21758Index is a language name. Value is the list of switches to specify to the
21759compiler of the language to indicate a directory to look for sources.
21760
21761@item 
21762@strong{Include_Path}: single, indexed, case-insensitive index
21763
21764Index is a language name. Value is the name of an environment variable that
21765contains the path of all the directories that the compiler of the language
21766may search for sources.
21767
21768@item 
21769@strong{Include_Path_File}: single, indexed, case-insensitive index
21770
21771Index is a language name. Value is the name of an environment variable the
21772value of which is the path name of a text file that contains the directories
21773that the compiler of the language may search for sources.
21774
21775@item 
21776@strong{Object_Path_Switches}: list, indexed, case-insensitive index
21777
21778Index is a language name. Value is the list of switches to specify to the
21779compiler of the language the name of a text file that contains the list of
21780object directories. When this attribute is not declared, the text file is
21781not created.
21782@end itemize
21783@end itemize
21784
21785@node Package Cross_Reference Attributes,Package Finder Attributes,Package Compiler Attributes,Attributes
21786@anchor{gnat_ugn/gnat_project_manager id54}@anchor{1ae}@anchor{gnat_ugn/gnat_project_manager package-cross-reference-attributes}@anchor{1af}
21787@subsubsection Package Cross_Reference Attributes
21788
21789
21790
21791@itemize *
21792
21793@item 
21794@strong{Default_Switches}: list, indexed, case-insensitive index
21795
21796Index is a language name. Value is a list of switches to be used when invoking
21797@cite{gnatxref} for a source of the language, if there is no applicable
21798attribute Switches.
21799
21800@item 
21801@strong{Switches}: list, optional index, indexed, case-insensitive index,
21802others allowed
21803
21804Index is a source file name. Value is the list of switches to be used when
21805invoking @cite{gnatxref} for the source.
21806@end itemize
21807
21808
21809@node Package Finder Attributes,Package gnatls Attributes,Package Cross_Reference Attributes,Attributes
21810@anchor{gnat_ugn/gnat_project_manager id56}@anchor{1b0}@anchor{gnat_ugn/gnat_project_manager package-finder-attributes}@anchor{1b1}
21811@subsubsection Package Finder Attributes
21812
21813
21814
21815@itemize *
21816
21817@item 
21818@strong{Default_Switches}: list, indexed, case-insensitive index
21819
21820Index is a language name. Value is a list of switches to be used when invoking
21821@cite{gnatfind} for a source of the language, if there is no applicable
21822attribute Switches.
21823
21824@item 
21825@strong{Switches}: list, optional index, indexed, case-insensitive index,
21826others allowed
21827
21828Index is a source file name. Value is the list of switches to be used when
21829invoking @cite{gnatfind} for the source.
21830@end itemize
21831
21832@node Package gnatls Attributes,Package IDE Attributes,Package Finder Attributes,Attributes
21833@anchor{gnat_ugn/gnat_project_manager package-gnatls-attributes}@anchor{1b2}@anchor{gnat_ugn/gnat_project_manager id57}@anchor{1b3}
21834@subsubsection Package gnatls Attributes
21835
21836
21837
21838@itemize *
21839
21840@item 
21841@strong{Switches}: list
21842
21843Value is a list of switches to be used when invoking @cite{gnatls}.
21844@end itemize
21845
21846
21847@node Package IDE Attributes,Package Install Attributes,Package gnatls Attributes,Attributes
21848@anchor{gnat_ugn/gnat_project_manager id58}@anchor{1b4}@anchor{gnat_ugn/gnat_project_manager package-ide-attributes}@anchor{1b5}
21849@subsubsection Package IDE Attributes
21850
21851
21852
21853@itemize *
21854
21855@item 
21856@strong{Default_Switches}: list, indexed
21857
21858Index is the name of an external tool that the GNAT Programming System (GPS)
21859is supporting. Value is a list of switches to use when invoking that tool.
21860
21861@item 
21862@strong{Remote_Host}: single
21863
21864Value is a string that designates the remote host in a cross-compilation
21865environment, to be used for remote compilation and debugging. This attribute
21866should not be specified when running on the local machine.
21867
21868@item 
21869@strong{Program_Host}: single
21870
21871Value is a string that specifies the name of IP address of the embedded target
21872in a cross-compilation environment, on which the program should execute.
21873
21874@item 
21875@strong{Communication_Protocol}: single
21876
21877Value is the name of the protocol to use to communicate with the target
21878in a cross-compilation environment, for example @cite{"wtx"} or
21879@cite{"vxworks"}.
21880
21881@item 
21882@strong{Compiler_Command}: single, indexed, case-insensitive index
21883
21884Index is a language Name. Value is a string that denotes the command to be
21885used to invoke the compiler. The value of @cite{Compiler_Command ("Ada")} is
21886expected to be compatible with @emph{gnatmake}, in particular in
21887the handling of switches.
21888
21889@item 
21890@strong{Debugger_Command}: single
21891
21892Value is a string that specifies the name of the debugger to be used, such as
21893gdb, powerpc-wrs-vxworks-gdb or gdb-4.
21894
21895@item 
21896@strong{gnatlist}: single
21897
21898Value is a string that specifies the name of the @emph{gnatls} utility
21899to be used to retrieve information about the predefined path; for example,
21900@cite{"gnatls"}, @cite{"powerpc-wrs-vxworks-gnatls"}.
21901
21902@item 
21903@strong{VCS_Kind}: single
21904
21905Value is a string used to specify the Version Control System (VCS) to be used
21906for this project, for example "Subversion", "ClearCase". If the
21907value is set to "Auto", the IDE will try to detect the actual VCS used
21908on the list of supported ones.
21909
21910@item 
21911@strong{VCS_File_Check}: single
21912
21913Value is a string that specifies the command used by the VCS to check
21914the validity of a file, either when the user explicitly asks for a check,
21915or as a sanity check before doing the check-in.
21916
21917@item 
21918@strong{VCS_Log_Check}: single
21919
21920Value is a string that specifies the command used by the VCS to check
21921the validity of a log file.
21922
21923@item 
21924@strong{Documentation_Dir}: single
21925
21926Value is the directory used to generate the documentation of source code.
21927@end itemize
21928
21929@node Package Install Attributes,Package Linker Attributes,Package IDE Attributes,Attributes
21930@anchor{gnat_ugn/gnat_project_manager package-install-attributes}@anchor{1b6}@anchor{gnat_ugn/gnat_project_manager id59}@anchor{1b7}
21931@subsubsection Package Install Attributes
21932
21933
21934
21935@itemize *
21936
21937@item 
21938@strong{Artifacts}: list, indexed
21939
21940An array attribute to declare a set of files not part of the sources
21941to be installed. The array discriminant is the directory where the
21942file is to be installed. If a relative directory then Prefix (see
21943below) is prepended.
21944
21945@item 
21946@strong{Prefix}: single
21947
21948Value is the install destination directory.
21949
21950@item 
21951@strong{Sources_Subdir}: single
21952
21953Value is the sources directory or subdirectory of Prefix.
21954
21955@item 
21956@strong{Exec_Subdir}: single
21957
21958Value is the executables directory or subdirectory of Prefix.
21959
21960@item 
21961@strong{Lib_Subdir}: single
21962
21963Value is library directory or subdirectory of Prefix.
21964
21965@item 
21966@strong{Project_Subdir}: single
21967
21968Value is the project directory or subdirectory of Prefix.
21969
21970@item 
21971@strong{Active}: single
21972
21973Indicates that the project is to be installed or not. Case-insensitive value
21974"false" means that the project is not to be installed, all other values mean
21975that the project is to be installed.
21976
21977@item 
21978@strong{Mode}: single
21979
21980Value is the installation mode, it is either @strong{dev} (default) or @strong{usage}.
21981
21982@item 
21983@strong{Install_Name}: single
21984
21985Specify the name to use for recording the installation. The default is
21986the project name without the extension.
21987@end itemize
21988
21989@node Package Linker Attributes,Package Naming Attributes,Package Install Attributes,Attributes
21990@anchor{gnat_ugn/gnat_project_manager id60}@anchor{1b8}@anchor{gnat_ugn/gnat_project_manager package-linker-attributes}@anchor{1b9}
21991@subsubsection Package Linker Attributes
21992
21993
21994
21995@itemize *
21996
21997@item 
21998@strong{General}
21999
22000
22001@itemize *
22002
22003@item 
22004@strong{Required_Switches}: list
22005
22006Value is a list of switches that are required when invoking the linker to link
22007an executable.
22008
22009@item 
22010@strong{Default_Switches}: list, indexed, case-insensitive index
22011
22012Index is a language name. Value is a list of switches for the linker when
22013linking an executable for a main source of the language, when there is no
22014applicable Switches.
22015
22016@item 
22017@strong{Leading_Switches}: list, optional index, indexed,
22018case-insensitive index, others allowed
22019
22020Index is a source file name or a language name. Value is the list of switches
22021to be used at the beginning of the command line when invoking the linker to
22022build an executable for the source or for its language.
22023
22024@item 
22025@strong{Switches}: list, optional index, indexed, case-insensitive index,
22026others allowed
22027
22028Index is a source file name or a language name. Value is the list of switches
22029to be used when invoking the linker to build an executable for the source or
22030for its language.
22031
22032@item 
22033@strong{Trailing_Switches}: list, optional index, indexed,
22034case-insensitive index, others allowed
22035
22036Index is a source file name or a language name. Value is the list of switches
22037to be used at the end of the command line when invoking the linker to
22038build an executable for the source or for its language. These switches may
22039override the Required_Switches.
22040
22041@item 
22042@strong{Linker_Options}: list
22043
22044Value is a list of switches/options that are to be added when linking an
22045executable from a project importing the current project directly or indirectly.
22046Linker_Options are not used when linking an executable from the current
22047project.
22048
22049@item 
22050@strong{Map_File_Option}: single
22051
22052Value is the switch to specify the map file name that the linker needs to
22053create.
22054@end itemize
22055
22056@item 
22057@strong{Configuration - Linking}
22058
22059
22060@itemize *
22061
22062@item 
22063@strong{Driver}: single
22064
22065Value is the name of the linker executable.
22066@end itemize
22067
22068@item 
22069@strong{Configuration - Response Files}
22070
22071
22072@itemize *
22073
22074@item 
22075@strong{Max_Command_Line_Length}: single
22076
22077Value is the maximum number of character in the command line when invoking
22078the linker to link an executable.
22079
22080@item 
22081@strong{Response_File_Format}: single
22082
22083Indicates the kind of response file to create when the length of the linking
22084command line is too large. Only authorized case-insensitive values are "none",
22085"gnu", "object_list", "gcc_gnu", "gcc_option_list" and "gcc_object_list".
22086
22087@item 
22088@strong{Response_File_Switches}: list
22089
22090Value is the list of switches to specify a response file to the linker.
22091@end itemize
22092@end itemize
22093
22094@c only PRO or GPL
22095@c 
22096@c .. _Package_Metrics_Attribute:
22097@c 
22098@c Package Metrics Attribute
22099@c ^^^^^^^^^^^^^^^^^^^^^^^^^
22100@c 
22101@c * **Default_Switches**: list, indexed, case-insensitive index
22102@c 
22103@c   Index is a language name. Value is a list of switches to be used when invoking
22104@c   `gnatmetric` for a source of the language, if there is no applicable
22105@c   attribute Switches.
22106@c 
22107@c * **Switches**: list, optional index, indexed, case-insensitive index,
22108@c   others allowed
22109@c 
22110@c   Index is a source file name. Value is the list of switches to be used when
22111@c   invoking `gnatmetric` for the source.
22112
22113@node Package Naming Attributes,Package Remote Attributes,Package Linker Attributes,Attributes
22114@anchor{gnat_ugn/gnat_project_manager package-naming-attributes}@anchor{1ba}@anchor{gnat_ugn/gnat_project_manager id61}@anchor{1bb}
22115@subsubsection Package Naming Attributes
22116
22117
22118
22119@itemize *
22120
22121@item 
22122@strong{Specification_Suffix}: single, indexed, case-insensitive index
22123
22124Equivalent to attribute Spec_Suffix.
22125
22126@item 
22127@strong{Spec_Suffix}: single, indexed, case-insensitive index
22128
22129Index is a language name. Value is the extension of file names for specs of
22130the language.
22131
22132@item 
22133@strong{Implementation_Suffix}: single, indexed, case-insensitive index
22134
22135Equivalent to attribute Body_Suffix.
22136
22137@item 
22138@strong{Body_Suffix}: single, indexed, case-insensitive index
22139
22140Index is a language name. Value is the extension of file names for bodies of
22141the language.
22142
22143@item 
22144@strong{Separate_Suffix}: single
22145
22146Value is the extension of file names for subunits of Ada.
22147
22148@item 
22149@strong{Casing}: single
22150
22151Indicates the casing of sources of the Ada language. Only authorized
22152case-insensitive values are "lowercase", "uppercase" and "mixedcase".
22153
22154@item 
22155@strong{Dot_Replacement}: single
22156
22157Value is the string that replace the dot of unit names in the source file names
22158of the Ada language.
22159
22160@item 
22161@strong{Specification}: single, optional index, indexed,
22162case-insensitive index
22163
22164Equivalent to attribute Spec.
22165
22166@item 
22167@strong{Spec}: single, optional index, indexed, case-insensitive index
22168
22169Index is a unit name. Value is the file name of the spec of the unit.
22170
22171@item 
22172@strong{Implementation}: single, optional index, indexed,
22173case-insensitive index
22174
22175Equivalent to attribute Body.
22176
22177@item 
22178@strong{Body}: single, optional index, indexed, case-insensitive index
22179
22180Index is a unit name. Value is the file name of the body of the unit.
22181
22182@item 
22183@strong{Specification_Exceptions}: list, indexed, case-insensitive index
22184
22185Index is a language name. Value is a list of specs for the language that do not
22186necessarily follow the naming scheme for the language and that may or may not
22187be found in the source directories of the project.
22188
22189@item 
22190@strong{Implementation_Exceptions}: list, indexed, case-insensitive index
22191
22192Index is a language name. Value is a list of bodies for the language that do not
22193necessarily follow the naming scheme for the language and that may or may not
22194be found in the source directories of the project.
22195@end itemize
22196
22197
22198@node Package Remote Attributes,Package Stack Attributes,Package Naming Attributes,Attributes
22199@anchor{gnat_ugn/gnat_project_manager package-remote-attributes}@anchor{1bc}@anchor{gnat_ugn/gnat_project_manager id63}@anchor{1bd}
22200@subsubsection Package Remote Attributes
22201
22202
22203
22204@itemize *
22205
22206@item 
22207@strong{Included_Patterns}: list
22208
22209If this attribute is defined it sets the patterns to
22210synchronized from the master to the slaves. It is exclusive
22211with Excluded_Patterns, that is it is an error to define
22212both.
22213
22214@item 
22215@strong{Included_Artifact_Patterns}: list
22216
22217If this attribute is defined it sets the patterns of compilation
22218artifacts to synchronized from the slaves to the build master.
22219This attribute replace the default hard-coded patterns.
22220
22221@item 
22222@strong{Excluded_Patterns}: list
22223
22224Set of patterns to ignore when synchronizing sources from the build
22225master to the slaves. A set of predefined patterns are supported
22226(e.g. *.o, *.ali, *.exe, etc.), this attributes make it possible to
22227add some more patterns.
22228
22229@item 
22230@strong{Root_Dir}: single
22231
22232Value is the root directory used by the slave machines.
22233@end itemize
22234
22235@node Package Stack Attributes,Package Synchronize Attributes,Package Remote Attributes,Attributes
22236@anchor{gnat_ugn/gnat_project_manager id64}@anchor{1be}@anchor{gnat_ugn/gnat_project_manager package-stack-attributes}@anchor{1bf}
22237@subsubsection Package Stack Attributes
22238
22239
22240
22241@itemize *
22242
22243@item 
22244@strong{Switches}: list
22245
22246Value is the list of switches to be used when invoking @cite{gnatstack}.
22247@end itemize
22248
22249@node Package Synchronize Attributes,,Package Stack Attributes,Attributes
22250@anchor{gnat_ugn/gnat_project_manager package-synchronize-attributes}@anchor{1c0}
22251@subsubsection Package Synchronize Attributes
22252
22253
22254
22255@itemize *
22256
22257@item 
22258@strong{Default_Switches}: list, indexed, case-insensitive index
22259
22260Index is a language name. Value is a list of switches to be used when invoking
22261@cite{gnatsync} for a source of the language, if there is no applicable
22262attribute Switches.
22263
22264@item 
22265@strong{Switches}: list, optional index, indexed, case-insensitive index,
22266others allowed
22267
22268Index is a source file name. Value is the list of switches to be used when
22269invoking @cite{gnatsync} for the source.
22270@end itemize
22271
22272@node Tools Supporting Project Files,GNAT Utility Programs,GNAT Project Manager,Top
22273@anchor{gnat_ugn/tools_supporting_project_files doc}@anchor{1c1}@anchor{gnat_ugn/tools_supporting_project_files tools-supporting-project-files}@anchor{c}@anchor{gnat_ugn/tools_supporting_project_files id1}@anchor{1c2}
22274@chapter Tools Supporting Project Files
22275
22276
22277This section describes how project files can be used in conjunction with a number of
22278GNAT tools.
22279
22280@menu
22281* gnatmake and Project Files:: 
22282* The GNAT Driver and Project Files:: 
22283
22284@end menu
22285
22286@node gnatmake and Project Files,The GNAT Driver and Project Files,,Tools Supporting Project Files
22287@anchor{gnat_ugn/tools_supporting_project_files id2}@anchor{1c3}@anchor{gnat_ugn/tools_supporting_project_files gnatmake-and-project-files}@anchor{e1}
22288@section gnatmake and Project Files
22289
22290
22291This section covers several topics related to @emph{gnatmake} and
22292project files: defining switches for @emph{gnatmake}
22293and for the tools that it invokes; specifying configuration pragmas;
22294the use of the @cite{Main} attribute; building and rebuilding library project
22295files.
22296
22297@menu
22298* Switches Related to Project Files:: 
22299* Switches and Project Files:: 
22300* Specifying Configuration Pragmas:: 
22301* Project Files and Main Subprograms:: 
22302* Library Project Files:: 
22303
22304@end menu
22305
22306@node Switches Related to Project Files,Switches and Project Files,,gnatmake and Project Files
22307@anchor{gnat_ugn/tools_supporting_project_files switches-related-to-project-files}@anchor{e3}@anchor{gnat_ugn/tools_supporting_project_files id3}@anchor{1c4}
22308@subsection Switches Related to Project Files
22309
22310
22311The following switches are used by GNAT tools that support project files:
22312
22313@quotation
22314
22315@geindex -P (any project-aware tool)
22316@end quotation
22317
22318
22319@table @asis
22320
22321@item @code{-P@emph{project}}
22322
22323Indicates the name of a project file. This project file will be parsed with
22324the verbosity indicated by @emph{-vP*x*},
22325if any, and using the external references indicated
22326by @emph{-X} switches, if any.
22327There may zero, one or more spaces between @emph{-P} and @cite{project}.
22328
22329There must be only one @emph{-P} switch on the command line.
22330
22331Since the Project Manager parses the project file only after all the switches
22332on the command line are checked, the order of the switches
22333@emph{-P},
22334@emph{-vP*x*}
22335or @emph{-X} is not significant.
22336
22337@geindex -X (any project-aware tool)
22338
22339@item @code{-X@emph{name}=@emph{value}}
22340
22341Indicates that external variable @cite{name} has the value @cite{value}.
22342The Project Manager will use this value for occurrences of
22343@cite{external(name)} when parsing the project file.
22344
22345If @cite{name} or @cite{value} includes a space, then @cite{name=value} should be
22346put between quotes.
22347
22348@example
22349-XOS=NT
22350-X"user=John Doe"
22351@end example
22352
22353Several @emph{-X} switches can be used simultaneously.
22354If several @emph{-X} switches specify the same
22355@cite{name}, only the last one is used.
22356
22357An external variable specified with a @emph{-X} switch
22358takes precedence over the value of the same name in the environment.
22359
22360@geindex -vP (any project-aware tool)
22361
22362@item @code{-vP@emph{x}}
22363
22364Indicates the verbosity of the parsing of GNAT project files.
22365
22366@emph{-vP0} means Default;
22367@emph{-vP1} means Medium;
22368@emph{-vP2} means High.
22369
22370The default is Default: no output for syntactically correct
22371project files.
22372If several @emph{-vP*x*} switches are present,
22373only the last one is used.
22374
22375@geindex -aP (any project-aware tool)
22376
22377@item @code{-aP@emph{dir}}
22378
22379Add directory @cite{dir} at the beginning of the project search path, in order,
22380after the current working directory.
22381
22382@geindex -eL (any project-aware tool)
22383
22384@item @code{-eL}
22385
22386Follow all symbolic links when processing project files.
22387
22388@geindex --subdirs= (gnatmake and gnatclean)
22389
22390@item @code{--subdirs=@emph{subdir}}
22391
22392This switch is recognized by @emph{gnatmake} and @emph{gnatclean}. It
22393indicate that the real directories (except the source directories) are the
22394subdirectories @cite{subdir} of the directories specified in the project files.
22395This applies in particular to object directories, library directories and
22396exec directories. If the subdirectories do not exist, they are created
22397automatically.
22398@end table
22399
22400@node Switches and Project Files,Specifying Configuration Pragmas,Switches Related to Project Files,gnatmake and Project Files
22401@anchor{gnat_ugn/tools_supporting_project_files id4}@anchor{1c5}@anchor{gnat_ugn/tools_supporting_project_files switches-and-project-files}@anchor{1c6}
22402@subsection Switches and Project Files
22403
22404
22405For each of the packages @cite{Builder}, @cite{Compiler}, @cite{Binder}, and
22406@cite{Linker}, you can specify a @cite{Default_Switches}
22407attribute, a @cite{Switches} attribute, or both;
22408as their names imply, these switch-related
22409attributes affect the switches that are used for each of these GNAT
22410components when
22411@emph{gnatmake} is invoked.  As will be explained below, these
22412component-specific switches precede
22413the switches provided on the @emph{gnatmake} command line.
22414
22415The @cite{Default_Switches} attribute is an attribute
22416indexed by language name (case insensitive) whose value is a string list.
22417For example:
22418
22419@quotation
22420
22421@example
22422package Compiler is
22423  for Default_Switches ("Ada")
22424      use ("-gnaty",
22425           "-v");
22426end Compiler;
22427@end example
22428@end quotation
22429
22430The @cite{Switches} attribute is indexed on a file name (which may or may
22431not be case sensitive, depending
22432on the operating system) whose value is a string list.  For example:
22433
22434@quotation
22435
22436@example
22437package Builder is
22438   for Switches ("main1.adb")
22439       use ("-O2");
22440   for Switches ("main2.adb")
22441       use ("-g");
22442end Builder;
22443@end example
22444@end quotation
22445
22446For the @cite{Builder} package, the file names must designate source files
22447for main subprograms.  For the @cite{Binder} and @cite{Linker} packages, the
22448file names must designate @code{ALI} or source files for main subprograms.
22449In each case just the file name without an explicit extension is acceptable.
22450
22451For each tool used in a program build (@emph{gnatmake}, the compiler, the
22452binder, and the linker), the corresponding package @@dfn@{contributes@} a set of
22453switches for each file on which the tool is invoked, based on the
22454switch-related attributes defined in the package.
22455In particular, the switches
22456that each of these packages contributes for a given file @cite{f} comprise:
22457
22458
22459@itemize *
22460
22461@item 
22462the value of attribute @cite{Switches (`f})`,
22463if it is specified in the package for the given file,
22464
22465@item 
22466otherwise, the value of @cite{Default_Switches ("Ada")},
22467if it is specified in the package.
22468@end itemize
22469
22470If neither of these attributes is defined in the package, then the package does
22471not contribute any switches for the given file.
22472
22473When @emph{gnatmake} is invoked on a file, the switches comprise
22474two sets, in the following order: those contributed for the file
22475by the @cite{Builder} package;
22476and the switches passed on the command line.
22477
22478When @emph{gnatmake} invokes a tool (compiler, binder, linker) on a file,
22479the switches passed to the tool comprise three sets,
22480in the following order:
22481
22482
22483@itemize *
22484
22485@item 
22486the applicable switches contributed for the file
22487by the @cite{Builder} package in the project file supplied on the command line;
22488
22489@item 
22490those contributed for the file by the package (in the relevant project file --
22491see below) corresponding to the tool; and
22492
22493@item 
22494the applicable switches passed on the command line.
22495@end itemize
22496
22497The term @emph{applicable switches} reflects the fact that
22498@emph{gnatmake} switches may or may not be passed to individual
22499tools, depending on the individual switch.
22500
22501@emph{gnatmake} may invoke the compiler on source files from different
22502projects. The Project Manager will use the appropriate project file to
22503determine the @cite{Compiler} package for each source file being compiled.
22504Likewise for the @cite{Binder} and @cite{Linker} packages.
22505
22506As an example, consider the following package in a project file:
22507
22508@quotation
22509
22510@example
22511project Proj1 is
22512   package Compiler is
22513      for Default_Switches ("Ada")
22514          use ("-g");
22515      for Switches ("a.adb")
22516          use ("-O1");
22517      for Switches ("b.adb")
22518          use ("-O2",
22519               "-gnaty");
22520   end Compiler;
22521end Proj1;
22522@end example
22523@end quotation
22524
22525If @emph{gnatmake} is invoked with this project file, and it needs to
22526compile, say, the files @code{a.adb}, @code{b.adb}, and @code{c.adb}, then
22527@code{a.adb} will be compiled with the switch @emph{-O1},
22528@code{b.adb} with switches @emph{-O2} and @emph{-gnaty},
22529and @code{c.adb} with @emph{-g}.
22530
22531The following example illustrates the ordering of the switches
22532contributed by different packages:
22533
22534@quotation
22535
22536@example
22537project Proj2 is
22538   package Builder is
22539      for Switches ("main.adb")
22540          use ("-g",
22541               "-O1",
22542               "-f");
22543   end Builder;
22544
22545   package Compiler is
22546      for Switches ("main.adb")
22547          use ("-O2");
22548   end Compiler;
22549end Proj2;
22550@end example
22551@end quotation
22552
22553If you issue the command:
22554
22555@quotation
22556
22557@example
22558$ gnatmake -Pproj2 -O0 main
22559@end example
22560@end quotation
22561
22562then the compiler will be invoked on @code{main.adb} with the following
22563sequence of switches
22564
22565@quotation
22566
22567@example
22568-g -O1 -O2 -O0
22569@end example
22570@end quotation
22571
22572with the last @emph{-O}
22573switch having precedence over the earlier ones;
22574several other switches
22575(such as @emph{-c}) are added implicitly.
22576
22577The switches @emph{-g}
22578and @emph{-O1} are contributed by package
22579@cite{Builder},  @emph{-O2} is contributed
22580by the package @cite{Compiler}
22581and @emph{-O0} comes from the command line.
22582
22583The @emph{-g} switch will also be passed in the invocation of
22584@emph{Gnatlink.}
22585
22586A final example illustrates switch contributions from packages in different
22587project files:
22588
22589@quotation
22590
22591@example
22592project Proj3 is
22593   for Source_Files use ("pack.ads", "pack.adb");
22594   package Compiler is
22595      for Default_Switches ("Ada")
22596          use ("-gnata");
22597   end Compiler;
22598end Proj3;
22599
22600with "Proj3";
22601project Proj4 is
22602   for Source_Files use ("foo_main.adb", "bar_main.adb");
22603   package Builder is
22604      for Switches ("foo_main.adb")
22605          use ("-s",
22606               "-g");
22607   end Builder;
22608end Proj4;
22609@end example
22610
22611@example
22612-- Ada source file:
22613with Pack;
22614procedure Foo_Main is
22615   ...
22616end Foo_Main;
22617@end example
22618@end quotation
22619
22620If the command is
22621
22622@quotation
22623
22624@example
22625$ gnatmake -PProj4 foo_main.adb -cargs -gnato
22626@end example
22627@end quotation
22628
22629then the switches passed to the compiler for @code{foo_main.adb} are
22630@emph{-g} (contributed by the package @cite{Proj4.Builder}) and
22631@emph{-gnato} (passed on the command line).
22632When the imported package @cite{Pack} is compiled, the switches used
22633are @emph{-g} from @cite{Proj4.Builder},
22634@emph{-gnata} (contributed from package @cite{Proj3.Compiler},
22635and @emph{-gnato} from the command line.
22636
22637When using @emph{gnatmake} with project files, some switches or
22638arguments may be expressed as relative paths. As the working directory where
22639compilation occurs may change, these relative paths are converted to absolute
22640paths. For the switches found in a project file, the relative paths
22641are relative to the project file directory, for the switches on the command
22642line, they are relative to the directory where @emph{gnatmake} is invoked.
22643The switches for which this occurs are:
22644-I,
22645-A,
22646-L,
22647-aO,
22648-aL,
22649-aI, as well as all arguments that are not switches (arguments to
22650switch
22651-o, object files specified in package @cite{Linker} or after
22652-largs on the command line). The exception to this rule is the switch
22653--RTS= for which a relative path argument is never converted.
22654
22655@node Specifying Configuration Pragmas,Project Files and Main Subprograms,Switches and Project Files,gnatmake and Project Files
22656@anchor{gnat_ugn/tools_supporting_project_files id5}@anchor{1c7}@anchor{gnat_ugn/tools_supporting_project_files specifying-configuration-pragmas}@anchor{7d}
22657@subsection Specifying Configuration Pragmas
22658
22659
22660When using @emph{gnatmake} with project files, if there exists a file
22661@code{gnat.adc} that contains configuration pragmas, this file will be
22662ignored.
22663
22664Configuration pragmas can be defined by means of the following attributes in
22665project files: @cite{Global_Configuration_Pragmas} in package @cite{Builder}
22666and @cite{Local_Configuration_Pragmas} in package @cite{Compiler}.
22667
22668Both these attributes are single string attributes. Their values is the path
22669name of a file containing configuration pragmas. If a path name is relative,
22670then it is relative to the project directory of the project file where the
22671attribute is defined.
22672
22673When compiling a source, the configuration pragmas used are, in order,
22674those listed in the file designated by attribute
22675@cite{Global_Configuration_Pragmas} in package @cite{Builder} of the main
22676project file, if it is specified, and those listed in the file designated by
22677attribute @cite{Local_Configuration_Pragmas} in package @cite{Compiler} of
22678the project file of the source, if it exists.
22679
22680@node Project Files and Main Subprograms,Library Project Files,Specifying Configuration Pragmas,gnatmake and Project Files
22681@anchor{gnat_ugn/tools_supporting_project_files id6}@anchor{1c8}@anchor{gnat_ugn/tools_supporting_project_files project-files-and-main-subprograms}@anchor{e2}
22682@subsection Project Files and Main Subprograms
22683
22684
22685When using a project file, you can invoke @emph{gnatmake}
22686with one or several main subprograms, by specifying their source files on the
22687command line.
22688
22689@quotation
22690
22691@example
22692$ gnatmake -Pprj main1.adb main2.adb main3.adb
22693@end example
22694@end quotation
22695
22696Each of these needs to be a source file of the same project, except
22697when the switch @cite{-u} is used.
22698
22699When @cite{-u} is not used, all the mains need to be sources of the
22700same project, one of the project in the tree rooted at the project specified
22701on the command line. The package @cite{Builder} of this common project, the
22702"main project" is the one that is considered by @emph{gnatmake}.
22703
22704When @cite{-u} is used, the specified source files may be in projects
22705imported directly or indirectly by the project specified on the command line.
22706Note that if such a source file is not part of the project specified on the
22707command line, the switches found in package @cite{Builder} of the
22708project specified on the command line, if any, that are transmitted
22709to the compiler will still be used, not those found in the project file of
22710the source file.
22711
22712When using a project file, you can also invoke @emph{gnatmake} without
22713explicitly specifying any main, and the effect depends on whether you have
22714defined the @cite{Main} attribute.  This attribute has a string list value,
22715where each element in the list is the name of a source file (the file
22716extension is optional) that contains a unit that can be a main subprogram.
22717
22718If the @cite{Main} attribute is defined in a project file as a non-empty
22719string list and the switch @emph{-u} is not used on the command
22720line, then invoking @emph{gnatmake} with this project file but without any
22721main on the command line is equivalent to invoking @emph{gnatmake} with all
22722the file names in the @cite{Main} attribute on the command line.
22723
22724Example:
22725
22726@quotation
22727
22728@example
22729project Prj is
22730   for Main use ("main1.adb", "main2.adb", "main3.adb");
22731end Prj;
22732@end example
22733@end quotation
22734
22735With this project file, @cite{"gnatmake -Pprj"}
22736is equivalent to
22737@cite{"gnatmake -Pprj main1.adb main2.adb main3.adb"}.
22738
22739When the project attribute @cite{Main} is not specified, or is specified
22740as an empty string list, or when the switch @emph{-u} is used on the command
22741line, then invoking @emph{gnatmake} with no main on the command line will
22742result in all immediate sources of the project file being checked, and
22743potentially recompiled. Depending on the presence of the switch @emph{-u},
22744sources from other project files on which the immediate sources of the main
22745project file depend are also checked and potentially recompiled. In other
22746words, the @emph{-u} switch is applied to all of the immediate sources of the
22747main project file.
22748
22749When no main is specified on the command line and attribute @cite{Main} exists
22750and includes several mains, or when several mains are specified on the
22751command line, the default switches in package @cite{Builder} will
22752be used for all mains, even if there are specific switches
22753specified for one or several mains.
22754
22755But the switches from package @cite{Binder} or @cite{Linker} will be
22756the specific switches for each main, if they are specified.
22757
22758@node Library Project Files,,Project Files and Main Subprograms,gnatmake and Project Files
22759@anchor{gnat_ugn/tools_supporting_project_files id7}@anchor{1c9}@anchor{gnat_ugn/tools_supporting_project_files library-project-files}@anchor{1ca}
22760@subsection Library Project Files
22761
22762
22763When @emph{gnatmake} is invoked with a main project file that is a library
22764project file, it is not allowed to specify one or more mains on the command
22765line.
22766
22767When a library project file is specified, switches @cite{-b} and
22768@cite{-l} have special meanings.
22769
22770
22771@itemize *
22772
22773@item 
22774@cite{-b} is only allowed for stand-alone libraries. It indicates
22775to @emph{gnatmake} that @emph{gnatbind} should be invoked for the
22776library.
22777
22778@item 
22779@cite{-l} may be used for all library projects. It indicates
22780to @emph{gnatmake} that the binder generated file should be compiled
22781(in the case of a stand-alone library) and that the library should be built.
22782@end itemize
22783
22784@node The GNAT Driver and Project Files,,gnatmake and Project Files,Tools Supporting Project Files
22785@anchor{gnat_ugn/tools_supporting_project_files id8}@anchor{1cb}@anchor{gnat_ugn/tools_supporting_project_files the-gnat-driver-and-project-files}@anchor{11f}
22786@section The GNAT Driver and Project Files
22787
22788
22789A number of GNAT tools beyond @emph{gnatmake}
22790can benefit from project files:
22791
22792
22793
22794@itemize *
22795
22796@item 
22797@emph{gnatbind}
22798
22799@item 
22800@emph{gnatclean}
22801
22802@item 
22803@emph{gnatfind}
22804
22805@item 
22806@emph{gnatlink}
22807
22808@item 
22809@emph{gnatls}
22810
22811@item 
22812@emph{gnatxref}
22813@end itemize
22814
22815However, none of these tools can be invoked
22816directly with a project file switch (@emph{-P}).
22817They must be invoked through the @emph{gnat} driver.
22818
22819The @emph{gnat} driver is a wrapper that accepts a number of commands and
22820calls the corresponding tool. It was designed initially for VMS platforms (to
22821convert VMS qualifiers to Unix-style switches), but it is now available on all
22822GNAT platforms.
22823
22824On non-VMS platforms, the @emph{gnat} driver accepts the following commands
22825(case insensitive):
22826
22827
22828
22829@itemize *
22830
22831@item 
22832BIND to invoke @emph{gnatbind}
22833
22834@item 
22835CHOP to invoke @emph{gnatchop}
22836
22837@item 
22838CLEAN to invoke @emph{gnatclean}
22839
22840@item 
22841COMP or COMPILE to invoke the compiler
22842
22843@item 
22844FIND to invoke @emph{gnatfind}
22845
22846@item 
22847KR or KRUNCH to invoke @emph{gnatkr}
22848
22849@item 
22850LINK to invoke @emph{gnatlink}
22851
22852@item 
22853LS or LIST to invoke @emph{gnatls}
22854
22855@item 
22856MAKE to invoke @emph{gnatmake}
22857
22858@item 
22859NAME to invoke @emph{gnatname}
22860
22861@item 
22862PREP or PREPROCESS to invoke @emph{gnatprep}
22863
22864@item 
22865XREF to invoke @emph{gnatxref}
22866@end itemize
22867
22868Note that the command
22869@emph{gnatmake -c -f -u} is used to invoke the compiler.
22870
22871On non-VMS platforms, between @emph{gnat} and the command, two
22872special switches may be used:
22873
22874
22875@itemize *
22876
22877@item 
22878@emph{-v} to display the invocation of the tool.
22879
22880@item 
22881@emph{-dn} to prevent the @emph{gnat} driver from removing
22882the temporary files it has created. These temporary files are
22883configuration files and temporary file list files.
22884@end itemize
22885
22886The command may be followed by switches and arguments for the invoked
22887tool.
22888
22889@quotation
22890
22891@example
22892$ gnat bind -C main.ali
22893$ gnat ls -a main
22894$ gnat chop foo.txt
22895@end example
22896@end quotation
22897
22898Switches may also be put in text files, one switch per line, and the text
22899files may be specified with their path name preceded by '@@'.
22900
22901@quotation
22902
22903@example
22904$ gnat bind @@args.txt main.ali
22905@end example
22906@end quotation
22907
22908In addition, for the following commands the project file related switches
22909(@emph{-P}, @emph{-X} and @emph{-vPx}) may be used in addition to
22910the switches of the invoking tool:
22911
22912
22913
22914@itemize *
22915
22916@item 
22917BIND
22918
22919@item 
22920COMP or COMPILE
22921
22922@item 
22923FIND
22924
22925@item 
22926LS or LIST
22927
22928@item 
22929LINK
22930
22931@item 
22932XREF
22933@end itemize
22934
22935
22936For each of the following commands, there is optionally a corresponding
22937package in the main project.
22938
22939
22940
22941@itemize *
22942
22943@item 
22944package @cite{Binder} for command BIND (invoking @cite{gnatbind})
22945
22946@item 
22947package @cite{Compiler} for command COMP or COMPILE (invoking the compiler)
22948
22949@item 
22950package @cite{Cross_Reference} for command XREF (invoking @cite{gnatxref})
22951
22952@item 
22953package @cite{Finder} for command FIND (invoking @cite{gnatfind})
22954
22955@item 
22956package @cite{Gnatls} for command LS or LIST (invoking @cite{gnatls})
22957
22958@item 
22959package @cite{Linker} for command LINK (invoking @cite{gnatlink})
22960@end itemize
22961
22962Package @cite{Gnatls} has a unique attribute @cite{Switches},
22963a simple variable with a string list value. It contains switches
22964for the invocation of @cite{gnatls}.
22965
22966@quotation
22967
22968@example
22969project Proj1 is
22970   package gnatls is
22971      for Switches
22972          use ("-a",
22973               "-v");
22974   end gnatls;
22975end Proj1;
22976@end example
22977@end quotation
22978
22979All other packages have two attribute @cite{Switches} and
22980@cite{Default_Switches}.
22981
22982@cite{Switches} is an indexed attribute, indexed by the
22983source file name, that has a string list value: the switches to be
22984used when the tool corresponding to the package is invoked for the specific
22985source file.
22986
22987@cite{Default_Switches} is an attribute,
22988indexed by  the programming language that has a string list value.
22989@cite{Default_Switches ("Ada")} contains the
22990switches for the invocation of the tool corresponding
22991to the package, except if a specific @cite{Switches} attribute
22992is specified for the source file.
22993
22994@quotation
22995
22996@example
22997project Proj is
22998
22999   for Source_Dirs use ("");
23000
23001   package gnatls is
23002      for Switches use
23003          ("-a",
23004           "-v");
23005   end gnatls;
23006
23007   package Compiler is
23008      for Default_Switches ("Ada")
23009          use ("-gnatv",
23010               "-gnatwa");
23011   end Binder;
23012
23013   package Binder is
23014      for Default_Switches ("Ada")
23015          use ("-C",
23016               "-e");
23017   end Binder;
23018
23019   package Linker is
23020      for Default_Switches ("Ada")
23021          use ("-C");
23022      for Switches ("main.adb")
23023          use ("-C",
23024               "-v",
23025               "-v");
23026   end Linker;
23027
23028   package Finder is
23029      for Default_Switches ("Ada")
23030           use ("-a",
23031                "-f");
23032   end Finder;
23033
23034   package Cross_Reference is
23035      for Default_Switches ("Ada")
23036          use ("-a",
23037               "-f",
23038               "-d",
23039               "-u");
23040   end Cross_Reference;
23041end Proj;
23042@end example
23043@end quotation
23044
23045With the above project file, commands such as
23046
23047@quotation
23048
23049@example
23050$ gnat comp -Pproj main
23051$ gnat ls -Pproj main
23052$ gnat xref -Pproj main
23053$ gnat bind -Pproj main.ali
23054$ gnat link -Pproj main.ali
23055@end example
23056@end quotation
23057
23058will set up the environment properly and invoke the tool with the switches
23059found in the package corresponding to the tool:
23060@cite{Default_Switches ("Ada")} for all tools,
23061except @cite{Switches ("main.adb")}
23062for @cite{gnatlink}.
23063
23064
23065@node GNAT Utility Programs,GNAT and Program Execution,Tools Supporting Project Files,Top
23066@anchor{gnat_ugn/gnat_utility_programs doc}@anchor{1cc}@anchor{gnat_ugn/gnat_utility_programs gnat-utility-programs}@anchor{d}@anchor{gnat_ugn/gnat_utility_programs id1}@anchor{1cd}
23067@chapter GNAT Utility Programs
23068
23069
23070This chapter describes a number of utility programs:
23071
23072
23073
23074@itemize *
23075
23076@item 
23077@ref{22,,The File Cleanup Utility gnatclean}
23078
23079@item 
23080@ref{23,,The GNAT Library Browser gnatls}
23081
23082@item 
23083@ref{24,,The Cross-Referencing Tools gnatxref and gnatfind}
23084
23085@item 
23086@ref{25,,The Ada to HTML Converter gnathtml}
23087@end itemize
23088
23089Other GNAT utilities are described elsewhere in this manual:
23090
23091
23092@itemize *
23093
23094@item 
23095@ref{5b,,Handling Arbitrary File Naming Conventions with gnatname}
23096
23097@item 
23098@ref{65,,File Name Krunching with gnatkr}
23099
23100@item 
23101@ref{38,,Renaming Files with gnatchop}
23102
23103@item 
23104@ref{19,,Preprocessing with gnatprep}
23105@end itemize
23106
23107@menu
23108* The File Cleanup Utility gnatclean:: 
23109* The GNAT Library Browser gnatls:: 
23110* The Cross-Referencing Tools gnatxref and gnatfind:: 
23111* The Ada to HTML Converter gnathtml:: 
23112
23113@end menu
23114
23115@node The File Cleanup Utility gnatclean,The GNAT Library Browser gnatls,,GNAT Utility Programs
23116@anchor{gnat_ugn/gnat_utility_programs id2}@anchor{1ce}@anchor{gnat_ugn/gnat_utility_programs the-file-cleanup-utility-gnatclean}@anchor{22}
23117@section The File Cleanup Utility @emph{gnatclean}
23118
23119
23120@geindex File cleanup tool
23121
23122@geindex gnatclean
23123
23124@cite{gnatclean} is a tool that allows the deletion of files produced by the
23125compiler, binder and linker, including ALI files, object files, tree files,
23126expanded source files, library files, interface copy source files, binder
23127generated files and executable files.
23128
23129@menu
23130* Running gnatclean:: 
23131* Switches for gnatclean:: 
23132
23133@end menu
23134
23135@node Running gnatclean,Switches for gnatclean,,The File Cleanup Utility gnatclean
23136@anchor{gnat_ugn/gnat_utility_programs running-gnatclean}@anchor{1cf}@anchor{gnat_ugn/gnat_utility_programs id3}@anchor{1d0}
23137@subsection Running @cite{gnatclean}
23138
23139
23140The @cite{gnatclean} command has the form:
23141
23142@quotation
23143
23144@example
23145$ gnatclean switches `names`
23146@end example
23147@end quotation
23148
23149where @cite{names} is a list of source file names. Suffixes @code{.ads} and
23150@code{adb} may be omitted. If a project file is specified using switch
23151@code{-P}, then @cite{names} may be completely omitted.
23152
23153In normal mode, @cite{gnatclean} delete the files produced by the compiler and,
23154if switch @cite{-c} is not specified, by the binder and
23155the linker. In informative-only mode, specified by switch
23156@cite{-n}, the list of files that would have been deleted in
23157normal mode is listed, but no file is actually deleted.
23158
23159@node Switches for gnatclean,,Running gnatclean,The File Cleanup Utility gnatclean
23160@anchor{gnat_ugn/gnat_utility_programs id4}@anchor{1d1}@anchor{gnat_ugn/gnat_utility_programs switches-for-gnatclean}@anchor{1d2}
23161@subsection Switches for @cite{gnatclean}
23162
23163
23164@cite{gnatclean} recognizes the following switches:
23165
23166@geindex --version (gnatclean)
23167
23168
23169@table @asis
23170
23171@item @code{--version}
23172
23173Display Copyright and version, then exit disregarding all other options.
23174@end table
23175
23176@geindex --help (gnatclean)
23177
23178
23179@table @asis
23180
23181@item @code{--help}
23182
23183If @emph{--version} was not used, display usage, then exit disregarding
23184all other options.
23185
23186@item @code{--subdirs=@emph{subdir}}
23187
23188Actual object directory of each project file is the subdirectory subdir of the
23189object directory specified or defaulted in the project file.
23190
23191@item @code{--unchecked-shared-lib-imports}
23192
23193By default, shared library projects are not allowed to import static library
23194projects. When this switch is used on the command line, this restriction is
23195relaxed.
23196@end table
23197
23198@geindex -c (gnatclean)
23199
23200
23201@table @asis
23202
23203@item @code{-c}
23204
23205Only attempt to delete the files produced by the compiler, not those produced
23206by the binder or the linker. The files that are not to be deleted are library
23207files, interface copy files, binder generated files and executable files.
23208@end table
23209
23210@geindex -D (gnatclean)
23211
23212
23213@table @asis
23214
23215@item @code{-D @emph{dir}}
23216
23217Indicate that ALI and object files should normally be found in directory @cite{dir}.
23218@end table
23219
23220@geindex -F (gnatclean)
23221
23222
23223@table @asis
23224
23225@item @code{-F}
23226
23227When using project files, if some errors or warnings are detected during
23228parsing and verbose mode is not in effect (no use of switch
23229-v), then error lines start with the full path name of the project
23230file, rather than its simple file name.
23231@end table
23232
23233@geindex -h (gnatclean)
23234
23235
23236@table @asis
23237
23238@item @code{-h}
23239
23240Output a message explaining the usage of @cite{gnatclean}.
23241@end table
23242
23243@geindex -n (gnatclean)
23244
23245
23246@table @asis
23247
23248@item @code{-n}
23249
23250Informative-only mode. Do not delete any files. Output the list of the files
23251that would have been deleted if this switch was not specified.
23252@end table
23253
23254@geindex -P (gnatclean)
23255
23256
23257@table @asis
23258
23259@item @code{-P@emph{project}}
23260
23261Use project file @cite{project}. Only one such switch can be used.
23262When cleaning a project file, the files produced by the compilation of the
23263immediate sources or inherited sources of the project files are to be
23264deleted. This is not depending on the presence or not of executable names
23265on the command line.
23266@end table
23267
23268@geindex -q (gnatclean)
23269
23270
23271@table @asis
23272
23273@item @code{-q}
23274
23275Quiet output. If there are no errors, do not output anything, except in
23276verbose mode (switch -v) or in informative-only mode
23277(switch -n).
23278@end table
23279
23280@geindex -r (gnatclean)
23281
23282
23283@table @asis
23284
23285@item @code{-r}
23286
23287When a project file is specified (using switch -P),
23288clean all imported and extended project files, recursively. If this switch
23289is not specified, only the files related to the main project file are to be
23290deleted. This switch has no effect if no project file is specified.
23291@end table
23292
23293@geindex -v (gnatclean)
23294
23295
23296@table @asis
23297
23298@item @code{-v}
23299
23300Verbose mode.
23301@end table
23302
23303@geindex -vP (gnatclean)
23304
23305
23306@table @asis
23307
23308@item @code{-vP@emph{x}}
23309
23310Indicates the verbosity of the parsing of GNAT project files.
23311@ref{e3,,Switches Related to Project Files}.
23312@end table
23313
23314@geindex -X (gnatclean)
23315
23316
23317@table @asis
23318
23319@item @code{-X@emph{name}=@emph{value}}
23320
23321Indicates that external variable @cite{name} has the value @cite{value}.
23322The Project Manager will use this value for occurrences of
23323@cite{external(name)} when parsing the project file.
23324@ref{e3,,Switches Related to Project Files}.
23325@end table
23326
23327@geindex -aO (gnatclean)
23328
23329
23330@table @asis
23331
23332@item @code{-aO@emph{dir}}
23333
23334When searching for ALI and object files, look in directory @cite{dir}.
23335@end table
23336
23337@geindex -I (gnatclean)
23338
23339
23340@table @asis
23341
23342@item @code{-I@emph{dir}}
23343
23344Equivalent to @code{-aO@emph{dir}}.
23345@end table
23346
23347@geindex -I- (gnatclean)
23348
23349@geindex Source files
23350@geindex suppressing search
23351
23352
23353@table @asis
23354
23355@item @code{-I-}
23356
23357Do not look for ALI or object files in the directory
23358where @cite{gnatclean} was invoked.
23359@end table
23360
23361@node The GNAT Library Browser gnatls,The Cross-Referencing Tools gnatxref and gnatfind,The File Cleanup Utility gnatclean,GNAT Utility Programs
23362@anchor{gnat_ugn/gnat_utility_programs the-gnat-library-browser-gnatls}@anchor{23}@anchor{gnat_ugn/gnat_utility_programs id5}@anchor{1d3}
23363@section The GNAT Library Browser @cite{gnatls}
23364
23365
23366@geindex Library browser
23367
23368@c index: ! gnatls
23369
23370@cite{gnatls} is a tool that outputs information about compiled
23371units. It gives the relationship between objects, unit names and source
23372files. It can also be used to check the source dependencies of a unit
23373as well as various characteristics.
23374
23375Note: to invoke @cite{gnatls} with a project file, use the @cite{gnat}
23376driver (see @ref{11f,,The GNAT Driver and Project Files}).
23377
23378@menu
23379* Running gnatls:: 
23380* Switches for gnatls:: 
23381* Example of gnatls Usage:: 
23382
23383@end menu
23384
23385@node Running gnatls,Switches for gnatls,,The GNAT Library Browser gnatls
23386@anchor{gnat_ugn/gnat_utility_programs id6}@anchor{1d4}@anchor{gnat_ugn/gnat_utility_programs running-gnatls}@anchor{1d5}
23387@subsection Running @cite{gnatls}
23388
23389
23390The @cite{gnatls} command has the form
23391
23392@quotation
23393
23394@example
23395$ gnatls switches `object_or_ali_file`
23396@end example
23397@end quotation
23398
23399The main argument is the list of object or @code{ali} files
23400(see @ref{44,,The Ada Library Information Files})
23401for which information is requested.
23402
23403In normal mode, without additional option, @cite{gnatls} produces a
23404four-column listing. Each line represents information for a specific
23405object. The first column gives the full path of the object, the second
23406column gives the name of the principal unit in this object, the third
23407column gives the status of the source and the fourth column gives the
23408full path of the source representing this unit.
23409Here is a simple example of use:
23410
23411@quotation
23412
23413@example
23414$ gnatls *.o
23415./demo1.o            demo1            DIF demo1.adb
23416./demo2.o            demo2             OK demo2.adb
23417./hello.o            h1                OK hello.adb
23418./instr-child.o      instr.child      MOK instr-child.adb
23419./instr.o            instr             OK instr.adb
23420./tef.o              tef              DIF tef.adb
23421./text_io_example.o  text_io_example   OK text_io_example.adb
23422./tgef.o             tgef             DIF tgef.adb
23423@end example
23424@end quotation
23425
23426The first line can be interpreted as follows: the main unit which is
23427contained in
23428object file @code{demo1.o} is demo1, whose main source is in
23429@code{demo1.adb}. Furthermore, the version of the source used for the
23430compilation of demo1 has been modified (DIF). Each source file has a status
23431qualifier which can be:
23432
23433
23434@table @asis
23435
23436@item @emph{OK (unchanged)}
23437
23438The version of the source file used for the compilation of the
23439specified unit corresponds exactly to the actual source file.
23440
23441@item @emph{MOK (slightly modified)}
23442
23443The version of the source file used for the compilation of the
23444specified unit differs from the actual source file but not enough to
23445require recompilation. If you use gnatmake with the qualifier
23446@emph{-m (minimal recompilation)}, a file marked
23447MOK will not be recompiled.
23448
23449@item @emph{DIF (modified)}
23450
23451No version of the source found on the path corresponds to the source
23452used to build this object.
23453
23454@item @emph{??? (file not found)}
23455
23456No source file was found for this unit.
23457
23458@item @emph{HID (hidden,  unchanged version not first on PATH)}
23459
23460The version of the source that corresponds exactly to the source used
23461for compilation has been found on the path but it is hidden by another
23462version of the same source that has been modified.
23463@end table
23464
23465@node Switches for gnatls,Example of gnatls Usage,Running gnatls,The GNAT Library Browser gnatls
23466@anchor{gnat_ugn/gnat_utility_programs id7}@anchor{1d6}@anchor{gnat_ugn/gnat_utility_programs switches-for-gnatls}@anchor{1d7}
23467@subsection Switches for @cite{gnatls}
23468
23469
23470@cite{gnatls} recognizes the following switches:
23471
23472@geindex --version (gnatls)
23473
23474
23475@table @asis
23476
23477@item @code{--version}
23478
23479Display Copyright and version, then exit disregarding all other options.
23480@end table
23481
23482@geindex --help (gnatls)
23483
23484
23485@table @asis
23486
23487@item @code{*--help}
23488
23489If @emph{--version} was not used, display usage, then exit disregarding
23490all other options.
23491@end table
23492
23493@geindex -a (gnatls)
23494
23495
23496@table @asis
23497
23498@item @code{-a}
23499
23500Consider all units, including those of the predefined Ada library.
23501Especially useful with @emph{-d}.
23502@end table
23503
23504@geindex -d (gnatls)
23505
23506
23507@table @asis
23508
23509@item @code{-d}
23510
23511List sources from which specified units depend on.
23512@end table
23513
23514@geindex -h (gnatls)
23515
23516
23517@table @asis
23518
23519@item @code{-h}
23520
23521Output the list of options.
23522@end table
23523
23524@geindex -o (gnatls)
23525
23526
23527@table @asis
23528
23529@item @code{-o}
23530
23531Only output information about object files.
23532@end table
23533
23534@geindex -s (gnatls)
23535
23536
23537@table @asis
23538
23539@item @code{-s}
23540
23541Only output information about source files.
23542@end table
23543
23544@geindex -u (gnatls)
23545
23546
23547@table @asis
23548
23549@item @code{-u}
23550
23551Only output information about compilation units.
23552@end table
23553
23554@geindex -files (gnatls)
23555
23556
23557@table @asis
23558
23559@item @code{-files=@emph{file}}
23560
23561Take as arguments the files listed in text file @cite{file}.
23562Text file @cite{file} may contain empty lines that are ignored.
23563Each nonempty line should contain the name of an existing file.
23564Several such switches may be specified simultaneously.
23565@end table
23566
23567@geindex -aO (gnatls)
23568
23569@geindex -aI (gnatls)
23570
23571@geindex -I (gnatls)
23572
23573@geindex -I- (gnatls)
23574
23575
23576@table @asis
23577
23578@item @code{-aO@emph{dir}}, @code{-aI@emph{dir}}, @code{-I@emph{dir}}, @code{-I-}, @code{-nostdinc}
23579
23580Source path manipulation. Same meaning as the equivalent @emph{gnatmake}
23581flags (@ref{df,,Switches for gnatmake}).
23582@end table
23583
23584@geindex -aP (gnatls)
23585
23586
23587@table @asis
23588
23589@item @code{-aP@emph{dir}}
23590
23591Add @cite{dir} at the beginning of the project search dir.
23592@end table
23593
23594@geindex --RTS (gnatls)
23595
23596
23597@table @asis
23598
23599@item @code{--RTS=@emph{rts-path}`}
23600
23601Specifies the default location of the runtime library. Same meaning as the
23602equivalent @emph{gnatmake} flag (@ref{df,,Switches for gnatmake}).
23603@end table
23604
23605@geindex -v (gnatls)
23606
23607
23608@table @asis
23609
23610@item @code{-v}
23611
23612Verbose mode. Output the complete source, object and project paths. Do not use
23613the default column layout but instead use long format giving as much as
23614information possible on each requested units, including special
23615characteristics such as:
23616
23617
23618@itemize *
23619
23620@item 
23621@emph{Preelaborable}: The unit is preelaborable in the Ada sense.
23622
23623@item 
23624@emph{No_Elab_Code}:  No elaboration code has been produced by the compiler for this unit.
23625
23626@item 
23627@emph{Pure}: The unit is pure in the Ada sense.
23628
23629@item 
23630@emph{Elaborate_Body}: The unit contains a pragma Elaborate_Body.
23631
23632@item 
23633@emph{Remote_Types}: The unit contains a pragma Remote_Types.
23634
23635@item 
23636@emph{Shared_Passive}: The unit contains a pragma Shared_Passive.
23637
23638@item 
23639@emph{Predefined}: This unit is part of the predefined environment and cannot be modified
23640by the user.
23641
23642@item 
23643@emph{Remote_Call_Interface}: The unit contains a pragma Remote_Call_Interface.
23644@end itemize
23645@end table
23646
23647@node Example of gnatls Usage,,Switches for gnatls,The GNAT Library Browser gnatls
23648@anchor{gnat_ugn/gnat_utility_programs id8}@anchor{1d8}@anchor{gnat_ugn/gnat_utility_programs example-of-gnatls-usage}@anchor{1d9}
23649@subsection Example of @cite{gnatls} Usage
23650
23651
23652Example of using the verbose switch. Note how the source and
23653object paths are affected by the -I switch.
23654
23655@quotation
23656
23657@example
23658$ gnatls -v -I.. demo1.o
23659
23660GNATLS 5.03w (20041123-34)
23661Copyright 1997-2004 Free Software Foundation, Inc.
23662
23663Source Search Path:
23664   <Current_Directory>
23665   ../
23666   /home/comar/local/adainclude/
23667
23668Object Search Path:
23669   <Current_Directory>
23670   ../
23671   /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
23672
23673Project Search Path:
23674   <Current_Directory>
23675   /home/comar/local/lib/gnat/
23676
23677./demo1.o
23678   Unit =>
23679     Name   => demo1
23680     Kind   => subprogram body
23681     Flags  => No_Elab_Code
23682     Source => demo1.adb    modified
23683@end example
23684@end quotation
23685
23686The following is an example of use of the dependency list.
23687Note the use of the -s switch
23688which gives a straight list of source files. This can be useful for
23689building specialized scripts.
23690
23691@quotation
23692
23693@example
23694$ gnatls -d demo2.o
23695./demo2.o   demo2        OK demo2.adb
23696                         OK gen_list.ads
23697                         OK gen_list.adb
23698                         OK instr.ads
23699                         OK instr-child.ads
23700
23701$ gnatls -d -s -a demo1.o
23702demo1.adb
23703/home/comar/local/adainclude/ada.ads
23704/home/comar/local/adainclude/a-finali.ads
23705/home/comar/local/adainclude/a-filico.ads
23706/home/comar/local/adainclude/a-stream.ads
23707/home/comar/local/adainclude/a-tags.ads
23708gen_list.ads
23709gen_list.adb
23710/home/comar/local/adainclude/gnat.ads
23711/home/comar/local/adainclude/g-io.ads
23712instr.ads
23713/home/comar/local/adainclude/system.ads
23714/home/comar/local/adainclude/s-exctab.ads
23715/home/comar/local/adainclude/s-finimp.ads
23716/home/comar/local/adainclude/s-finroo.ads
23717/home/comar/local/adainclude/s-secsta.ads
23718/home/comar/local/adainclude/s-stalib.ads
23719/home/comar/local/adainclude/s-stoele.ads
23720/home/comar/local/adainclude/s-stratt.ads
23721/home/comar/local/adainclude/s-tasoli.ads
23722/home/comar/local/adainclude/s-unstyp.ads
23723/home/comar/local/adainclude/unchconv.ads
23724@end example
23725@end quotation
23726
23727@node The Cross-Referencing Tools gnatxref and gnatfind,The Ada to HTML Converter gnathtml,The GNAT Library Browser gnatls,GNAT Utility Programs
23728@anchor{gnat_ugn/gnat_utility_programs the-cross-referencing-tools-gnatxref-and-gnatfind}@anchor{24}@anchor{gnat_ugn/gnat_utility_programs id9}@anchor{1da}
23729@section The Cross-Referencing Tools @cite{gnatxref} and @cite{gnatfind}
23730
23731
23732@geindex gnatxref
23733
23734@geindex gnatfind
23735
23736The compiler generates cross-referencing information (unless
23737you set the @code{-gnatx} switch), which are saved in the @code{.ali} files.
23738This information indicates where in the source each entity is declared and
23739referenced. Note that entities in package Standard are not included, but
23740entities in all other predefined units are included in the output.
23741
23742Before using any of these two tools, you need to compile successfully your
23743application, so that GNAT gets a chance to generate the cross-referencing
23744information.
23745
23746The two tools @cite{gnatxref} and @cite{gnatfind} take advantage of this
23747information to provide the user with the capability to easily locate the
23748declaration and references to an entity. These tools are quite similar,
23749the difference being that @cite{gnatfind} is intended for locating
23750definitions and/or references to a specified entity or entities, whereas
23751@cite{gnatxref} is oriented to generating a full report of all
23752cross-references.
23753
23754To use these tools, you must not compile your application using the
23755@emph{-gnatx} switch on the @emph{gnatmake} command line
23756(see @ref{1d,,Building with gnatmake}). Otherwise, cross-referencing
23757information will not be generated.
23758
23759Note: to invoke @cite{gnatxref} or @cite{gnatfind} with a project file,
23760use the @cite{gnat} driver (see @ref{11f,,The GNAT Driver and Project Files}).
23761
23762@menu
23763* gnatxref Switches:: 
23764* gnatfind Switches:: 
23765* Project Files for gnatxref and gnatfind:: 
23766* Regular Expressions in gnatfind and gnatxref:: 
23767* Examples of gnatxref Usage:: 
23768* Examples of gnatfind Usage:: 
23769
23770@end menu
23771
23772@node gnatxref Switches,gnatfind Switches,,The Cross-Referencing Tools gnatxref and gnatfind
23773@anchor{gnat_ugn/gnat_utility_programs id10}@anchor{1db}@anchor{gnat_ugn/gnat_utility_programs gnatxref-switches}@anchor{1dc}
23774@subsection @cite{gnatxref} Switches
23775
23776
23777The command invocation for @cite{gnatxref} is:
23778
23779@quotation
23780
23781@example
23782$ gnatxref [`switches`] `sourcefile1` [`sourcefile2` ...]
23783@end example
23784@end quotation
23785
23786where
23787
23788
23789@table @asis
23790
23791@item @emph{sourcefile1} [, @emph{sourcefile2} ...]
23792
23793identify the source files for which a report is to be generated. The
23794'with'ed units will be processed too. You must provide at least one file.
23795
23796These file names are considered to be regular expressions, so for instance
23797specifying @code{source*.adb} is the same as giving every file in the current
23798directory whose name starts with @code{source} and whose extension is
23799@code{adb}.
23800
23801You shouldn't specify any directory name, just base names. @emph{gnatxref}
23802and @emph{gnatfind} will be able to locate these files by themselves using
23803the source path. If you specify directories, no result is produced.
23804@end table
23805
23806The following switches are available for @emph{gnatxref}:
23807
23808@geindex --version (gnatxref)
23809
23810
23811@table @asis
23812
23813@item @code{-version}
23814
23815Display Copyright and version, then exit disregarding all other options.
23816@end table
23817
23818@geindex --help (gnatxref)
23819
23820
23821@table @asis
23822
23823@item @code{-help}
23824
23825If @emph{--version} was not used, display usage, then exit disregarding
23826all other options.
23827@end table
23828
23829@geindex -a (gnatxref)
23830
23831
23832@table @asis
23833
23834@item @code{a}
23835
23836If this switch is present, @cite{gnatfind} and @cite{gnatxref} will parse
23837the read-only files found in the library search path. Otherwise, these files
23838will be ignored. This option can be used to protect Gnat sources or your own
23839libraries from being parsed, thus making @cite{gnatfind} and @cite{gnatxref}
23840much faster, and their output much smaller. Read-only here refers to access
23841or permissions status in the file system for the current user.
23842@end table
23843
23844@geindex -aIDIR (gnatxref)
23845
23846
23847@table @asis
23848
23849@item @code{aI@emph{DIR}}
23850
23851When looking for source files also look in directory DIR. The order in which
23852source file search is undertaken is the same as for @emph{gnatmake}.
23853@end table
23854
23855@geindex -aODIR (gnatxref)
23856
23857
23858@table @asis
23859
23860@item @code{aO@emph{DIR}}
23861
23862When searching for library and object files, look in directory
23863DIR. The order in which library files are searched is the same as for
23864@emph{gnatmake}.
23865@end table
23866
23867@geindex -nostdinc (gnatxref)
23868
23869
23870@table @asis
23871
23872@item @code{nostdinc}
23873
23874Do not look for sources in the system default directory.
23875@end table
23876
23877@geindex -nostdlib (gnatxref)
23878
23879
23880@table @asis
23881
23882@item @code{nostdlib}
23883
23884Do not look for library files in the system default directory.
23885@end table
23886
23887@geindex --ext (gnatxref)
23888
23889
23890@table @asis
23891
23892@item @code{-ext=@emph{extension}}
23893
23894Specify an alternate ali file extension. The default is @cite{ali} and other
23895extensions (e.g. @cite{gli} for C/C++ sources when using @emph{-fdump-xref})
23896may be specified via this switch. Note that if this switch overrides the
23897default, which means that only the new extension will be considered.
23898@end table
23899
23900@geindex --RTS (gnatxref)
23901
23902
23903@table @asis
23904
23905@item @code{-RTS=@emph{rts-path}}
23906
23907Specifies the default location of the runtime library. Same meaning as the
23908equivalent @emph{gnatmake} flag (@ref{df,,Switches for gnatmake}).
23909@end table
23910
23911@geindex -d (gnatxref)
23912
23913
23914@table @asis
23915
23916@item @code{d}
23917
23918If this switch is set @cite{gnatxref} will output the parent type
23919reference for each matching derived types.
23920@end table
23921
23922@geindex -f (gnatxref)
23923
23924
23925@table @asis
23926
23927@item @code{f}
23928
23929If this switch is set, the output file names will be preceded by their
23930directory (if the file was found in the search path). If this switch is
23931not set, the directory will not be printed.
23932@end table
23933
23934@geindex -g (gnatxref)
23935
23936
23937@table @asis
23938
23939@item @code{g}
23940
23941If this switch is set, information is output only for library-level
23942entities, ignoring local entities. The use of this switch may accelerate
23943@cite{gnatfind} and @cite{gnatxref}.
23944@end table
23945
23946@geindex -IDIR (gnatxref)
23947
23948
23949@table @asis
23950
23951@item @code{I@emph{DIR}}
23952
23953Equivalent to @code{-aODIR -aIDIR}.
23954@end table
23955
23956@geindex -pFILE (gnatxref)
23957
23958
23959@table @asis
23960
23961@item @code{p@emph{FILE}}
23962
23963Specify a project file to use @ref{b,,GNAT Project Manager}.
23964If you need to use the @code{.gpr}
23965project files, you should use gnatxref through the GNAT driver
23966(@emph{gnat xref -Pproject}).
23967
23968By default, @cite{gnatxref} and @cite{gnatfind} will try to locate a
23969project file in the current directory.
23970
23971If a project file is either specified or found by the tools, then the content
23972of the source directory and object directory lines are added as if they
23973had been specified respectively by @code{-aI}
23974and @code{-aO}.
23975
23976@item @code{u}
23977
23978Output only unused symbols. This may be really useful if you give your
23979main compilation unit on the command line, as @cite{gnatxref} will then
23980display every unused entity and 'with'ed package.
23981
23982@item @code{v}
23983
23984Instead of producing the default output, @cite{gnatxref} will generate a
23985@code{tags} file that can be used by vi. For examples how to use this
23986feature, see @ref{1dd,,Examples of gnatxref Usage}. The tags file is output
23987to the standard output, thus you will have to redirect it to a file.
23988@end table
23989
23990All these switches may be in any order on the command line, and may even
23991appear after the file names. They need not be separated by spaces, thus
23992you can say @code{gnatxref -ag} instead of @code{gnatxref -a -g}.
23993
23994@node gnatfind Switches,Project Files for gnatxref and gnatfind,gnatxref Switches,The Cross-Referencing Tools gnatxref and gnatfind
23995@anchor{gnat_ugn/gnat_utility_programs id11}@anchor{1de}@anchor{gnat_ugn/gnat_utility_programs gnatfind-switches}@anchor{1df}
23996@subsection @cite{gnatfind} Switches
23997
23998
23999The command invocation for @cite{gnatfind} is:
24000
24001@quotation
24002
24003@example
24004$ gnatfind [`switches`] `pattern`[:`sourcefile`[:`line`[:`column`]]]
24005      [`file1` `file2` ...]
24006@end example
24007@end quotation
24008
24009with the following iterpretation of the command arguments:
24010
24011
24012@table @asis
24013
24014@item @emph{pattern}
24015
24016An entity will be output only if it matches the regular expression found
24017in @cite{pattern}, see @ref{1e0,,Regular Expressions in gnatfind and gnatxref}.
24018
24019Omitting the pattern is equivalent to specifying @code{*}, which
24020will match any entity. Note that if you do not provide a pattern, you
24021have to provide both a sourcefile and a line.
24022
24023Entity names are given in Latin-1, with uppercase/lowercase equivalence
24024for matching purposes. At the current time there is no support for
240258-bit codes other than Latin-1, or for wide characters in identifiers.
24026
24027@item @emph{sourcefile}
24028
24029@cite{gnatfind} will look for references, bodies or declarations
24030of symbols referenced in @code{sourcefile}, at line @cite{line}
24031and column @cite{column}. See @ref{1e1,,Examples of gnatfind Usage}
24032for syntax examples.
24033
24034@item @emph{line}
24035
24036A decimal integer identifying the line number containing
24037the reference to the entity (or entities) to be located.
24038
24039@item @emph{column}
24040
24041A decimal integer identifying the exact location on the
24042line of the first character of the identifier for the
24043entity reference. Columns are numbered from 1.
24044
24045@item @emph{file1 file2 ...}
24046
24047The search will be restricted to these source files. If none are given, then
24048the search will be conducted for every library file in the search path.
24049These files must appear only after the pattern or sourcefile.
24050
24051These file names are considered to be regular expressions, so for instance
24052specifying @code{source*.adb} is the same as giving every file in the current
24053directory whose name starts with @code{source} and whose extension is
24054@code{adb}.
24055
24056The location of the spec of the entity will always be displayed, even if it
24057isn't in one of @code{file1}, @code{file2}, ... The
24058occurrences of the entity in the separate units of the ones given on the
24059command line will also be displayed.
24060
24061Note that if you specify at least one file in this part, @cite{gnatfind} may
24062sometimes not be able to find the body of the subprograms.
24063@end table
24064
24065At least one of 'sourcefile' or 'pattern' has to be present on
24066the command line.
24067
24068The following switches are available:
24069
24070@geindex --version (gnatfind)
24071
24072
24073@table @asis
24074
24075@item @code{--version}
24076
24077Display Copyright and version, then exit disregarding all other options.
24078@end table
24079
24080@geindex --help (gnatfind)
24081
24082
24083@table @asis
24084
24085@item @code{-help}
24086
24087If @emph{--version} was not used, display usage, then exit disregarding
24088all other options.
24089@end table
24090
24091@geindex -a (gnatfind)
24092
24093
24094@table @asis
24095
24096@item @code{a}
24097
24098If this switch is present, @cite{gnatfind} and @cite{gnatxref} will parse
24099the read-only files found in the library search path. Otherwise, these files
24100will be ignored. This option can be used to protect Gnat sources or your own
24101libraries from being parsed, thus making @cite{gnatfind} and @cite{gnatxref}
24102much faster, and their output much smaller. Read-only here refers to access
24103or permission status in the file system for the current user.
24104@end table
24105
24106@geindex -aIDIR (gnatfind)
24107
24108
24109@table @asis
24110
24111@item @code{aI@emph{DIR}}
24112
24113When looking for source files also look in directory DIR. The order in which
24114source file search is undertaken is the same as for @emph{gnatmake}.
24115@end table
24116
24117@geindex -aODIR (gnatfind)
24118
24119
24120@table @asis
24121
24122@item @code{aO@emph{DIR}}
24123
24124When searching for library and object files, look in directory
24125DIR. The order in which library files are searched is the same as for
24126@emph{gnatmake}.
24127@end table
24128
24129@geindex -nostdinc (gnatfind)
24130
24131
24132@table @asis
24133
24134@item @code{nostdinc}
24135
24136Do not look for sources in the system default directory.
24137@end table
24138
24139@geindex -nostdlib (gnatfind)
24140
24141
24142@table @asis
24143
24144@item @code{nostdlib}
24145
24146Do not look for library files in the system default directory.
24147@end table
24148
24149@geindex --ext (gnatfind)
24150
24151
24152@table @asis
24153
24154@item @code{-ext=@emph{extension}}
24155
24156Specify an alternate ali file extension. The default is @cite{ali} and other
24157extensions (e.g. @cite{gli} for C/C++ sources when using @emph{-fdump-xref})
24158may be specified via this switch. Note that if this switch overrides the
24159default, which means that only the new extension will be considered.
24160@end table
24161
24162@geindex --RTS (gnatfind)
24163
24164
24165@table @asis
24166
24167@item @code{-RTS=@emph{rts-path}}
24168
24169Specifies the default location of the runtime library. Same meaning as the
24170equivalent @emph{gnatmake} flag (@ref{df,,Switches for gnatmake}).
24171@end table
24172
24173@geindex -d (gnatfind)
24174
24175
24176@table @asis
24177
24178@item @code{d}
24179
24180If this switch is set, then @cite{gnatfind} will output the parent type
24181reference for each matching derived types.
24182@end table
24183
24184@geindex -e (gnatfind)
24185
24186
24187@table @asis
24188
24189@item @code{e}
24190
24191By default, @cite{gnatfind} accept the simple regular expression set for
24192@cite{pattern}. If this switch is set, then the pattern will be
24193considered as full Unix-style regular expression.
24194@end table
24195
24196@geindex -f (gnatfind)
24197
24198
24199@table @asis
24200
24201@item @code{f}
24202
24203If this switch is set, the output file names will be preceded by their
24204directory (if the file was found in the search path). If this switch is
24205not set, the directory will not be printed.
24206@end table
24207
24208@geindex -g (gnatfind)
24209
24210
24211@table @asis
24212
24213@item @code{g}
24214
24215If this switch is set, information is output only for library-level
24216entities, ignoring local entities. The use of this switch may accelerate
24217@cite{gnatfind} and @cite{gnatxref}.
24218@end table
24219
24220@geindex -IDIR (gnatfind)
24221
24222
24223@table @asis
24224
24225@item @code{I@emph{DIR}}
24226
24227Equivalent to @code{-aODIR -aIDIR}.
24228@end table
24229
24230@geindex -pFILE (gnatfind)
24231
24232
24233@table @asis
24234
24235@item @code{p@emph{FILE}}
24236
24237Specify a project file (@ref{b,,GNAT Project Manager}) to use.
24238By default, @cite{gnatxref} and @cite{gnatfind} will try to locate a
24239project file in the current directory.
24240
24241If a project file is either specified or found by the tools, then the content
24242of the source directory and object directory lines are added as if they
24243had been specified respectively by @code{-aI} and
24244@code{-aO}.
24245@end table
24246
24247@geindex -r (gnatfind)
24248
24249
24250@table @asis
24251
24252@item @code{r}
24253
24254By default, @cite{gnatfind} will output only the information about the
24255declaration, body or type completion of the entities. If this switch is
24256set, the @cite{gnatfind} will locate every reference to the entities in
24257the files specified on the command line (or in every file in the search
24258path if no file is given on the command line).
24259@end table
24260
24261@geindex -s (gnatfind)
24262
24263
24264@table @asis
24265
24266@item @code{s}
24267
24268If this switch is set, then @cite{gnatfind} will output the content
24269of the Ada source file lines were the entity was found.
24270@end table
24271
24272@geindex -t (gnatfind)
24273
24274
24275@table @asis
24276
24277@item @code{t}
24278
24279If this switch is set, then @cite{gnatfind} will output the type hierarchy for
24280the specified type. It act like -d option but recursively from parent
24281type to parent type. When this switch is set it is not possible to
24282specify more than one file.
24283@end table
24284
24285All these switches may be in any order on the command line, and may even
24286appear after the file names. They need not be separated by spaces, thus
24287you can say @code{gnatxref -ag} instead of
24288@code{gnatxref -a -g}.
24289
24290As stated previously, gnatfind will search in every directory in the
24291search path. You can force it to look only in the current directory if
24292you specify @cite{*} at the end of the command line.
24293
24294@node Project Files for gnatxref and gnatfind,Regular Expressions in gnatfind and gnatxref,gnatfind Switches,The Cross-Referencing Tools gnatxref and gnatfind
24295@anchor{gnat_ugn/gnat_utility_programs project-files-for-gnatxref-and-gnatfind}@anchor{1e2}@anchor{gnat_ugn/gnat_utility_programs id12}@anchor{1e3}
24296@subsection Project Files for @emph{gnatxref} and @emph{gnatfind}
24297
24298
24299Project files allow a programmer to specify how to compile its
24300application, where to find sources, etc.  These files are used
24301primarily by GPS, but they can also be used
24302by the two tools @cite{gnatxref} and @cite{gnatfind}.
24303
24304A project file name must end with @code{.gpr}. If a single one is
24305present in the current directory, then @cite{gnatxref} and @cite{gnatfind} will
24306extract the information from it. If multiple project files are found, none of
24307them is read, and you have to use the @code{-p} switch to specify the one
24308you want to use.
24309
24310The following lines can be included, even though most of them have default
24311values which can be used in most cases.
24312The lines can be entered in any order in the file.
24313Except for @code{src_dir} and @code{obj_dir}, you can only have one instance of
24314each line. If you have multiple instances, only the last one is taken into
24315account.
24316
24317
24318@itemize *
24319
24320@item 
24321
24322@table @asis
24323
24324@item @emph{src_dir=DIR}
24325
24326[default: @cite{"./"}].
24327Specifies a directory where to look for source files. Multiple @cite{src_dir}
24328lines can be specified and they will be searched in the order they
24329are specified.
24330@end table
24331
24332@item 
24333
24334@table @asis
24335
24336@item @emph{obj_dir=DIR}
24337
24338[default: @cite{"./"}].
24339Specifies a directory where to look for object and library files. Multiple
24340@cite{obj_dir} lines can be specified, and they will be searched in the order
24341they are specified
24342@end table
24343
24344@item 
24345
24346@table @asis
24347
24348@item @emph{comp_opt=SWITCHES}
24349
24350[default: @cite{""}].
24351Creates a variable which can be referred to subsequently by using
24352the @cite{$@{comp_opt@}} notation. This is intended to store the default
24353switches given to @emph{gnatmake} and @emph{gcc}.
24354@end table
24355
24356@item 
24357
24358@table @asis
24359
24360@item @emph{bind_opt=SWITCHES}
24361
24362[default: @cite{""}].
24363Creates a variable which can be referred to subsequently by using
24364the @code{$@emph{bind_opt}} notation. This is intended to store the default
24365switches given to @emph{gnatbind}.
24366@end table
24367
24368@item 
24369
24370@table @asis
24371
24372@item @emph{link_opt=SWITCHES}
24373
24374[default: @cite{""}].
24375Creates a variable which can be referred to subsequently by using
24376the @code{$@emph{link_opt}} notation. This is intended to store the default
24377switches given to @emph{gnatlink}.
24378@end table
24379
24380@item 
24381
24382@table @asis
24383
24384@item @emph{main=EXECUTABLE}
24385
24386[default: @cite{""}].
24387Specifies the name of the executable for the application. This variable can
24388be referred to in the following lines by using the @code{@emph{$@{main}} notation.
24389@end table
24390
24391@item 
24392
24393@table @asis
24394
24395@item @emph{comp_cmd=COMMAND}
24396
24397[default: @cite{"gcc -c -I$@{src_dir@} -g -gnatq"}].
24398Specifies the command used to compile a single file in the application.
24399@end table
24400
24401@item 
24402
24403@table @asis
24404
24405@item @emph{make_cmd=COMMAND}
24406
24407[default: @cite{"gnatmake $@{main@} -aI$@{src_dir@} -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@} -bargs $@{bind_opt@} -largs $@{link_opt@}"}].
24408Specifies the command used to recompile the whole application.
24409@end table
24410
24411@item 
24412
24413@table @asis
24414
24415@item @emph{run_cmd=COMMAND}
24416
24417[default: @cite{"$@{main@}"}].
24418Specifies the command used to run the application.
24419@end table
24420
24421@item 
24422
24423@table @asis
24424
24425@item @emph{debug_cmd=COMMAND}
24426
24427[default: @cite{"gdb $@{main@}"}].
24428Specifies the command used to debug the application
24429@end table
24430@end itemize
24431
24432@emph{gnatxref} and @emph{gnatfind} only take into account the
24433@cite{src_dir} and @cite{obj_dir} lines, and ignore the others.
24434
24435@node Regular Expressions in gnatfind and gnatxref,Examples of gnatxref Usage,Project Files for gnatxref and gnatfind,The Cross-Referencing Tools gnatxref and gnatfind
24436@anchor{gnat_ugn/gnat_utility_programs id13}@anchor{1e4}@anchor{gnat_ugn/gnat_utility_programs regular-expressions-in-gnatfind-and-gnatxref}@anchor{1e0}
24437@subsection Regular Expressions in @cite{gnatfind} and @cite{gnatxref}
24438
24439
24440As specified in the section about @emph{gnatfind}, the pattern can be a
24441regular expression. Two kinds of regular expressions
24442are recognized:
24443
24444
24445@itemize *
24446
24447@item 
24448
24449@table @asis
24450
24451@item @emph{Globbing pattern}
24452
24453These are the most common regular expression. They are the same as are
24454generally used in a Unix shell command line, or in a DOS session.
24455
24456Here is a more formal grammar:
24457
24458@example
24459regexp ::= term
24460term   ::= elmt            -- matches elmt
24461term   ::= elmt elmt       -- concatenation (elmt then elmt)
24462term   ::= *               -- any string of 0 or more characters
24463term   ::= ?               -- matches any character
24464term   ::= [char @{char@}]   -- matches any character listed
24465term   ::= [char - char]   -- matches any character in range
24466@end example
24467@end table
24468
24469@item 
24470
24471@table @asis
24472
24473@item @emph{Full regular expression}
24474
24475The second set of regular expressions is much more powerful. This is the
24476type of regular expressions recognized by utilities such as @code{grep}.
24477
24478The following is the form of a regular expression, expressed in same BNF
24479style as is found in the Ada Reference Manual:
24480
24481@example
24482regexp ::= term @{| term@}   -- alternation (term or term ...)
24483
24484term ::= item @{item@}       -- concatenation (item then item)
24485
24486item ::= elmt              -- match elmt
24487item ::= elmt *            -- zero or more elmt's
24488item ::= elmt +            -- one or more elmt's
24489item ::= elmt ?            -- matches elmt or nothing
24490
24491elmt ::= nschar            -- matches given character
24492elmt ::= [nschar @{nschar@}]   -- matches any character listed
24493elmt ::= [^ nschar @{nschar@}] -- matches any character not listed
24494elmt ::= [char - char]     -- matches chars in given range
24495elmt ::= \\ char            -- matches given character
24496elmt ::= .                 -- matches any single character
24497elmt ::= ( regexp )        -- parens used for grouping
24498
24499char ::= any character, including special characters
24500nschar ::= any character except ()[].*+?^
24501@end example
24502
24503Here are a few examples:
24504
24505@quotation
24506
24507
24508@table @asis
24509
24510@item @code{abcde|fghi}
24511
24512will match any of the two strings @code{abcde} and @code{fghi},
24513
24514@item @code{abc*d}
24515
24516will match any string like @code{abd}, @code{abcd}, @code{abccd},
24517@code{abcccd}, and so on,
24518
24519@item @code{[a-z]+}
24520
24521will match any string which has only lowercase characters in it (and at
24522least one character.
24523@end table
24524@end quotation
24525@end table
24526@end itemize
24527
24528@node Examples of gnatxref Usage,Examples of gnatfind Usage,Regular Expressions in gnatfind and gnatxref,The Cross-Referencing Tools gnatxref and gnatfind
24529@anchor{gnat_ugn/gnat_utility_programs examples-of-gnatxref-usage}@anchor{1dd}@anchor{gnat_ugn/gnat_utility_programs id14}@anchor{1e5}
24530@subsection Examples of @cite{gnatxref} Usage
24531
24532
24533@menu
24534* General Usage:: 
24535* Using gnatxref with vi:: 
24536
24537@end menu
24538
24539@node General Usage,Using gnatxref with vi,,Examples of gnatxref Usage
24540@anchor{gnat_ugn/gnat_utility_programs general-usage}@anchor{1e6}
24541@subsubsection General Usage
24542
24543
24544For the following examples, we will consider the following units:
24545
24546@quotation
24547
24548@example
24549main.ads:
245501: with Bar;
245512: package Main is
245523:     procedure Foo (B : in Integer);
245534:     C : Integer;
245545: private
245556:     D : Integer;
245567: end Main;
24557
24558main.adb:
245591: package body Main is
245602:     procedure Foo (B : in Integer) is
245613:     begin
245624:        C := B;
245635:        D := B;
245646:        Bar.Print (B);
245657:        Bar.Print (C);
245668:     end Foo;
245679: end Main;
24568
24569bar.ads:
245701: package Bar is
245712:     procedure Print (B : Integer);
245723: end bar;
24573@end example
24574@end quotation
24575
24576The first thing to do is to recompile your application (for instance, in
24577that case just by doing a @code{gnatmake main}, so that GNAT generates
24578the cross-referencing information.
24579You can then issue any of the following commands:
24580
24581@quotation
24582
24583
24584@itemize *
24585
24586@item 
24587@code{gnatxref main.adb}
24588@cite{gnatxref} generates cross-reference information for main.adb
24589and every unit 'with'ed by main.adb.
24590
24591The output would be:
24592
24593@quotation
24594
24595@example
24596B                                                      Type: Integer
24597  Decl: bar.ads           2:22
24598B                                                      Type: Integer
24599  Decl: main.ads          3:20
24600  Body: main.adb          2:20
24601  Ref:  main.adb          4:13     5:13     6:19
24602Bar                                                    Type: Unit
24603  Decl: bar.ads           1:9
24604  Ref:  main.adb          6:8      7:8
24605       main.ads           1:6
24606C                                                      Type: Integer
24607  Decl: main.ads          4:5
24608  Modi: main.adb          4:8
24609  Ref:  main.adb          7:19
24610D                                                      Type: Integer
24611  Decl: main.ads          6:5
24612  Modi: main.adb          5:8
24613Foo                                                    Type: Unit
24614  Decl: main.ads          3:15
24615  Body: main.adb          2:15
24616Main                                                    Type: Unit
24617  Decl: main.ads          2:9
24618  Body: main.adb          1:14
24619Print                                                   Type: Unit
24620  Decl: bar.ads           2:15
24621  Ref:  main.adb          6:12     7:12
24622@end example
24623@end quotation
24624
24625This shows that the entity @cite{Main} is declared in main.ads, line 2, column 9,
24626its body is in main.adb, line 1, column 14 and is not referenced any where.
24627
24628The entity @cite{Print} is declared in bar.ads, line 2, column 15 and it
24629is referenced in main.adb, line 6 column 12 and line 7 column 12.
24630
24631@item 
24632@code{gnatxref package1.adb package2.ads}
24633@cite{gnatxref} will generates cross-reference information for
24634package1.adb, package2.ads and any other package 'with'ed by any
24635of these.
24636@end itemize
24637@end quotation
24638
24639@node Using gnatxref with vi,,General Usage,Examples of gnatxref Usage
24640@anchor{gnat_ugn/gnat_utility_programs using-gnatxref-with-vi}@anchor{1e7}
24641@subsubsection Using gnatxref with vi
24642
24643
24644@cite{gnatxref} can generate a tags file output, which can be used
24645directly from @emph{vi}. Note that the standard version of @emph{vi}
24646will not work properly with overloaded symbols. Consider using another
24647free implementation of @emph{vi}, such as @emph{vim}.
24648
24649@quotation
24650
24651@example
24652$ gnatxref -v gnatfind.adb > tags
24653@end example
24654@end quotation
24655
24656The following command will generate the tags file for @cite{gnatfind} itself
24657(if the sources are in the search path!):
24658
24659@quotation
24660
24661@example
24662$ gnatxref -v gnatfind.adb > tags
24663@end example
24664@end quotation
24665
24666From @emph{vi}, you can then use the command @code{:tag @emph{entity}}
24667(replacing @cite{entity} by whatever you are looking for), and vi will
24668display a new file with the corresponding declaration of entity.
24669
24670@node Examples of gnatfind Usage,,Examples of gnatxref Usage,The Cross-Referencing Tools gnatxref and gnatfind
24671@anchor{gnat_ugn/gnat_utility_programs id15}@anchor{1e8}@anchor{gnat_ugn/gnat_utility_programs examples-of-gnatfind-usage}@anchor{1e1}
24672@subsection Examples of @cite{gnatfind} Usage
24673
24674
24675
24676@itemize *
24677
24678@item 
24679@code{gnatfind -f xyz:main.adb}
24680Find declarations for all entities xyz referenced at least once in
24681main.adb. The references are search in every library file in the search
24682path.
24683
24684The directories will be printed as well (as the @code{-f}
24685switch is set)
24686
24687The output will look like:
24688
24689@quotation
24690
24691@example
24692directory/main.ads:106:14: xyz <= declaration
24693directory/main.adb:24:10: xyz <= body
24694directory/foo.ads:45:23: xyz <= declaration
24695@end example
24696@end quotation
24697
24698I.e., one of the entities xyz found in main.adb is declared at
24699line 12 of main.ads (and its body is in main.adb), and another one is
24700declared at line 45 of foo.ads
24701
24702@item 
24703@code{gnatfind -fs xyz:main.adb}
24704This is the same command as the previous one, but @cite{gnatfind} will
24705display the content of the Ada source file lines.
24706
24707The output will look like:
24708
24709@example
24710directory/main.ads:106:14: xyz <= declaration
24711   procedure xyz;
24712directory/main.adb:24:10: xyz <= body
24713   procedure xyz is
24714directory/foo.ads:45:23: xyz <= declaration
24715   xyz : Integer;
24716@end example
24717
24718This can make it easier to find exactly the location your are looking
24719for.
24720
24721@item 
24722@code{gnatfind -r "*x*":main.ads:123 foo.adb}
24723Find references to all entities containing an x that are
24724referenced on line 123 of main.ads.
24725The references will be searched only in main.ads and foo.adb.
24726
24727@item 
24728@code{gnatfind main.ads:123}
24729Find declarations and bodies for all entities that are referenced on
24730line 123 of main.ads.
24731
24732This is the same as @code{gnatfind "*":main.adb:123`}
24733
24734@item 
24735@code{gnatfind mydir/main.adb:123:45}
24736Find the declaration for the entity referenced at column 45 in
24737line 123 of file main.adb in directory mydir. Note that it
24738is usual to omit the identifier name when the column is given,
24739since the column position identifies a unique reference.
24740
24741The column has to be the beginning of the identifier, and should not
24742point to any character in the middle of the identifier.
24743@end itemize
24744
24745@node The Ada to HTML Converter gnathtml,,The Cross-Referencing Tools gnatxref and gnatfind,GNAT Utility Programs
24746@anchor{gnat_ugn/gnat_utility_programs the-ada-to-html-converter-gnathtml}@anchor{25}@anchor{gnat_ugn/gnat_utility_programs id16}@anchor{1e9}
24747@section The Ada to HTML Converter @cite{gnathtml}
24748
24749
24750@geindex gnathtml
24751
24752@emph{gnathtml} is a Perl script that allows Ada source files to be browsed using
24753standard Web browsers. For installation information, see @ref{1ea,,Installing gnathtml}.
24754
24755Ada reserved keywords are highlighted in a bold font and Ada comments in
24756a blue font. Unless your program was compiled with the gcc @emph{-gnatx}
24757switch to suppress the generation of cross-referencing information, user
24758defined variables and types will appear in a different color; you will
24759be able to click on any identifier and go to its declaration.
24760
24761@menu
24762* Invoking gnathtml:: 
24763* Installing gnathtml:: 
24764
24765@end menu
24766
24767@node Invoking gnathtml,Installing gnathtml,,The Ada to HTML Converter gnathtml
24768@anchor{gnat_ugn/gnat_utility_programs invoking-gnathtml}@anchor{1eb}@anchor{gnat_ugn/gnat_utility_programs id17}@anchor{1ec}
24769@subsection Invoking @emph{gnathtml}
24770
24771
24772The command line is as follows:
24773
24774@quotation
24775
24776@example
24777$ perl gnathtml.pl [`switches`] `ada-files`
24778@end example
24779@end quotation
24780
24781You can specify as many Ada files as you want. @cite{gnathtml} will generate
24782an html file for every ada file, and a global file called @code{index.htm}.
24783This file is an index of every identifier defined in the files.
24784
24785The following switches are available:
24786
24787@geindex -83 (gnathtml)
24788
24789
24790@table @asis
24791
24792@item @code{83}
24793
24794Only the Ada 83 subset of keywords will be highlighted.
24795@end table
24796
24797@geindex -cc (gnathtml)
24798
24799
24800@table @asis
24801
24802@item @code{cc @emph{color}}
24803
24804This option allows you to change the color used for comments. The default
24805value is green. The color argument can be any name accepted by html.
24806@end table
24807
24808@geindex -d (gnathtml)
24809
24810
24811@table @asis
24812
24813@item @code{d}
24814
24815If the Ada files depend on some other files (for instance through
24816@cite{with} clauses, the latter files will also be converted to html.
24817Only the files in the user project will be converted to html, not the files
24818in the run-time library itself.
24819@end table
24820
24821@geindex -D (gnathtml)
24822
24823
24824@table @asis
24825
24826@item @code{D}
24827
24828This command is the same as @emph{-d} above, but @emph{gnathtml} will
24829also look for files in the run-time library, and generate html files for them.
24830@end table
24831
24832@geindex -ext (gnathtml)
24833
24834
24835@table @asis
24836
24837@item @code{ext @emph{extension}}
24838
24839This option allows you to change the extension of the generated HTML files.
24840If you do not specify an extension, it will default to @code{htm}.
24841@end table
24842
24843@geindex -f (gnathtml)
24844
24845
24846@table @asis
24847
24848@item @code{f}
24849
24850By default, gnathtml will generate html links only for global entities
24851('with'ed units, global variables and types,...).  If you specify
24852@emph{-f} on the command line, then links will be generated for local
24853entities too.
24854@end table
24855
24856@geindex -l (gnathtml)
24857
24858
24859@table @asis
24860
24861@item @code{l @emph{number}}
24862
24863If this switch is provided and @cite{number} is not 0, then
24864@cite{gnathtml} will number the html files every @cite{number} line.
24865@end table
24866
24867@geindex -I (gnathtml)
24868
24869
24870@table @asis
24871
24872@item @code{I @emph{dir}}
24873
24874Specify a directory to search for library files (@code{.ALI} files) and
24875source files. You can provide several -I switches on the command line,
24876and the directories will be parsed in the order of the command line.
24877@end table
24878
24879@geindex -o (gnathtml)
24880
24881
24882@table @asis
24883
24884@item @code{o @emph{dir}}
24885
24886Specify the output directory for html files. By default, gnathtml will
24887saved the generated html files in a subdirectory named @code{html/}.
24888@end table
24889
24890@geindex -p (gnathtml)
24891
24892
24893@table @asis
24894
24895@item @code{p @emph{file}}
24896
24897If you are using Emacs and the most recent Emacs Ada mode, which provides
24898a full Integrated Development Environment for compiling, checking,
24899running and debugging applications, you may use @code{.gpr} files
24900to give the directories where Emacs can find sources and object files.
24901
24902Using this switch, you can tell gnathtml to use these files.
24903This allows you to get an html version of your application, even if it
24904is spread over multiple directories.
24905@end table
24906
24907@geindex -sc (gnathtml)
24908
24909
24910@table @asis
24911
24912@item @code{sc @emph{color}}
24913
24914This switch allows you to change the color used for symbol
24915definitions.
24916The default value is red. The color argument can be any name accepted by html.
24917@end table
24918
24919@geindex -t (gnathtml)
24920
24921
24922@table @asis
24923
24924@item @code{t @emph{file}}
24925
24926This switch provides the name of a file. This file contains a list of
24927file names to be converted, and the effect is exactly as though they had
24928appeared explicitly on the command line. This
24929is the recommended way to work around the command line length limit on some
24930systems.
24931@end table
24932
24933@node Installing gnathtml,,Invoking gnathtml,The Ada to HTML Converter gnathtml
24934@anchor{gnat_ugn/gnat_utility_programs installing-gnathtml}@anchor{1ea}@anchor{gnat_ugn/gnat_utility_programs id18}@anchor{1ed}
24935@subsection Installing @cite{gnathtml}
24936
24937
24938@cite{Perl} needs to be installed on your machine to run this script.
24939@cite{Perl} is freely available for almost every architecture and
24940operating system via the Internet.
24941
24942On Unix systems, you  may want to modify  the  first line of  the script
24943@cite{gnathtml},  to explicitly  specify  where Perl
24944is located. The syntax of this line is:
24945
24946@quotation
24947
24948@example
24949#!full_path_name_to_perl
24950@end example
24951@end quotation
24952
24953Alternatively, you may run the script using the following command line:
24954
24955@quotation
24956
24957@example
24958$ perl gnathtml.pl [`switches`] `files`
24959@end example
24960@end quotation
24961
24962@c -- +---------------------------------------------------------------------+
24963
24964@c -- | The following sections are present only in the PRO and GPL editions |
24965
24966@c -- +---------------------------------------------------------------------+
24967
24968
24969
24970
24971
24972
24973
24974@c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
24975
24976@node GNAT and Program Execution,Platform-Specific Information,GNAT Utility Programs,Top
24977@anchor{gnat_ugn/gnat_and_program_execution gnat-and-program-execution}@anchor{e}@anchor{gnat_ugn/gnat_and_program_execution doc}@anchor{1ee}@anchor{gnat_ugn/gnat_and_program_execution id1}@anchor{1ef}
24978@chapter GNAT and Program Execution
24979
24980
24981This chapter covers several topics:
24982
24983
24984@itemize *
24985
24986@item 
24987@ref{1f0,,Running and Debugging Ada Programs}
24988
24989@item 
24990@ref{1f1,,Code Coverage and Profiling}
24991
24992@item 
24993@ref{1f2,,Improving Performance}
24994
24995@item 
24996@ref{1f3,,Overflow Check Handling in GNAT}
24997
24998@item 
24999@ref{1f4,,Performing Dimensionality Analysis in GNAT}
25000
25001@item 
25002@ref{1f5,,Stack Related Facilities}
25003
25004@item 
25005@ref{1f6,,Memory Management Issues}
25006@end itemize
25007
25008@menu
25009* Running and Debugging Ada Programs:: 
25010* Code Coverage and Profiling:: 
25011* Improving Performance:: 
25012* Overflow Check Handling in GNAT:: 
25013* Performing Dimensionality Analysis in GNAT:: 
25014* Stack Related Facilities:: 
25015* Memory Management Issues:: 
25016
25017@end menu
25018
25019@node Running and Debugging Ada Programs,Code Coverage and Profiling,,GNAT and Program Execution
25020@anchor{gnat_ugn/gnat_and_program_execution id2}@anchor{1f0}@anchor{gnat_ugn/gnat_and_program_execution running-and-debugging-ada-programs}@anchor{26}
25021@section Running and Debugging Ada Programs
25022
25023
25024@geindex Debugging
25025
25026This section discusses how to debug Ada programs.
25027
25028An incorrect Ada program may be handled in three ways by the GNAT compiler:
25029
25030
25031@itemize *
25032
25033@item 
25034The illegality may be a violation of the static semantics of Ada. In
25035that case GNAT diagnoses the constructs in the program that are illegal.
25036It is then a straightforward matter for the user to modify those parts of
25037the program.
25038
25039@item 
25040The illegality may be a violation of the dynamic semantics of Ada. In
25041that case the program compiles and executes, but may generate incorrect
25042results, or may terminate abnormally with some exception.
25043
25044@item 
25045When presented with a program that contains convoluted errors, GNAT
25046itself may terminate abnormally without providing full diagnostics on
25047the incorrect user program.
25048@end itemize
25049
25050@geindex Debugger
25051
25052@geindex gdb
25053
25054@menu
25055* The GNAT Debugger GDB:: 
25056* Running GDB:: 
25057* Introduction to GDB Commands:: 
25058* Using Ada Expressions:: 
25059* Calling User-Defined Subprograms:: 
25060* Using the next Command in a Function:: 
25061* Stopping When Ada Exceptions Are Raised:: 
25062* Ada Tasks:: 
25063* Debugging Generic Units:: 
25064* Remote Debugging with gdbserver:: 
25065* GNAT Abnormal Termination or Failure to Terminate:: 
25066* Naming Conventions for GNAT Source Files:: 
25067* Getting Internal Debugging Information:: 
25068* Stack Traceback:: 
25069
25070@end menu
25071
25072@node The GNAT Debugger GDB,Running GDB,,Running and Debugging Ada Programs
25073@anchor{gnat_ugn/gnat_and_program_execution the-gnat-debugger-gdb}@anchor{1f7}@anchor{gnat_ugn/gnat_and_program_execution id3}@anchor{1f8}
25074@subsection The GNAT Debugger GDB
25075
25076
25077@cite{GDB} is a general purpose, platform-independent debugger that
25078can be used to debug mixed-language programs compiled with @emph{gcc},
25079and in particular is capable of debugging Ada programs compiled with
25080GNAT. The latest versions of @cite{GDB} are Ada-aware and can handle
25081complex Ada data structures.
25082
25083See @cite{Debugging with GDB},
25084for full details on the usage of @cite{GDB}, including a section on
25085its usage on programs. This manual should be consulted for full
25086details. The section that follows is a brief introduction to the
25087philosophy and use of @cite{GDB}.
25088
25089When GNAT programs are compiled, the compiler optionally writes debugging
25090information into the generated object file, including information on
25091line numbers, and on declared types and variables. This information is
25092separate from the generated code. It makes the object files considerably
25093larger, but it does not add to the size of the actual executable that
25094will be loaded into memory, and has no impact on run-time performance. The
25095generation of debug information is triggered by the use of the
25096-g switch in the @emph{gcc} or @emph{gnatmake} command
25097used to carry out the compilations. It is important to emphasize that
25098the use of these options does not change the generated code.
25099
25100The debugging information is written in standard system formats that
25101are used by many tools, including debuggers and profilers. The format
25102of the information is typically designed to describe C types and
25103semantics, but GNAT implements a translation scheme which allows full
25104details about Ada types and variables to be encoded into these
25105standard C formats. Details of this encoding scheme may be found in
25106the file exp_dbug.ads in the GNAT source distribution. However, the
25107details of this encoding are, in general, of no interest to a user,
25108since @cite{GDB} automatically performs the necessary decoding.
25109
25110When a program is bound and linked, the debugging information is
25111collected from the object files, and stored in the executable image of
25112the program. Again, this process significantly increases the size of
25113the generated executable file, but it does not increase the size of
25114the executable program itself. Furthermore, if this program is run in
25115the normal manner, it runs exactly as if the debug information were
25116not present, and takes no more actual memory.
25117
25118However, if the program is run under control of @cite{GDB}, the
25119debugger is activated.  The image of the program is loaded, at which
25120point it is ready to run.  If a run command is given, then the program
25121will run exactly as it would have if @cite{GDB} were not present. This
25122is a crucial part of the @cite{GDB} design philosophy.  @cite{GDB} is
25123entirely non-intrusive until a breakpoint is encountered.  If no
25124breakpoint is ever hit, the program will run exactly as it would if no
25125debugger were present. When a breakpoint is hit, @cite{GDB} accesses
25126the debugging information and can respond to user commands to inspect
25127variables, and more generally to report on the state of execution.
25128
25129@node Running GDB,Introduction to GDB Commands,The GNAT Debugger GDB,Running and Debugging Ada Programs
25130@anchor{gnat_ugn/gnat_and_program_execution id4}@anchor{1f9}@anchor{gnat_ugn/gnat_and_program_execution running-gdb}@anchor{1fa}
25131@subsection Running GDB
25132
25133
25134This section describes how to initiate the debugger.
25135
25136The debugger can be launched from a @cite{GPS} menu or
25137directly from the command line. The description below covers the latter use.
25138All the commands shown can be used in the @cite{GPS} debug console window,
25139but there are usually more GUI-based ways to achieve the same effect.
25140
25141The command to run @cite{GDB} is
25142
25143@quotation
25144
25145@example
25146$ gdb program
25147@end example
25148@end quotation
25149
25150where @cite{program} is the name of the executable file. This
25151activates the debugger and results in a prompt for debugger commands.
25152The simplest command is simply @cite{run}, which causes the program to run
25153exactly as if the debugger were not present. The following section
25154describes some of the additional commands that can be given to @cite{GDB}.
25155
25156@node Introduction to GDB Commands,Using Ada Expressions,Running GDB,Running and Debugging Ada Programs
25157@anchor{gnat_ugn/gnat_and_program_execution introduction-to-gdb-commands}@anchor{1fb}@anchor{gnat_ugn/gnat_and_program_execution id5}@anchor{1fc}
25158@subsection Introduction to GDB Commands
25159
25160
25161@cite{GDB} contains a large repertoire of commands.
25162See @cite{Debugging with GDB} for extensive documentation on the use
25163of these commands, together with examples of their use. Furthermore,
25164the command @emph{help} invoked from within GDB activates a simple help
25165facility which summarizes the available commands and their options.
25166In this section we summarize a few of the most commonly
25167used commands to give an idea of what @cite{GDB} is about. You should create
25168a simple program with debugging information and experiment with the use of
25169these @cite{GDB} commands on the program as you read through the
25170following section.
25171
25172
25173@itemize *
25174
25175@item 
25176
25177@table @asis
25178
25179@item @emph{set args `arguments`}
25180
25181The @cite{arguments} list above is a list of arguments to be passed to
25182the program on a subsequent run command, just as though the arguments
25183had been entered on a normal invocation of the program. The @cite{set args}
25184command is not needed if the program does not require arguments.
25185@end table
25186
25187@item 
25188
25189@table @asis
25190
25191@item @emph{run}
25192
25193The @cite{run} command causes execution of the program to start from
25194the beginning. If the program is already running, that is to say if
25195you are currently positioned at a breakpoint, then a prompt will ask
25196for confirmation that you want to abandon the current execution and
25197restart.
25198@end table
25199
25200@item 
25201
25202@table @asis
25203
25204@item @emph{breakpoint `location`}
25205
25206The breakpoint command sets a breakpoint, that is to say a point at which
25207execution will halt and @cite{GDB} will await further
25208commands. @cite{location} is
25209either a line number within a file, given in the format @cite{file:linenumber},
25210or it is the name of a subprogram. If you request that a breakpoint be set on
25211a subprogram that is overloaded, a prompt will ask you to specify on which of
25212those subprograms you want to breakpoint. You can also
25213specify that all of them should be breakpointed. If the program is run
25214and execution encounters the breakpoint, then the program
25215stops and @cite{GDB} signals that the breakpoint was encountered by
25216printing the line of code before which the program is halted.
25217@end table
25218
25219@item 
25220
25221@table @asis
25222
25223@item @emph{catch exception `name`}
25224
25225This command causes the program execution to stop whenever exception
25226@cite{name} is raised.  If @cite{name} is omitted, then the execution is
25227suspended when any exception is raised.
25228@end table
25229
25230@item 
25231
25232@table @asis
25233
25234@item @emph{print `expression`}
25235
25236This will print the value of the given expression. Most simple
25237Ada expression formats are properly handled by @cite{GDB}, so the expression
25238can contain function calls, variables, operators, and attribute references.
25239@end table
25240
25241@item 
25242
25243@table @asis
25244
25245@item @emph{continue}
25246
25247Continues execution following a breakpoint, until the next breakpoint or the
25248termination of the program.
25249@end table
25250
25251@item 
25252
25253@table @asis
25254
25255@item @emph{step}
25256
25257Executes a single line after a breakpoint. If the next statement
25258is a subprogram call, execution continues into (the first statement of)
25259the called subprogram.
25260@end table
25261
25262@item 
25263
25264@table @asis
25265
25266@item @emph{next}
25267
25268Executes a single line. If this line is a subprogram call, executes and
25269returns from the call.
25270@end table
25271
25272@item 
25273
25274@table @asis
25275
25276@item @emph{list}
25277
25278Lists a few lines around the current source location. In practice, it
25279is usually more convenient to have a separate edit window open with the
25280relevant source file displayed. Successive applications of this command
25281print subsequent lines. The command can be given an argument which is a
25282line number, in which case it displays a few lines around the specified one.
25283@end table
25284
25285@item 
25286
25287@table @asis
25288
25289@item @emph{backtrace}
25290
25291Displays a backtrace of the call chain. This command is typically
25292used after a breakpoint has occurred, to examine the sequence of calls that
25293leads to the current breakpoint. The display includes one line for each
25294activation record (frame) corresponding to an active subprogram.
25295@end table
25296
25297@item 
25298
25299@table @asis
25300
25301@item @emph{up}
25302
25303At a breakpoint, @cite{GDB} can display the values of variables local
25304to the current frame. The command @cite{up} can be used to
25305examine the contents of other active frames, by moving the focus up
25306the stack, that is to say from callee to caller, one frame at a time.
25307@end table
25308
25309@item 
25310
25311@table @asis
25312
25313@item @emph{down}
25314
25315Moves the focus of @cite{GDB} down from the frame currently being
25316examined to the frame of its callee (the reverse of the previous command),
25317@end table
25318
25319@item 
25320
25321@table @asis
25322
25323@item @emph{frame `n`}
25324
25325Inspect the frame with the given number. The value 0 denotes the frame
25326of the current breakpoint, that is to say the top of the call stack.
25327@end table
25328
25329@item 
25330
25331@table @asis
25332
25333@item @emph{kill}
25334
25335Kills the child process in which the program is running under GDB.
25336This may be useful for several purposes:
25337
25338
25339@itemize *
25340
25341@item 
25342It allows you to recompile and relink your program, since on many systems
25343you cannot regenerate an executable file while it is running in a process.
25344
25345@item 
25346You can run your program outside the debugger, on systems that do not
25347permit executing a program outside GDB while breakpoints are set
25348within GDB.
25349
25350@item 
25351It allows you to debug a core dump rather than a running process.
25352@end itemize
25353@end table
25354@end itemize
25355
25356The above list is a very short introduction to the commands that
25357@cite{GDB} provides. Important additional capabilities, including conditional
25358breakpoints, the ability to execute command sequences on a breakpoint,
25359the ability to debug at the machine instruction level and many other
25360features are described in detail in @cite{Debugging with GDB}.
25361Note that most commands can be abbreviated
25362(for example, c for continue, bt for backtrace).
25363
25364@node Using Ada Expressions,Calling User-Defined Subprograms,Introduction to GDB Commands,Running and Debugging Ada Programs
25365@anchor{gnat_ugn/gnat_and_program_execution id6}@anchor{1fd}@anchor{gnat_ugn/gnat_and_program_execution using-ada-expressions}@anchor{1fe}
25366@subsection Using Ada Expressions
25367
25368
25369@geindex Ada expressions (in gdb)
25370
25371@cite{GDB} supports a fairly large subset of Ada expression syntax, with some
25372extensions. The philosophy behind the design of this subset is
25373
25374@quotation
25375
25376
25377@itemize *
25378
25379@item 
25380That @cite{GDB} should provide basic literals and access to operations for
25381arithmetic, dereferencing, field selection, indexing, and subprogram calls,
25382leaving more sophisticated computations to subprograms written into the
25383program (which therefore may be called from @cite{GDB}).
25384
25385@item 
25386That type safety and strict adherence to Ada language restrictions
25387are not particularly relevant in a debugging context.
25388
25389@item 
25390That brevity is important to the @cite{GDB} user.
25391@end itemize
25392@end quotation
25393
25394Thus, for brevity, the debugger acts as if there were
25395implicit @cite{with} and @cite{use} clauses in effect for all user-written
25396packages, thus making it unnecessary to fully qualify most names with
25397their packages, regardless of context. Where this causes ambiguity,
25398@cite{GDB} asks the user's intent.
25399
25400For details on the supported Ada syntax, see @cite{Debugging with GDB}.
25401
25402@node Calling User-Defined Subprograms,Using the next Command in a Function,Using Ada Expressions,Running and Debugging Ada Programs
25403@anchor{gnat_ugn/gnat_and_program_execution id7}@anchor{1ff}@anchor{gnat_ugn/gnat_and_program_execution calling-user-defined-subprograms}@anchor{200}
25404@subsection Calling User-Defined Subprograms
25405
25406
25407An important capability of @cite{GDB} is the ability to call user-defined
25408subprograms while debugging. This is achieved simply by entering
25409a subprogram call statement in the form:
25410
25411@quotation
25412
25413@example
25414call subprogram-name (parameters)
25415@end example
25416@end quotation
25417
25418The keyword @cite{call} can be omitted in the normal case where the
25419@cite{subprogram-name} does not coincide with any of the predefined
25420@cite{GDB} commands.
25421
25422The effect is to invoke the given subprogram, passing it the
25423list of parameters that is supplied. The parameters can be expressions and
25424can include variables from the program being debugged. The
25425subprogram must be defined
25426at the library level within your program, and @cite{GDB} will call the
25427subprogram within the environment of your program execution (which
25428means that the subprogram is free to access or even modify variables
25429within your program).
25430
25431The most important use of this facility is in allowing the inclusion of
25432debugging routines that are tailored to particular data structures
25433in your program. Such debugging routines can be written to provide a suitably
25434high-level description of an abstract type, rather than a low-level dump
25435of its physical layout. After all, the standard
25436@cite{GDB print} command only knows the physical layout of your
25437types, not their abstract meaning. Debugging routines can provide information
25438at the desired semantic level and are thus enormously useful.
25439
25440For example, when debugging GNAT itself, it is crucial to have access to
25441the contents of the tree nodes used to represent the program internally.
25442But tree nodes are represented simply by an integer value (which in turn
25443is an index into a table of nodes).
25444Using the @cite{print} command on a tree node would simply print this integer
25445value, which is not very useful. But the PN routine (defined in file
25446treepr.adb in the GNAT sources) takes a tree node as input, and displays
25447a useful high level representation of the tree node, which includes the
25448syntactic category of the node, its position in the source, the integers
25449that denote descendant nodes and parent node, as well as varied
25450semantic information. To study this example in more detail, you might want to
25451look at the body of the PN procedure in the stated file.
25452
25453Another useful application of this capability is to deal with situations of
25454complex data which are not handled suitably by GDB. For example, if you specify
25455Convention Fortran for a multi-dimensional array, GDB does not know that
25456the ordering of array elements has been switched and will not properly
25457address the array elements. In such a case, instead of trying to print the
25458elements directly from GDB, you can write a callable procedure that prints
25459the elements in the desired format.
25460
25461@node Using the next Command in a Function,Stopping When Ada Exceptions Are Raised,Calling User-Defined Subprograms,Running and Debugging Ada Programs
25462@anchor{gnat_ugn/gnat_and_program_execution using-the-next-command-in-a-function}@anchor{201}@anchor{gnat_ugn/gnat_and_program_execution id8}@anchor{202}
25463@subsection Using the @emph{next} Command in a Function
25464
25465
25466When you use the @cite{next} command in a function, the current source
25467location will advance to the next statement as usual. A special case
25468arises in the case of a @cite{return} statement.
25469
25470Part of the code for a return statement is the 'epilogue' of the function.
25471This is the code that returns to the caller. There is only one copy of
25472this epilogue code, and it is typically associated with the last return
25473statement in the function if there is more than one return. In some
25474implementations, this epilogue is associated with the first statement
25475of the function.
25476
25477The result is that if you use the @cite{next} command from a return
25478statement that is not the last return statement of the function you
25479may see a strange apparent jump to the last return statement or to
25480the start of the function. You should simply ignore this odd jump.
25481The value returned is always that from the first return statement
25482that was stepped through.
25483
25484@node Stopping When Ada Exceptions Are Raised,Ada Tasks,Using the next Command in a Function,Running and Debugging Ada Programs
25485@anchor{gnat_ugn/gnat_and_program_execution stopping-when-ada-exceptions-are-raised}@anchor{203}@anchor{gnat_ugn/gnat_and_program_execution id9}@anchor{204}
25486@subsection Stopping When Ada Exceptions Are Raised
25487
25488
25489@geindex Exceptions (in gdb)
25490
25491You can set catchpoints that stop the program execution when your program
25492raises selected exceptions.
25493
25494
25495@itemize *
25496
25497@item 
25498
25499@table @asis
25500
25501@item @emph{catch exception}
25502
25503Set a catchpoint that stops execution whenever (any task in the) program
25504raises any exception.
25505@end table
25506
25507@item 
25508
25509@table @asis
25510
25511@item @emph{catch exception `name`}
25512
25513Set a catchpoint that stops execution whenever (any task in the) program
25514raises the exception @cite{name}.
25515@end table
25516
25517@item 
25518
25519@table @asis
25520
25521@item @emph{catch exception unhandled}
25522
25523Set a catchpoint that stops executing whenever (any task in the) program
25524raises an exception for which there is no handler.
25525@end table
25526
25527@item 
25528
25529@table @asis
25530
25531@item @emph{info exceptions}, @emph{info exceptions `regexp`}
25532
25533The @cite{info exceptions} command permits the user to examine all defined
25534exceptions within Ada programs. With a regular expression, @cite{regexp}, as
25535argument, prints out only those exceptions whose name matches @cite{regexp}.
25536@end table
25537@end itemize
25538
25539@geindex Tasks (in gdb)
25540
25541@node Ada Tasks,Debugging Generic Units,Stopping When Ada Exceptions Are Raised,Running and Debugging Ada Programs
25542@anchor{gnat_ugn/gnat_and_program_execution ada-tasks}@anchor{205}@anchor{gnat_ugn/gnat_and_program_execution id10}@anchor{206}
25543@subsection Ada Tasks
25544
25545
25546@cite{GDB} allows the following task-related commands:
25547
25548
25549@itemize *
25550
25551@item 
25552
25553@table @asis
25554
25555@item @emph{info tasks}
25556
25557This command shows a list of current Ada tasks, as in the following example:
25558
25559@example
25560(gdb) info tasks
25561  ID       TID P-ID   Thread Pri State                 Name
25562   1   8088000   0   807e000  15 Child Activation Wait main_task
25563   2   80a4000   1   80ae000  15 Accept/Select Wait    b
25564   3   809a800   1   80a4800  15 Child Activation Wait a
25565*  4   80ae800   3   80b8000  15 Running               c
25566@end example
25567
25568In this listing, the asterisk before the first task indicates it to be the
25569currently running task. The first column lists the task ID that is used
25570to refer to tasks in the following commands.
25571@end table
25572@end itemize
25573
25574@geindex Breakpoints and tasks
25575
25576
25577@itemize *
25578
25579@item 
25580@emph{break `linespec` task `taskid`}, @emph{break `linespec` task `taskid` if ...}
25581
25582@quotation
25583
25584These commands are like the @cite{break ... thread ...}.
25585@cite{linespec} specifies source lines.
25586
25587Use the qualifier @code{task @emph{taskid}} with a breakpoint command
25588to specify that you only want @cite{GDB} to stop the program when a
25589particular Ada task reaches this breakpoint. @cite{taskid} is one of the
25590numeric task identifiers assigned by @cite{GDB}, shown in the first
25591column of the @code{info tasks} display.
25592
25593If you do not specify @code{task @emph{taskid}} when you set a
25594breakpoint, the breakpoint applies to @emph{all} tasks of your
25595program.
25596
25597You can use the @cite{task} qualifier on conditional breakpoints as
25598well; in this case, place @code{task @emph{taskid}} before the
25599breakpoint condition (before the @cite{if}).
25600@end quotation
25601@end itemize
25602
25603@geindex Task switching (in gdb)
25604
25605
25606@itemize *
25607
25608@item 
25609@emph{task `taskno`}
25610
25611@quotation
25612
25613This command allows switching to the task referred by @cite{taskno}. In
25614particular, this allows browsing of the backtrace of the specified
25615task. It is advisable to switch back to the original task before
25616continuing execution otherwise the scheduling of the program may be
25617perturbed.
25618@end quotation
25619@end itemize
25620
25621For more detailed information on the tasking support,
25622see @cite{Debugging with GDB}.
25623
25624@geindex Debugging Generic Units
25625
25626@geindex Generics
25627
25628@node Debugging Generic Units,Remote Debugging with gdbserver,Ada Tasks,Running and Debugging Ada Programs
25629@anchor{gnat_ugn/gnat_and_program_execution debugging-generic-units}@anchor{207}@anchor{gnat_ugn/gnat_and_program_execution id11}@anchor{208}
25630@subsection Debugging Generic Units
25631
25632
25633GNAT always uses code expansion for generic instantiation. This means that
25634each time an instantiation occurs, a complete copy of the original code is
25635made, with appropriate substitutions of formals by actuals.
25636
25637It is not possible to refer to the original generic entities in
25638@cite{GDB}, but it is always possible to debug a particular instance of
25639a generic, by using the appropriate expanded names. For example, if we have
25640
25641@quotation
25642
25643@example
25644procedure g is
25645
25646   generic package k is
25647      procedure kp (v1 : in out integer);
25648   end k;
25649
25650   package body k is
25651      procedure kp (v1 : in out integer) is
25652      begin
25653         v1 := v1 + 1;
25654      end kp;
25655   end k;
25656
25657   package k1 is new k;
25658   package k2 is new k;
25659
25660   var : integer := 1;
25661
25662begin
25663   k1.kp (var);
25664   k2.kp (var);
25665   k1.kp (var);
25666   k2.kp (var);
25667end;
25668@end example
25669@end quotation
25670
25671Then to break on a call to procedure kp in the k2 instance, simply
25672use the command:
25673
25674@quotation
25675
25676@example
25677(gdb) break g.k2.kp
25678@end example
25679@end quotation
25680
25681When the breakpoint occurs, you can step through the code of the
25682instance in the normal manner and examine the values of local variables, as for
25683other units.
25684
25685@geindex Remote Debugging with gdbserver
25686
25687@node Remote Debugging with gdbserver,GNAT Abnormal Termination or Failure to Terminate,Debugging Generic Units,Running and Debugging Ada Programs
25688@anchor{gnat_ugn/gnat_and_program_execution remote-debugging-with-gdbserver}@anchor{209}@anchor{gnat_ugn/gnat_and_program_execution id12}@anchor{20a}
25689@subsection Remote Debugging with gdbserver
25690
25691
25692On platforms where gdbserver is supported, it is possible to use this tool
25693to debug your application remotely.  This can be useful in situations
25694where the program needs to be run on a target host that is different
25695from the host used for development, particularly when the target has
25696a limited amount of resources (either CPU and/or memory).
25697
25698To do so, start your program using gdbserver on the target machine.
25699gdbserver then automatically suspends the execution of your program
25700at its entry point, waiting for a debugger to connect to it.  The
25701following commands starts an application and tells gdbserver to
25702wait for a connection with the debugger on localhost port 4444.
25703
25704@quotation
25705
25706@example
25707$ gdbserver localhost:4444 program
25708Process program created; pid = 5685
25709Listening on port 4444
25710@end example
25711@end quotation
25712
25713Once gdbserver has started listening, we can tell the debugger to establish
25714a connection with this gdbserver, and then start the same debugging session
25715as if the program was being debugged on the same host, directly under
25716the control of GDB.
25717
25718@quotation
25719
25720@example
25721$ gdb program
25722(gdb) target remote targethost:4444
25723Remote debugging using targethost:4444
257240x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
25725(gdb) b foo.adb:3
25726Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
25727(gdb) continue
25728Continuing.
25729
25730Breakpoint 1, foo () at foo.adb:4
257314       end foo;
25732@end example
25733@end quotation
25734
25735It is also possible to use gdbserver to attach to an already running
25736program, in which case the execution of that program is simply suspended
25737until the connection between the debugger and gdbserver is established.
25738
25739For more information on how to use gdbserver, see the @emph{Using the gdbserver Program}
25740section in @cite{Debugging with GDB}.
25741GNAT provides support for gdbserver on x86-linux, x86-windows and x86_64-linux.
25742
25743@geindex Abnormal Termination or Failure to Terminate
25744
25745@node GNAT Abnormal Termination or Failure to Terminate,Naming Conventions for GNAT Source Files,Remote Debugging with gdbserver,Running and Debugging Ada Programs
25746@anchor{gnat_ugn/gnat_and_program_execution gnat-abnormal-termination-or-failure-to-terminate}@anchor{20b}@anchor{gnat_ugn/gnat_and_program_execution id13}@anchor{20c}
25747@subsection GNAT Abnormal Termination or Failure to Terminate
25748
25749
25750When presented with programs that contain serious errors in syntax
25751or semantics,
25752GNAT may on rare occasions  experience problems in operation, such
25753as aborting with a
25754segmentation fault or illegal memory access, raising an internal
25755exception, terminating abnormally, or failing to terminate at all.
25756In such cases, you can activate
25757various features of GNAT that can help you pinpoint the construct in your
25758program that is the likely source of the problem.
25759
25760The following strategies are presented in increasing order of
25761difficulty, corresponding to your experience in using GNAT and your
25762familiarity with compiler internals.
25763
25764
25765@itemize *
25766
25767@item 
25768Run @emph{gcc} with the @emph{-gnatf}. This first
25769switch causes all errors on a given line to be reported. In its absence,
25770only the first error on a line is displayed.
25771
25772The @emph{-gnatdO} switch causes errors to be displayed as soon as they
25773are encountered, rather than after compilation is terminated. If GNAT
25774terminates prematurely or goes into an infinite loop, the last error
25775message displayed may help to pinpoint the culprit.
25776
25777@item 
25778Run @emph{gcc} with the @emph{-v (verbose)} switch. In this
25779mode, @emph{gcc} produces ongoing information about the progress of the
25780compilation and provides the name of each procedure as code is
25781generated. This switch allows you to find which Ada procedure was being
25782compiled when it encountered a code generation problem.
25783@end itemize
25784
25785@geindex -gnatdc switch
25786
25787
25788@itemize *
25789
25790@item 
25791Run @emph{gcc} with the @emph{-gnatdc} switch. This is a GNAT specific
25792switch that does for the front-end what @emph{-v} does
25793for the back end. The system prints the name of each unit,
25794either a compilation unit or nested unit, as it is being analyzed.
25795
25796@item 
25797Finally, you can start
25798@cite{gdb} directly on the @cite{gnat1} executable. @cite{gnat1} is the
25799front-end of GNAT, and can be run independently (normally it is just
25800called from @emph{gcc}). You can use @cite{gdb} on @cite{gnat1} as you
25801would on a C program (but @ref{1f7,,The GNAT Debugger GDB} for caveats). The
25802@cite{where} command is the first line of attack; the variable
25803@cite{lineno} (seen by @cite{print lineno}), used by the second phase of
25804@cite{gnat1} and by the @emph{gcc} backend, indicates the source line at
25805which the execution stopped, and @cite{input_file name} indicates the name of
25806the source file.
25807@end itemize
25808
25809@node Naming Conventions for GNAT Source Files,Getting Internal Debugging Information,GNAT Abnormal Termination or Failure to Terminate,Running and Debugging Ada Programs
25810@anchor{gnat_ugn/gnat_and_program_execution naming-conventions-for-gnat-source-files}@anchor{20d}@anchor{gnat_ugn/gnat_and_program_execution id14}@anchor{20e}
25811@subsection Naming Conventions for GNAT Source Files
25812
25813
25814In order to examine the workings of the GNAT system, the following
25815brief description of its organization may be helpful:
25816
25817
25818@itemize *
25819
25820@item 
25821Files with prefix @code{sc} contain the lexical scanner.
25822
25823@item 
25824All files prefixed with @code{par} are components of the parser. The
25825numbers correspond to chapters of the Ada Reference Manual. For example,
25826parsing of select statements can be found in @code{par-ch9.adb}.
25827
25828@item 
25829All files prefixed with @code{sem} perform semantic analysis. The
25830numbers correspond to chapters of the Ada standard. For example, all
25831issues involving context clauses can be found in @code{sem_ch10.adb}. In
25832addition, some features of the language require sufficient special processing
25833to justify their own semantic files: sem_aggr for aggregates, sem_disp for
25834dynamic dispatching, etc.
25835
25836@item 
25837All files prefixed with @code{exp} perform normalization and
25838expansion of the intermediate representation (abstract syntax tree, or AST).
25839these files use the same numbering scheme as the parser and semantics files.
25840For example, the construction of record initialization procedures is done in
25841@code{exp_ch3.adb}.
25842
25843@item 
25844The files prefixed with @code{bind} implement the binder, which
25845verifies the consistency of the compilation, determines an order of
25846elaboration, and generates the bind file.
25847
25848@item 
25849The files @code{atree.ads} and @code{atree.adb} detail the low-level
25850data structures used by the front-end.
25851
25852@item 
25853The files @code{sinfo.ads} and @code{sinfo.adb} detail the structure of
25854the abstract syntax tree as produced by the parser.
25855
25856@item 
25857The files @code{einfo.ads} and @code{einfo.adb} detail the attributes of
25858all entities, computed during semantic analysis.
25859
25860@item 
25861Library management issues are dealt with in files with prefix
25862@code{lib}.
25863
25864@geindex Annex A (in Ada Reference Manual)
25865
25866@item 
25867Ada files with the prefix @code{a-} are children of @cite{Ada}, as
25868defined in Annex A.
25869
25870@geindex Annex B (in Ada reference Manual)
25871
25872@item 
25873Files with prefix @code{i-} are children of @cite{Interfaces}, as
25874defined in Annex B.
25875
25876@geindex System (package in Ada Reference Manual)
25877
25878@item 
25879Files with prefix @code{s-} are children of @cite{System}. This includes
25880both language-defined children and GNAT run-time routines.
25881
25882@geindex GNAT (package)
25883
25884@item 
25885Files with prefix @code{g-} are children of @cite{GNAT}. These are useful
25886general-purpose packages, fully documented in their specs. All
25887the other @code{.c} files are modifications of common @emph{gcc} files.
25888@end itemize
25889
25890@node Getting Internal Debugging Information,Stack Traceback,Naming Conventions for GNAT Source Files,Running and Debugging Ada Programs
25891@anchor{gnat_ugn/gnat_and_program_execution id15}@anchor{20f}@anchor{gnat_ugn/gnat_and_program_execution getting-internal-debugging-information}@anchor{210}
25892@subsection Getting Internal Debugging Information
25893
25894
25895Most compilers have internal debugging switches and modes. GNAT
25896does also, except GNAT internal debugging switches and modes are not
25897secret. A summary and full description of all the compiler and binder
25898debug flags are in the file @code{debug.adb}. You must obtain the
25899sources of the compiler to see the full detailed effects of these flags.
25900
25901The switches that print the source of the program (reconstructed from
25902the internal tree) are of general interest for user programs, as are the
25903options to print
25904the full internal tree, and the entity table (the symbol table
25905information). The reconstructed source provides a readable version of the
25906program after the front-end has completed analysis and  expansion,
25907and is useful when studying the performance of specific constructs.
25908For example, constraint checks are indicated, complex aggregates
25909are replaced with loops and assignments, and tasking primitives
25910are replaced with run-time calls.
25911
25912@geindex traceback
25913
25914@geindex stack traceback
25915
25916@geindex stack unwinding
25917
25918@node Stack Traceback,,Getting Internal Debugging Information,Running and Debugging Ada Programs
25919@anchor{gnat_ugn/gnat_and_program_execution stack-traceback}@anchor{211}@anchor{gnat_ugn/gnat_and_program_execution id16}@anchor{212}
25920@subsection Stack Traceback
25921
25922
25923Traceback is a mechanism to display the sequence of subprogram calls that
25924leads to a specified execution point in a program. Often (but not always)
25925the execution point is an instruction at which an exception has been raised.
25926This mechanism is also known as @emph{stack unwinding} because it obtains
25927its information by scanning the run-time stack and recovering the activation
25928records of all active subprograms. Stack unwinding is one of the most
25929important tools for program debugging.
25930
25931The first entry stored in traceback corresponds to the deepest calling level,
25932that is to say the subprogram currently executing the instruction
25933from which we want to obtain the traceback.
25934
25935Note that there is no runtime performance penalty when stack traceback
25936is enabled, and no exception is raised during program execution.
25937
25938@geindex traceback
25939@geindex non-symbolic
25940
25941@menu
25942* Non-Symbolic Traceback:: 
25943* Symbolic Traceback:: 
25944
25945@end menu
25946
25947@node Non-Symbolic Traceback,Symbolic Traceback,,Stack Traceback
25948@anchor{gnat_ugn/gnat_and_program_execution non-symbolic-traceback}@anchor{213}@anchor{gnat_ugn/gnat_and_program_execution id17}@anchor{214}
25949@subsubsection Non-Symbolic Traceback
25950
25951
25952Note: this feature is not supported on all platforms. See
25953@code{GNAT.Traceback} spec in @code{g-traceb.ads}
25954for a complete list of supported platforms.
25955
25956@subsubheading Tracebacks From an Unhandled Exception
25957
25958
25959A runtime non-symbolic traceback is a list of addresses of call instructions.
25960To enable this feature you must use the @emph{-E}
25961@cite{gnatbind}'s option. With this option a stack traceback is stored as part
25962of exception information. You can retrieve this information using the
25963@cite{addr2line} tool.
25964
25965Here is a simple example:
25966
25967@quotation
25968
25969@example
25970procedure STB is
25971
25972   procedure P1 is
25973   begin
25974      raise Constraint_Error;
25975   end P1;
25976
25977   procedure P2 is
25978   begin
25979      P1;
25980   end P2;
25981
25982begin
25983   P2;
25984end STB;
25985@end example
25986
25987@example
25988$ gnatmake stb -bargs -E
25989$ stb
25990
25991Execution terminated by unhandled exception
25992Exception name: CONSTRAINT_ERROR
25993Message: stb.adb:5
25994Call stack traceback locations:
259950x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
25996@end example
25997@end quotation
25998
25999As we see the traceback lists a sequence of addresses for the unhandled
26000exception @cite{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
26001guess that this exception come from procedure P1. To translate these
26002addresses into the source lines where the calls appear, the
26003@cite{addr2line} tool, described below, is invaluable. The use of this tool
26004requires the program to be compiled with debug information.
26005
26006@quotation
26007
26008@example
26009$ gnatmake -g stb -bargs -E
26010$ stb
26011
26012Execution terminated by unhandled exception
26013Exception name: CONSTRAINT_ERROR
26014Message: stb.adb:5
26015Call stack traceback locations:
260160x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
26017
26018$ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
26019   0x4011f1 0x77e892a4
26020
2602100401373 at d:/stb/stb.adb:5
260220040138B at d:/stb/stb.adb:10
260230040139C at d:/stb/stb.adb:14
2602400401335 at d:/stb/b~stb.adb:104
26025004011C4 at /build/.../crt1.c:200
26026004011F1 at /build/.../crt1.c:222
2602777E892A4 in ?? at ??:0
26028@end example
26029@end quotation
26030
26031The @cite{addr2line} tool has several other useful options:
26032
26033@quotation
26034
26035
26036@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
26037@item
26038
26039@code{--functions}
26040
26041@tab
26042
26043to get the function name corresponding to any location
26044
26045@item
26046
26047@code{--demangle=gnat}
26048
26049@tab
26050
26051to use the gnat decoding mode for the function names.
26052Note that for binutils version 2.9.x the option is
26053simply @code{--demangle}.
26054
26055@end multitable
26056
26057
26058@example
26059$ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
26060   0x40139c 0x401335 0x4011c4 0x4011f1
26061
2606200401373 in stb.p1 at d:/stb/stb.adb:5
260630040138B in stb.p2 at d:/stb/stb.adb:10
260640040139C in stb at d:/stb/stb.adb:14
2606500401335 in main at d:/stb/b~stb.adb:104
26066004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
26067004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
26068@end example
26069@end quotation
26070
26071From this traceback we can see that the exception was raised in
26072@code{stb.adb} at line 5, which was reached from a procedure call in
26073@code{stb.adb} at line 10, and so on. The @code{b~std.adb} is the binder file,
26074which contains the call to the main program.
26075@ref{120,,Running gnatbind}. The remaining entries are assorted runtime routines,
26076and the output will vary from platform to platform.
26077
26078It is also possible to use @cite{GDB} with these traceback addresses to debug
26079the program. For example, we can break at a given code location, as reported
26080in the stack traceback:
26081
26082@quotation
26083
26084@example
26085$ gdb -nw stb
26086@end example
26087@end quotation
26088
26089Furthermore, this feature is not implemented inside Windows DLL. Only
26090the non-symbolic traceback is reported in this case.
26091
26092@quotation
26093
26094@example
26095(gdb) break *0x401373
26096Breakpoint 1 at 0x401373: file stb.adb, line 5.
26097@end example
26098@end quotation
26099
26100It is important to note that the stack traceback addresses
26101do not change when debug information is included. This is particularly useful
26102because it makes it possible to release software without debug information (to
26103minimize object size), get a field report that includes a stack traceback
26104whenever an internal bug occurs, and then be able to retrieve the sequence
26105of calls with the same program compiled with debug information.
26106
26107@subsubheading Tracebacks From Exception Occurrences
26108
26109
26110Non-symbolic tracebacks are obtained by using the @emph{-E} binder argument.
26111The stack traceback is attached to the exception information string, and can
26112be retrieved in an exception handler within the Ada program, by means of the
26113Ada facilities defined in @cite{Ada.Exceptions}. Here is a simple example:
26114
26115@quotation
26116
26117@example
26118with Ada.Text_IO;
26119with Ada.Exceptions;
26120
26121procedure STB is
26122
26123   use Ada;
26124   use Ada.Exceptions;
26125
26126   procedure P1 is
26127      K : Positive := 1;
26128   begin
26129      K := K - 1;
26130   exception
26131      when E : others =>
26132         Text_IO.Put_Line (Exception_Information (E));
26133   end P1;
26134
26135   procedure P2 is
26136   begin
26137      P1;
26138   end P2;
26139
26140begin
26141   P2;
26142end STB;
26143@end example
26144@end quotation
26145
26146This program will output:
26147
26148@quotation
26149
26150@example
26151$ stb
26152
26153Exception name: CONSTRAINT_ERROR
26154Message: stb.adb:12
26155Call stack traceback locations:
261560x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
26157@end example
26158@end quotation
26159
26160@subsubheading Tracebacks From Anywhere in a Program
26161
26162
26163It is also possible to retrieve a stack traceback from anywhere in a
26164program. For this you need to
26165use the @cite{GNAT.Traceback} API. This package includes a procedure called
26166@cite{Call_Chain} that computes a complete stack traceback, as well as useful
26167display procedures described below. It is not necessary to use the
26168@emph{-E gnatbind} option in this case, because the stack traceback mechanism
26169is invoked explicitly.
26170
26171In the following example we compute a traceback at a specific location in
26172the program, and we display it using @cite{GNAT.Debug_Utilities.Image} to
26173convert addresses to strings:
26174
26175@quotation
26176
26177@example
26178with Ada.Text_IO;
26179with GNAT.Traceback;
26180with GNAT.Debug_Utilities;
26181
26182procedure STB is
26183
26184   use Ada;
26185   use GNAT;
26186   use GNAT.Traceback;
26187
26188   procedure P1 is
26189      TB  : Tracebacks_Array (1 .. 10);
26190      --  We are asking for a maximum of 10 stack frames.
26191      Len : Natural;
26192      --  Len will receive the actual number of stack frames returned.
26193   begin
26194      Call_Chain (TB, Len);
26195
26196      Text_IO.Put ("In STB.P1 : ");
26197
26198      for K in 1 .. Len loop
26199         Text_IO.Put (Debug_Utilities.Image (TB (K)));
26200         Text_IO.Put (' ');
26201      end loop;
26202
26203      Text_IO.New_Line;
26204   end P1;
26205
26206   procedure P2 is
26207   begin
26208      P1;
26209   end P2;
26210
26211begin
26212   P2;
26213end STB;
26214@end example
26215
26216@example
26217$ gnatmake -g stb
26218$ stb
26219
26220In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
2622116#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
26222@end example
26223@end quotation
26224
26225You can then get further information by invoking the @cite{addr2line}
26226tool as described earlier (note that the hexadecimal addresses
26227need to be specified in C format, with a leading '0x').
26228
26229@geindex traceback
26230@geindex symbolic
26231
26232@node Symbolic Traceback,,Non-Symbolic Traceback,Stack Traceback
26233@anchor{gnat_ugn/gnat_and_program_execution id18}@anchor{215}@anchor{gnat_ugn/gnat_and_program_execution symbolic-traceback}@anchor{216}
26234@subsubsection Symbolic Traceback
26235
26236
26237A symbolic traceback is a stack traceback in which procedure names are
26238associated with each code location.
26239
26240Note that this feature is not supported on all platforms. See
26241@code{GNAT.Traceback.Symbolic} spec in @code{g-trasym.ads} for a complete
26242list of currently supported platforms.
26243
26244Note that the symbolic traceback requires that the program be compiled
26245with debug information. If it is not compiled with debug information
26246only the non-symbolic information will be valid.
26247
26248@subsubheading Tracebacks From Exception Occurrences
26249
26250
26251Here is an example:
26252
26253@quotation
26254
26255@example
26256with Ada.Text_IO;
26257with GNAT.Traceback.Symbolic;
26258
26259procedure STB is
26260
26261   procedure P1 is
26262   begin
26263      raise Constraint_Error;
26264   end P1;
26265
26266   procedure P2 is
26267   begin
26268      P1;
26269   end P2;
26270
26271   procedure P3 is
26272   begin
26273      P2;
26274   end P3;
26275
26276begin
26277   P3;
26278exception
26279   when E : others =>
26280      Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
26281end STB;
26282@end example
26283
26284@example
26285$ gnatmake -g .\stb -bargs -E
26286$ stb
26287
262880040149F in stb.p1 at stb.adb:8
26289004014B7 in stb.p2 at stb.adb:13
26290004014CF in stb.p3 at stb.adb:18
26291004015DD in ada.stb at stb.adb:22
2629200401461 in main at b~stb.adb:168
26293004011C4 in __mingw_CRTStartup at crt1.c:200
26294004011F1 in mainCRTStartup at crt1.c:222
2629577E892A4 in ?? at ??:0
26296@end example
26297@end quotation
26298
26299In the above example the @code{.\} syntax in the @emph{gnatmake} command
26300is currently required by @emph{addr2line} for files that are in
26301the current working directory.
26302Moreover, the exact sequence of linker options may vary from platform
26303to platform.
26304The above @emph{-largs} section is for Windows platforms. By contrast,
26305under Unix there is no need for the @emph{-largs} section.
26306Differences across platforms are due to details of linker implementation.
26307
26308@subsubheading Tracebacks From Anywhere in a Program
26309
26310
26311It is possible to get a symbolic stack traceback
26312from anywhere in a program, just as for non-symbolic tracebacks.
26313The first step is to obtain a non-symbolic
26314traceback, and then call @cite{Symbolic_Traceback} to compute the symbolic
26315information. Here is an example:
26316
26317@quotation
26318
26319@example
26320with Ada.Text_IO;
26321with GNAT.Traceback;
26322with GNAT.Traceback.Symbolic;
26323
26324procedure STB is
26325
26326   use Ada;
26327   use GNAT.Traceback;
26328   use GNAT.Traceback.Symbolic;
26329
26330   procedure P1 is
26331      TB  : Tracebacks_Array (1 .. 10);
26332      --  We are asking for a maximum of 10 stack frames.
26333      Len : Natural;
26334      --  Len will receive the actual number of stack frames returned.
26335   begin
26336      Call_Chain (TB, Len);
26337      Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
26338   end P1;
26339
26340   procedure P2 is
26341   begin
26342      P1;
26343   end P2;
26344
26345begin
26346   P2;
26347end STB;
26348@end example
26349@end quotation
26350
26351@geindex Code Coverage
26352
26353@geindex Profiling
26354
26355@node Code Coverage and Profiling,Improving Performance,Running and Debugging Ada Programs,GNAT and Program Execution
26356@anchor{gnat_ugn/gnat_and_program_execution id19}@anchor{1f1}@anchor{gnat_ugn/gnat_and_program_execution code-coverage-and-profiling}@anchor{27}
26357@section Code Coverage and Profiling
26358
26359
26360This section describes how to use the @cite{gcov} coverage testing tool and
26361the @cite{gprof} profiler tool on Ada programs.
26362
26363@geindex gcov
26364
26365@menu
26366* Code Coverage of Ada Programs with gcov:: 
26367* Profiling an Ada Program with gprof:: 
26368
26369@end menu
26370
26371@node Code Coverage of Ada Programs with gcov,Profiling an Ada Program with gprof,,Code Coverage and Profiling
26372@anchor{gnat_ugn/gnat_and_program_execution id20}@anchor{217}@anchor{gnat_ugn/gnat_and_program_execution code-coverage-of-ada-programs-with-gcov}@anchor{218}
26373@subsection Code Coverage of Ada Programs with gcov
26374
26375
26376@cite{gcov} is a test coverage program: it analyzes the execution of a given
26377program on selected tests, to help you determine the portions of the program
26378that are still untested.
26379
26380@cite{gcov} is part of the GCC suite, and is described in detail in the GCC
26381User's Guide. You can refer to this documentation for a more complete
26382description.
26383
26384This chapter provides a quick startup guide, and
26385details some GNAT-specific features.
26386
26387@menu
26388* Quick startup guide:: 
26389* GNAT specifics:: 
26390
26391@end menu
26392
26393@node Quick startup guide,GNAT specifics,,Code Coverage of Ada Programs with gcov
26394@anchor{gnat_ugn/gnat_and_program_execution id21}@anchor{219}@anchor{gnat_ugn/gnat_and_program_execution quick-startup-guide}@anchor{21a}
26395@subsubsection Quick startup guide
26396
26397
26398In order to perform coverage analysis of a program using @cite{gcov}, several
26399steps are needed:
26400
26401
26402@enumerate 
26403
26404@item 
26405Instrument the code during the compilation process,
26406
26407@item 
26408Execute the instrumented program, and
26409
26410@item 
26411Invoke the @cite{gcov} tool to generate the coverage results.
26412@end enumerate
26413
26414@geindex -fprofile-arcs (gcc)
26415
26416@geindex -ftest-coverage (gcc
26417
26418@geindex -fprofile-arcs (gnatbind)
26419
26420The code instrumentation needed by gcov is created at the object level.
26421The source code is not modified in any way, because the instrumentation code is
26422inserted by gcc during the compilation process. To compile your code with code
26423coverage activated, you need to recompile your whole project using the
26424switches
26425@cite{-fprofile-arcs} and @cite{-ftest-coverage}, and link it using
26426@cite{-fprofile-arcs}.
26427
26428@quotation
26429
26430@example
26431$ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \\
26432   -largs -fprofile-arcs
26433@end example
26434@end quotation
26435
26436This compilation process will create @code{.gcno} files together with
26437the usual object files.
26438
26439Once the program is compiled with coverage instrumentation, you can
26440run it as many times as needed -- on portions of a test suite for
26441example. The first execution will produce @code{.gcda} files at the
26442same location as the @code{.gcno} files.  Subsequent executions
26443will update those files, so that a cumulative result of the covered
26444portions of the program is generated.
26445
26446Finally, you need to call the @cite{gcov} tool. The different options of
26447@cite{gcov} are described in the GCC User's Guide, section 'Invoking gcov'.
26448
26449This will create annotated source files with a @code{.gcov} extension:
26450@code{my_main.adb} file will be analyzed in @code{my_main.adb.gcov}.
26451
26452@node GNAT specifics,,Quick startup guide,Code Coverage of Ada Programs with gcov
26453@anchor{gnat_ugn/gnat_and_program_execution gnat-specifics}@anchor{21b}@anchor{gnat_ugn/gnat_and_program_execution id22}@anchor{21c}
26454@subsubsection GNAT specifics
26455
26456
26457Because of Ada semantics, portions of the source code may be shared among
26458several object files. This is the case for example when generics are
26459involved, when inlining is active  or when declarations generate  initialisation
26460calls. In order to take
26461into account this shared code, you need to call @cite{gcov} on all
26462source files of the tested program at once.
26463
26464The list of source files might exceed the system's maximum command line
26465length. In order to bypass this limitation, a new mechanism has been
26466implemented in @cite{gcov}: you can now list all your project's files into a
26467text file, and provide this file to gcov as a parameter,  preceded by a @code{@@}
26468(e.g. @code{gcov @@mysrclist.txt}).
26469
26470Note that on AIX compiling a static library with @cite{-fprofile-arcs} is
26471not supported as there can be unresolved symbols during the final link.
26472
26473@geindex gprof
26474
26475@geindex Profiling
26476
26477@node Profiling an Ada Program with gprof,,Code Coverage of Ada Programs with gcov,Code Coverage and Profiling
26478@anchor{gnat_ugn/gnat_and_program_execution profiling-an-ada-program-with-gprof}@anchor{21d}@anchor{gnat_ugn/gnat_and_program_execution id23}@anchor{21e}
26479@subsection Profiling an Ada Program with gprof
26480
26481
26482This section is not meant to be an exhaustive documentation of @cite{gprof}.
26483Full documentation for it can be found in the @cite{GNU Profiler User's Guide}
26484documentation that is part of this GNAT distribution.
26485
26486Profiling a program helps determine the parts of a program that are executed
26487most often, and are therefore the most time-consuming.
26488
26489@cite{gprof} is the standard GNU profiling tool; it has been enhanced to
26490better handle Ada programs and multitasking.
26491It is currently supported on the following platforms
26492
26493
26494@itemize *
26495
26496@item 
26497linux x86/x86_64
26498
26499@item 
26500solaris sparc/sparc64/x86
26501
26502@item 
26503windows x86
26504@end itemize
26505
26506In order to profile a program using @cite{gprof}, several steps are needed:
26507
26508
26509@enumerate 
26510
26511@item 
26512Instrument the code, which requires a full recompilation of the project with the
26513proper switches.
26514
26515@item 
26516Execute the program under the analysis conditions, i.e. with the desired
26517input.
26518
26519@item 
26520Analyze the results using the @cite{gprof} tool.
26521@end enumerate
26522
26523The following sections detail the different steps, and indicate how
26524to interpret the results.
26525
26526@menu
26527* Compilation for profiling:: 
26528* Program execution:: 
26529* Running gprof:: 
26530* Interpretation of profiling results:: 
26531
26532@end menu
26533
26534@node Compilation for profiling,Program execution,,Profiling an Ada Program with gprof
26535@anchor{gnat_ugn/gnat_and_program_execution id24}@anchor{21f}@anchor{gnat_ugn/gnat_and_program_execution compilation-for-profiling}@anchor{220}
26536@subsubsection Compilation for profiling
26537
26538
26539@geindex -pg (gcc)
26540@geindex for profiling
26541
26542@geindex -pg (gnatlink)
26543@geindex for profiling
26544
26545In order to profile a program the first step is to tell the compiler
26546to generate the necessary profiling information. The compiler switch to be used
26547is @code{-pg}, which must be added to other compilation switches. This
26548switch needs to be specified both during compilation and link stages, and can
26549be specified once when using gnatmake:
26550
26551@quotation
26552
26553@example
26554$ gnatmake -f -pg -P my_project
26555@end example
26556@end quotation
26557
26558Note that only the objects that were compiled with the @code{-pg} switch will
26559be profiled; if you need to profile your whole project, use the @code{-f}
26560gnatmake switch to force full recompilation.
26561
26562@node Program execution,Running gprof,Compilation for profiling,Profiling an Ada Program with gprof
26563@anchor{gnat_ugn/gnat_and_program_execution program-execution}@anchor{221}@anchor{gnat_ugn/gnat_and_program_execution id25}@anchor{222}
26564@subsubsection Program execution
26565
26566
26567Once the program has been compiled for profiling, you can run it as usual.
26568
26569The only constraint imposed by profiling is that the program must terminate
26570normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
26571properly analyzed.
26572
26573Once the program completes execution, a data file called @code{gmon.out} is
26574generated in the directory where the program was launched from. If this file
26575already exists, it will be overwritten.
26576
26577@node Running gprof,Interpretation of profiling results,Program execution,Profiling an Ada Program with gprof
26578@anchor{gnat_ugn/gnat_and_program_execution running-gprof}@anchor{223}@anchor{gnat_ugn/gnat_and_program_execution id26}@anchor{224}
26579@subsubsection Running gprof
26580
26581
26582The @cite{gprof} tool is called as follow:
26583
26584@quotation
26585
26586@example
26587$ gprof my_prog gmon.out
26588@end example
26589@end quotation
26590
26591or simply:
26592
26593@quotation
26594
26595@example
26596$  gprof my_prog
26597@end example
26598@end quotation
26599
26600The complete form of the gprof command line is the following:
26601
26602@quotation
26603
26604@example
26605$ gprof [switches] [executable [data-file]]
26606@end example
26607@end quotation
26608
26609@cite{gprof} supports numerous switches. The order of these
26610switch does not matter. The full list of options can be found in
26611the GNU Profiler User's Guide documentation that comes with this documentation.
26612
26613The following is the subset of those switches that is most relevant:
26614
26615@geindex --demangle (gprof)
26616
26617
26618@table @asis
26619
26620@item @code{--demangle[=@emph{style}]}, @code{--no-demangle}
26621
26622These options control whether symbol names should be demangled when
26623printing output.  The default is to demangle C++ symbols.  The
26624@code{--no-demangle} option may be used to turn off demangling. Different
26625compilers have different mangling styles.  The optional demangling style
26626argument can be used to choose an appropriate demangling style for your
26627compiler, in particular Ada symbols generated by GNAT can be demangled using
26628@code{--demangle=gnat}.
26629@end table
26630
26631@geindex -e (gprof)
26632
26633
26634@table @asis
26635
26636@item @code{-e @emph{function_name}}
26637
26638The @code{-e @emph{function}} option tells @cite{gprof} not to print
26639information about the function @cite{function_name} (and its
26640children...) in the call graph.  The function will still be listed
26641as a child of any functions that call it, but its index number will be
26642shown as @code{[not printed]}.  More than one @code{-e} option may be
26643given; only one @cite{function_name} may be indicated with each @code{-e}
26644option.
26645@end table
26646
26647@geindex -E (gprof)
26648
26649
26650@table @asis
26651
26652@item @code{-E @emph{function_name}}
26653
26654The @code{-E @emph{function}} option works like the @code{-e} option, but
26655execution time spent in the function (and children who were not called from
26656anywhere else), will not be used to compute the percentages-of-time for
26657the call graph.  More than one @code{-E} option may be given; only one
26658@cite{function_name} may be indicated with each @code{-E} option.
26659@end table
26660
26661@geindex -f (gprof)
26662
26663
26664@table @asis
26665
26666@item @code{-f @emph{function_name}}
26667
26668The @code{-f @emph{function}} option causes @cite{gprof} to limit the
26669call graph to the function @cite{function_name} and its children (and
26670their children...).  More than one @code{-f} option may be given;
26671only one @cite{function_name} may be indicated with each @code{-f}
26672option.
26673@end table
26674
26675@geindex -F (gprof)
26676
26677
26678@table @asis
26679
26680@item @code{-F @emph{function_name}}
26681
26682The @code{-F @emph{function}} option works like the @code{-f} option, but
26683only time spent in the function and its children (and their
26684children...) will be used to determine total-time and
26685percentages-of-time for the call graph.  More than one @code{-F} option
26686may be given; only one @cite{function_name} may be indicated with each
26687@code{-F} option.  The @code{-F} option overrides the @code{-E} option.
26688@end table
26689
26690@node Interpretation of profiling results,,Running gprof,Profiling an Ada Program with gprof
26691@anchor{gnat_ugn/gnat_and_program_execution id27}@anchor{225}@anchor{gnat_ugn/gnat_and_program_execution interpretation-of-profiling-results}@anchor{226}
26692@subsubsection Interpretation of profiling results
26693
26694
26695The results of the profiling analysis are represented by two arrays: the
26696'flat profile' and the 'call graph'. Full documentation of those outputs
26697can be found in the GNU Profiler User's Guide.
26698
26699The flat profile shows the time spent in each function of the program, and how
26700many time it has been called. This allows you to locate easily the most
26701time-consuming functions.
26702
26703The call graph shows, for each subprogram, the subprograms that call it,
26704and the subprograms that it calls. It also provides an estimate of the time
26705spent in each of those callers/called subprograms.
26706
26707@node Improving Performance,Overflow Check Handling in GNAT,Code Coverage and Profiling,GNAT and Program Execution
26708@anchor{gnat_ugn/gnat_and_program_execution improving-performance}@anchor{28}@anchor{gnat_ugn/gnat_and_program_execution id28}@anchor{1f2}
26709@section Improving Performance
26710
26711
26712@geindex Improving performance
26713
26714This section presents several topics related to program performance.
26715It first describes some of the tradeoffs that need to be considered
26716and some of the techniques for making your program run faster.
26717
26718
26719It then documents the unused subprogram/data elimination feature,
26720which can reduce the size of program executables.
26721
26722@menu
26723* Performance Considerations:: 
26724* Text_IO Suggestions:: 
26725* Reducing Size of Executables with Unused Subprogram/Data Elimination:: 
26726
26727@end menu
26728
26729@node Performance Considerations,Text_IO Suggestions,,Improving Performance
26730@anchor{gnat_ugn/gnat_and_program_execution id29}@anchor{227}@anchor{gnat_ugn/gnat_and_program_execution performance-considerations}@anchor{228}
26731@subsection Performance Considerations
26732
26733
26734The GNAT system provides a number of options that allow a trade-off
26735between
26736
26737
26738@itemize *
26739
26740@item 
26741performance of the generated code
26742
26743@item 
26744speed of compilation
26745
26746@item 
26747minimization of dependences and recompilation
26748
26749@item 
26750the degree of run-time checking.
26751@end itemize
26752
26753The defaults (if no options are selected) aim at improving the speed
26754of compilation and minimizing dependences, at the expense of performance
26755of the generated code:
26756
26757
26758@itemize *
26759
26760@item 
26761no optimization
26762
26763@item 
26764no inlining of subprogram calls
26765
26766@item 
26767all run-time checks enabled except overflow and elaboration checks
26768@end itemize
26769
26770These options are suitable for most program development purposes. This
26771section describes how you can modify these choices, and also provides
26772some guidelines on debugging optimized code.
26773
26774@menu
26775* Controlling Run-Time Checks:: 
26776* Use of Restrictions:: 
26777* Optimization Levels:: 
26778* Debugging Optimized Code:: 
26779* Inlining of Subprograms:: 
26780* Floating_Point_Operations:: 
26781* Vectorization of loops:: 
26782* Other Optimization Switches:: 
26783* Optimization and Strict Aliasing:: 
26784* Aliased Variables and Optimization:: 
26785* Atomic Variables and Optimization:: 
26786* Passive Task Optimization:: 
26787
26788@end menu
26789
26790@node Controlling Run-Time Checks,Use of Restrictions,,Performance Considerations
26791@anchor{gnat_ugn/gnat_and_program_execution controlling-run-time-checks}@anchor{229}@anchor{gnat_ugn/gnat_and_program_execution id30}@anchor{22a}
26792@subsubsection Controlling Run-Time Checks
26793
26794
26795By default, GNAT generates all run-time checks, except integer overflow
26796checks, stack overflow checks, and checks for access before elaboration on
26797subprogram calls. The latter are not required in default mode, because all
26798necessary checking is done at compile time.
26799
26800@geindex -gnatp (gcc)
26801
26802@geindex -gnato (gcc)
26803
26804Two gnat switches, @emph{-gnatp} and @emph{-gnato} allow this default to
26805be modified. See @ref{fe,,Run-Time Checks}.
26806
26807Our experience is that the default is suitable for most development
26808purposes.
26809
26810We treat integer overflow specially because these
26811are quite expensive and in our experience are not as important as other
26812run-time checks in the development process. Note that division by zero
26813is not considered an overflow check, and divide by zero checks are
26814generated where required by default.
26815
26816Elaboration checks are off by default, and also not needed by default, since
26817GNAT uses a static elaboration analysis approach that avoids the need for
26818run-time checking. This manual contains a full chapter discussing the issue
26819of elaboration checks, and if the default is not satisfactory for your use,
26820you should read this chapter.
26821
26822For validity checks, the minimal checks required by the Ada Reference
26823Manual (for case statements and assignments to array elements) are on
26824by default. These can be suppressed by use of the @emph{-gnatVn} switch.
26825Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
26826is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
26827it may be reasonable to routinely use @emph{-gnatVn}. Validity checks
26828are also suppressed entirely if @emph{-gnatp} is used.
26829
26830@geindex Overflow checks
26831
26832@geindex Checks
26833@geindex overflow
26834
26835@geindex Suppress
26836
26837@geindex Unsuppress
26838
26839@geindex pragma Suppress
26840
26841@geindex pragma Unsuppress
26842
26843Note that the setting of the switches controls the default setting of
26844the checks. They may be modified using either @cite{pragma Suppress} (to
26845remove checks) or @cite{pragma Unsuppress} (to add back suppressed
26846checks) in the program source.
26847
26848@node Use of Restrictions,Optimization Levels,Controlling Run-Time Checks,Performance Considerations
26849@anchor{gnat_ugn/gnat_and_program_execution use-of-restrictions}@anchor{22b}@anchor{gnat_ugn/gnat_and_program_execution id31}@anchor{22c}
26850@subsubsection Use of Restrictions
26851
26852
26853The use of pragma Restrictions allows you to control which features are
26854permitted in your program. Apart from the obvious point that if you avoid
26855relatively expensive features like finalization (enforceable by the use
26856of pragma Restrictions (No_Finalization), the use of this pragma does not
26857affect the generated code in most cases.
26858
26859One notable exception to this rule is that the possibility of task abort
26860results in some distributed overhead, particularly if finalization or
26861exception handlers are used. The reason is that certain sections of code
26862have to be marked as non-abortable.
26863
26864If you use neither the @cite{abort} statement, nor asynchronous transfer
26865of control (@cite{select ... then abort}), then this distributed overhead
26866is removed, which may have a general positive effect in improving
26867overall performance.  Especially code involving frequent use of tasking
26868constructs and controlled types will show much improved performance.
26869The relevant restrictions pragmas are
26870
26871@quotation
26872
26873@example
26874pragma Restrictions (No_Abort_Statements);
26875pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
26876@end example
26877@end quotation
26878
26879It is recommended that these restriction pragmas be used if possible. Note
26880that this also means that you can write code without worrying about the
26881possibility of an immediate abort at any point.
26882
26883@node Optimization Levels,Debugging Optimized Code,Use of Restrictions,Performance Considerations
26884@anchor{gnat_ugn/gnat_and_program_execution id32}@anchor{22d}@anchor{gnat_ugn/gnat_and_program_execution optimization-levels}@anchor{101}
26885@subsubsection Optimization Levels
26886
26887
26888@geindex -O (gcc)
26889
26890Without any optimization option,
26891the compiler's goal is to reduce the cost of
26892compilation and to make debugging produce the expected results.
26893Statements are independent: if you stop the program with a breakpoint between
26894statements, you can then assign a new value to any variable or change
26895the program counter to any other statement in the subprogram and get exactly
26896the results you would expect from the source code.
26897
26898Turning on optimization makes the compiler attempt to improve the
26899performance and/or code size at the expense of compilation time and
26900possibly the ability to debug the program.
26901
26902If you use multiple
26903-O options, with or without level numbers,
26904the last such option is the one that is effective.
26905
26906The default is optimization off. This results in the fastest compile
26907times, but GNAT makes absolutely no attempt to optimize, and the
26908generated programs are considerably larger and slower than when
26909optimization is enabled. You can use the
26910@emph{-O} switch (the permitted forms are @emph{-O0}, @emph{-O1}
26911@emph{-O2}, @emph{-O3}, and @emph{-Os})
26912to @emph{gcc} to control the optimization level:
26913
26914
26915@itemize *
26916
26917@item 
26918
26919@table @asis
26920
26921@item @emph{-O0}
26922
26923No optimization (the default);
26924generates unoptimized code but has
26925the fastest compilation time.
26926
26927Note that many other compilers do fairly extensive optimization
26928even if 'no optimization' is specified. With gcc, it is
26929very unusual to use -O0 for production if
26930execution time is of any concern, since -O0
26931really does mean no optimization at all. This difference between
26932gcc and other compilers should be kept in mind when doing
26933performance comparisons.
26934@end table
26935
26936@item 
26937
26938@table @asis
26939
26940@item @emph{-O1}
26941
26942Moderate optimization;
26943optimizes reasonably well but does not
26944degrade compilation time significantly.
26945@end table
26946
26947@item 
26948
26949@table @asis
26950
26951@item @emph{-O2}
26952
26953Full optimization;
26954generates highly optimized code and has
26955the slowest compilation time.
26956@end table
26957
26958@item 
26959
26960@table @asis
26961
26962@item @emph{-O3}
26963
26964Full optimization as in @emph{-O2};
26965also uses more aggressive automatic inlining of subprograms within a unit
26966(@ref{114,,Inlining of Subprograms}) and attempts to vectorize loops.
26967@end table
26968
26969@item 
26970
26971@table @asis
26972
26973@item @emph{-Os}
26974
26975Optimize space usage (code and data) of resulting program.
26976@end table
26977@end itemize
26978
26979Higher optimization levels perform more global transformations on the
26980program and apply more expensive analysis algorithms in order to generate
26981faster and more compact code. The price in compilation time, and the
26982resulting improvement in execution time,
26983both depend on the particular application and the hardware environment.
26984You should experiment to find the best level for your application.
26985
26986Since the precise set of optimizations done at each level will vary from
26987release to release (and sometime from target to target), it is best to think
26988of the optimization settings in general terms.
26989See the @emph{Options That Control Optimization} section in
26990@cite{Using the GNU Compiler Collection (GCC)}
26991for details about
26992the @emph{-O} settings and a number of @emph{-f} options that
26993individually enable or disable specific optimizations.
26994
26995Unlike some other compilation systems, @emph{gcc} has
26996been tested extensively at all optimization levels. There are some bugs
26997which appear only with optimization turned on, but there have also been
26998bugs which show up only in @emph{unoptimized} code. Selecting a lower
26999level of optimization does not improve the reliability of the code
27000generator, which in practice is highly reliable at all optimization
27001levels.
27002
27003Note regarding the use of @emph{-O3}: The use of this optimization level
27004is generally discouraged with GNAT, since it often results in larger
27005executables which may run more slowly. See further discussion of this point
27006in @ref{114,,Inlining of Subprograms}.
27007
27008@node Debugging Optimized Code,Inlining of Subprograms,Optimization Levels,Performance Considerations
27009@anchor{gnat_ugn/gnat_and_program_execution id33}@anchor{22e}@anchor{gnat_ugn/gnat_and_program_execution debugging-optimized-code}@anchor{22f}
27010@subsubsection Debugging Optimized Code
27011
27012
27013@geindex Debugging optimized code
27014
27015@geindex Optimization and debugging
27016
27017Although it is possible to do a reasonable amount of debugging at
27018nonzero optimization levels,
27019the higher the level the more likely that
27020source-level constructs will have been eliminated by optimization.
27021For example, if a loop is strength-reduced, the loop
27022control variable may be completely eliminated and thus cannot be
27023displayed in the debugger.
27024This can only happen at @emph{-O2} or @emph{-O3}.
27025Explicit temporary variables that you code might be eliminated at
27026level @emph{-O1} or higher.
27027
27028@geindex -g (gcc)
27029
27030The use of the @emph{-g} switch,
27031which is needed for source-level debugging,
27032affects the size of the program executable on disk,
27033and indeed the debugging information can be quite large.
27034However, it has no effect on the generated code (and thus does not
27035degrade performance)
27036
27037Since the compiler generates debugging tables for a compilation unit before
27038it performs optimizations, the optimizing transformations may invalidate some
27039of the debugging data.  You therefore need to anticipate certain
27040anomalous situations that may arise while debugging optimized code.
27041These are the most common cases:
27042
27043
27044@itemize *
27045
27046@item 
27047@emph{The 'hopping Program Counter':}  Repeated @cite{step} or @cite{next}
27048commands show
27049the PC bouncing back and forth in the code.  This may result from any of
27050the following optimizations:
27051
27052
27053@itemize -
27054
27055@item 
27056@emph{Common subexpression elimination:} using a single instance of code for a
27057quantity that the source computes several times.  As a result you
27058may not be able to stop on what looks like a statement.
27059
27060@item 
27061@emph{Invariant code motion:} moving an expression that does not change within a
27062loop, to the beginning of the loop.
27063
27064@item 
27065@emph{Instruction scheduling:} moving instructions so as to
27066overlap loads and stores (typically) with other code, or in
27067general to move computations of values closer to their uses. Often
27068this causes you to pass an assignment statement without the assignment
27069happening and then later bounce back to the statement when the
27070value is actually needed.  Placing a breakpoint on a line of code
27071and then stepping over it may, therefore, not always cause all the
27072expected side-effects.
27073@end itemize
27074
27075@item 
27076@emph{The 'big leap':} More commonly known as @emph{cross-jumping}, in which
27077two identical pieces of code are merged and the program counter suddenly
27078jumps to a statement that is not supposed to be executed, simply because
27079it (and the code following) translates to the same thing as the code
27080that @emph{was} supposed to be executed.  This effect is typically seen in
27081sequences that end in a jump, such as a @cite{goto}, a @cite{return}, or
27082a @cite{break} in a C @cite{switch} statement.
27083
27084@item 
27085@emph{The 'roving variable':} The symptom is an unexpected value in a variable.
27086There are various reasons for this effect:
27087
27088
27089@itemize -
27090
27091@item 
27092In a subprogram prologue, a parameter may not yet have been moved to its
27093'home'.
27094
27095@item 
27096A variable may be dead, and its register re-used.  This is
27097probably the most common cause.
27098
27099@item 
27100As mentioned above, the assignment of a value to a variable may
27101have been moved.
27102
27103@item 
27104A variable may be eliminated entirely by value propagation or
27105other means.  In this case, GCC may incorrectly generate debugging
27106information for the variable
27107@end itemize
27108
27109In general, when an unexpected value appears for a local variable or parameter
27110you should first ascertain if that value was actually computed by
27111your program, as opposed to being incorrectly reported by the debugger.
27112Record fields or
27113array elements in an object designated by an access value
27114are generally less of a problem, once you have ascertained that the access
27115value is sensible.
27116Typically, this means checking variables in the preceding code and in the
27117calling subprogram to verify that the value observed is explainable from other
27118values (one must apply the procedure recursively to those
27119other values); or re-running the code and stopping a little earlier
27120(perhaps before the call) and stepping to better see how the variable obtained
27121the value in question; or continuing to step @emph{from} the point of the
27122strange value to see if code motion had simply moved the variable's
27123assignments later.
27124@end itemize
27125
27126In light of such anomalies, a recommended technique is to use @emph{-O0}
27127early in the software development cycle, when extensive debugging capabilities
27128are most needed, and then move to @emph{-O1} and later @emph{-O2} as
27129the debugger becomes less critical.
27130Whether to use the @emph{-g} switch in the release version is
27131a release management issue.
27132Note that if you use @emph{-g} you can then use the @emph{strip} program
27133on the resulting executable,
27134which removes both debugging information and global symbols.
27135
27136@node Inlining of Subprograms,Floating_Point_Operations,Debugging Optimized Code,Performance Considerations
27137@anchor{gnat_ugn/gnat_and_program_execution id34}@anchor{230}@anchor{gnat_ugn/gnat_and_program_execution inlining-of-subprograms}@anchor{114}
27138@subsubsection Inlining of Subprograms
27139
27140
27141A call to a subprogram in the current unit is inlined if all the
27142following conditions are met:
27143
27144
27145@itemize *
27146
27147@item 
27148The optimization level is at least @emph{-O1}.
27149
27150@item 
27151The called subprogram is suitable for inlining: It must be small enough
27152and not contain something that @emph{gcc} cannot support in inlined
27153subprograms.
27154
27155@geindex pragma Inline
27156
27157@geindex Inline
27158
27159@item 
27160Any one of the following applies: @cite{pragma Inline} is applied to the
27161subprogram and the @emph{-gnatn} switch is specified; the
27162subprogram is local to the unit and called once from within it; the
27163subprogram is small and optimization level @emph{-O2} is specified;
27164optimization level @emph{-O3} is specified.
27165@end itemize
27166
27167Calls to subprograms in @emph{with}ed units are normally not inlined.
27168To achieve actual inlining (that is, replacement of the call by the code
27169in the body of the subprogram), the following conditions must all be true:
27170
27171
27172@itemize *
27173
27174@item 
27175The optimization level is at least @emph{-O1}.
27176
27177@item 
27178The called subprogram is suitable for inlining: It must be small enough
27179and not contain something that @emph{gcc} cannot support in inlined
27180subprograms.
27181
27182@item 
27183The call appears in a body (not in a package spec).
27184
27185@item 
27186There is a @cite{pragma Inline} for the subprogram.
27187
27188@item 
27189The @emph{-gnatn} switch is used on the command line.
27190@end itemize
27191
27192Even if all these conditions are met, it may not be possible for
27193the compiler to inline the call, due to the length of the body,
27194or features in the body that make it impossible for the compiler
27195to do the inlining.
27196
27197Note that specifying the @emph{-gnatn} switch causes additional
27198compilation dependencies. Consider the following:
27199
27200@quotation
27201
27202@example
27203package R is
27204   procedure Q;
27205   pragma Inline (Q);
27206end R;
27207package body R is
27208   ...
27209end R;
27210
27211with R;
27212procedure Main is
27213begin
27214   ...
27215   R.Q;
27216end Main;
27217@end example
27218@end quotation
27219
27220With the default behavior (no @emph{-gnatn} switch specified), the
27221compilation of the @cite{Main} procedure depends only on its own source,
27222@code{main.adb}, and the spec of the package in file @code{r.ads}. This
27223means that editing the body of @cite{R} does not require recompiling
27224@cite{Main}.
27225
27226On the other hand, the call @cite{R.Q} is not inlined under these
27227circumstances. If the @emph{-gnatn} switch is present when @cite{Main}
27228is compiled, the call will be inlined if the body of @cite{Q} is small
27229enough, but now @cite{Main} depends on the body of @cite{R} in
27230@code{r.adb} as well as on the spec. This means that if this body is edited,
27231the main program must be recompiled. Note that this extra dependency
27232occurs whether or not the call is in fact inlined by @emph{gcc}.
27233
27234The use of front end inlining with @emph{-gnatN} generates similar
27235additional dependencies.
27236
27237@geindex -fno-inline (gcc)
27238
27239Note: The @emph{-fno-inline} switch overrides all other conditions and ensures that
27240no inlining occurs, unless requested with pragma Inline_Always for gcc
27241back-ends. The extra dependences resulting from @emph{-gnatn} will still be active,
27242even if this switch is used to suppress the resulting inlining actions.
27243
27244@geindex -fno-inline-functions (gcc)
27245
27246Note: The @emph{-fno-inline-functions} switch can be used to prevent
27247automatic inlining of subprograms if @emph{-O3} is used.
27248
27249@geindex -fno-inline-small-functions (gcc)
27250
27251Note: The @emph{-fno-inline-small-functions} switch can be used to prevent
27252automatic inlining of small subprograms if @emph{-O2} is used.
27253
27254@geindex -fno-inline-functions-called-once (gcc)
27255
27256Note: The @emph{-fno-inline-functions-called-once} switch
27257can be used to prevent inlining of subprograms local to the unit
27258and called once from within it if @emph{-O1} is used.
27259
27260Note regarding the use of @emph{-O3}: @emph{-gnatn} is made up of two
27261sub-switches @emph{-gnatn1} and @emph{-gnatn2} that can be directly
27262specified in lieu of it, @emph{-gnatn} being translated into one of them
27263based on the optimization level. With @emph{-O2} or below, @emph{-gnatn}
27264is equivalent to @emph{-gnatn1} which activates pragma @cite{Inline} with
27265moderate inlining across modules. With @emph{-O3}, @emph{-gnatn} is
27266equivalent to @emph{-gnatn2} which activates pragma @cite{Inline} with
27267full inlining across modules. If you have used pragma @cite{Inline} in
27268appropriate cases, then it is usually much better to use @emph{-O2}
27269and @emph{-gnatn} and avoid the use of @emph{-O3} which has the additional
27270effect of inlining subprograms you did not think should be inlined. We have
27271found that the use of @emph{-O3} may slow down the compilation and increase
27272the code size by performing excessive inlining, leading to increased
27273instruction cache pressure from the increased code size and thus minor
27274performance improvements. So the bottom line here is that you should not
27275automatically assume that @emph{-O3} is better than @emph{-O2}, and
27276indeed you should use @emph{-O3} only if tests show that it actually
27277improves performance for your program.
27278
27279@node Floating_Point_Operations,Vectorization of loops,Inlining of Subprograms,Performance Considerations
27280@anchor{gnat_ugn/gnat_and_program_execution floating-point-operations}@anchor{231}@anchor{gnat_ugn/gnat_and_program_execution id35}@anchor{232}
27281@subsubsection Floating_Point_Operations
27282
27283
27284@geindex Floating-Point Operations
27285
27286On almost all targets, GNAT maps Float and Long_Float to the 32-bit and
2728764-bit standard IEEE floating-point representations, and operations will
27288use standard IEEE arithmetic as provided by the processor. On most, but
27289not all, architectures, the attribute Machine_Overflows is False for these
27290types, meaning that the semantics of overflow is implementation-defined.
27291In the case of GNAT, these semantics correspond to the normal IEEE
27292treatment of infinities and NaN (not a number) values. For example,
272931.0 / 0.0 yields plus infinitiy and 0.0 / 0.0 yields a NaN. By
27294avoiding explicit overflow checks, the performance is greatly improved
27295on many targets. However, if required, floating-point overflow can be
27296enabled by the use of the pragma Check_Float_Overflow.
27297
27298Another consideration that applies specifically to x86 32-bit
27299architectures is which form of floating-point arithmetic is used.
27300By default the operations use the old style x86 floating-point,
27301which implements an 80-bit extended precision form (on these
27302architectures the type Long_Long_Float corresponds to that form).
27303In addition, generation of efficient code in this mode means that
27304the extended precision form will be used for intermediate results.
27305This may be helpful in improving the final precision of a complex
27306expression. However it means that the results obtained on the x86
27307will be different from those on other architectures, and for some
27308algorithms, the extra intermediate precision can be detrimental.
27309
27310In addition to this old-style floating-point, all modern x86 chips
27311implement an alternative floating-point operation model referred
27312to as SSE2. In this model there is no extended form, and furthermore
27313execution performance is significantly enhanced. To force GNAT to use
27314this more modern form, use both of the switches:
27315
27316@quotation
27317
27318-msse2 -mfpmath=sse
27319@end quotation
27320
27321A unit compiled with these switches will automatically use the more
27322efficient SSE2 instruction set for Float and Long_Float operations.
27323Note that the ABI has the same form for both floating-point models,
27324so it is permissible to mix units compiled with and without these
27325switches.
27326
27327@node Vectorization of loops,Other Optimization Switches,Floating_Point_Operations,Performance Considerations
27328@anchor{gnat_ugn/gnat_and_program_execution id36}@anchor{233}@anchor{gnat_ugn/gnat_and_program_execution vectorization-of-loops}@anchor{234}
27329@subsubsection Vectorization of loops
27330
27331
27332@geindex Optimization Switches
27333
27334You can take advantage of the auto-vectorizer present in the @emph{gcc}
27335back end to vectorize loops with GNAT.  The corresponding command line switch
27336is @emph{-ftree-vectorize} but, as it is enabled by default at @emph{-O3}
27337and other aggressive optimizations helpful for vectorization also are enabled
27338by default at this level, using @emph{-O3} directly is recommended.
27339
27340You also need to make sure that the target architecture features a supported
27341SIMD instruction set.  For example, for the x86 architecture, you should at
27342least specify @emph{-msse2} to get significant vectorization (but you don't
27343need to specify it for x86-64 as it is part of the base 64-bit architecture).
27344Similarly, for the PowerPC architecture, you should specify @emph{-maltivec}.
27345
27346The preferred loop form for vectorization is the @cite{for} iteration scheme.
27347Loops with a @cite{while} iteration scheme can also be vectorized if they are
27348very simple, but the vectorizer will quickly give up otherwise.  With either
27349iteration scheme, the flow of control must be straight, in particular no
27350@cite{exit} statement may appear in the loop body.  The loop may however
27351contain a single nested loop, if it can be vectorized when considered alone:
27352
27353@quotation
27354
27355@example
27356A : array (1..4, 1..4) of Long_Float;
27357S : array (1..4) of Long_Float;
27358
27359procedure Sum is
27360begin
27361   for I in A'Range(1) loop
27362      for J in A'Range(2) loop
27363         S (I) := S (I) + A (I, J);
27364      end loop;
27365   end loop;
27366end Sum;
27367@end example
27368@end quotation
27369
27370The vectorizable operations depend on the targeted SIMD instruction set, but
27371the adding and some of the multiplying operators are generally supported, as
27372well as the logical operators for modular types.  Note that, in the former
27373case, enabling overflow checks, for example with @emph{-gnato}, totally
27374disables vectorization.  The other checks are not supposed to have the same
27375definitive effect, although compiling with @emph{-gnatp} might well reveal
27376cases where some checks do thwart vectorization.
27377
27378Type conversions may also prevent vectorization if they involve semantics that
27379are not directly supported by the code generator or the SIMD instruction set.
27380A typical example is direct conversion from floating-point to integer types.
27381The solution in this case is to use the following idiom:
27382
27383@quotation
27384
27385@example
27386Integer (S'Truncation (F))
27387@end example
27388@end quotation
27389
27390if @cite{S} is the subtype of floating-point object @cite{F}.
27391
27392In most cases, the vectorizable loops are loops that iterate over arrays.
27393All kinds of array types are supported, i.e. constrained array types with
27394static bounds:
27395
27396@quotation
27397
27398@example
27399type Array_Type is array (1 .. 4) of Long_Float;
27400@end example
27401@end quotation
27402
27403constrained array types with dynamic bounds:
27404
27405@quotation
27406
27407@example
27408type Array_Type is array (1 .. Q.N) of Long_Float;
27409
27410type Array_Type is array (Q.K .. 4) of Long_Float;
27411
27412type Array_Type is array (Q.K .. Q.N) of Long_Float;
27413@end example
27414@end quotation
27415
27416or unconstrained array types:
27417
27418@quotation
27419
27420@example
27421type Array_Type is array (Positive range <>) of Long_Float;
27422@end example
27423@end quotation
27424
27425The quality of the generated code decreases when the dynamic aspect of the
27426array type increases, the worst code being generated for unconstrained array
27427types.  This is so because, the less information the compiler has about the
27428bounds of the array, the more fallback code it needs to generate in order to
27429fix things up at run time.
27430
27431It is possible to specify that a given loop should be subject to vectorization
27432preferably to other optimizations by means of pragma @cite{Loop_Optimize}:
27433
27434@quotation
27435
27436@example
27437pragma Loop_Optimize (Vector);
27438@end example
27439@end quotation
27440
27441placed immediately within the loop will convey the appropriate hint to the
27442compiler for this loop.
27443
27444It is also possible to help the compiler generate better vectorized code
27445for a given loop by asserting that there are no loop-carried dependencies
27446in the loop.  Consider for example the procedure:
27447
27448@quotation
27449
27450@example
27451type Arr is array (1 .. 4) of Long_Float;
27452
27453procedure Add (X, Y : not null access Arr; R : not null access Arr) is
27454begin
27455  for I in Arr'Range loop
27456    R(I) := X(I) + Y(I);
27457  end loop;
27458end;
27459@end example
27460@end quotation
27461
27462By default, the compiler cannot unconditionally vectorize the loop because
27463assigning to a component of the array designated by R in one iteration could
27464change the value read from the components of the array designated by X or Y
27465in a later iteration.  As a result, the compiler will generate two versions
27466of the loop in the object code, one vectorized and the other not vectorized,
27467as well as a test to select the appropriate version at run time.  This can
27468be overcome by another hint:
27469
27470@quotation
27471
27472@example
27473pragma Loop_Optimize (Ivdep);
27474@end example
27475@end quotation
27476
27477placed immediately within the loop will tell the compiler that it can safely
27478omit the non-vectorized version of the loop as well as the run-time test.
27479
27480@node Other Optimization Switches,Optimization and Strict Aliasing,Vectorization of loops,Performance Considerations
27481@anchor{gnat_ugn/gnat_and_program_execution id37}@anchor{235}@anchor{gnat_ugn/gnat_and_program_execution other-optimization-switches}@anchor{236}
27482@subsubsection Other Optimization Switches
27483
27484
27485@geindex Optimization Switches
27486
27487Since @cite{GNAT} uses the @emph{gcc} back end, all the specialized
27488@emph{gcc} optimization switches are potentially usable. These switches
27489have not been extensively tested with GNAT but can generally be expected
27490to work. Examples of switches in this category are @emph{-funroll-loops}
27491and the various target-specific @emph{-m} options (in particular, it has
27492been observed that @emph{-march=xxx} can significantly improve performance
27493on appropriate machines). For full details of these switches, see
27494the @cite{Submodel Options} section in the @cite{Hardware Models and Configurations}
27495chapter of @cite{Using the GNU Compiler Collection (GCC)}.
27496
27497@node Optimization and Strict Aliasing,Aliased Variables and Optimization,Other Optimization Switches,Performance Considerations
27498@anchor{gnat_ugn/gnat_and_program_execution optimization-and-strict-aliasing}@anchor{f8}@anchor{gnat_ugn/gnat_and_program_execution id38}@anchor{237}
27499@subsubsection Optimization and Strict Aliasing
27500
27501
27502@geindex Aliasing
27503
27504@geindex Strict Aliasing
27505
27506@geindex No_Strict_Aliasing
27507
27508The strong typing capabilities of Ada allow an optimizer to generate
27509efficient code in situations where other languages would be forced to
27510make worst case assumptions preventing such optimizations. Consider
27511the following example:
27512
27513@quotation
27514
27515@example
27516procedure R is
27517   type Int1 is new Integer;
27518   type Int2 is new Integer;
27519   type Int1A is access Int1;
27520   type Int2A is access Int2;
27521   Int1V : Int1A;
27522   Int2V : Int2A;
27523   ...
27524
27525begin
27526   ...
27527   for J in Data'Range loop
27528      if Data (J) = Int1V.all then
27529         Int2V.all := Int2V.all + 1;
27530      end if;
27531   end loop;
27532   ...
27533end R;
27534@end example
27535@end quotation
27536
27537In this example, since the variable @cite{Int1V} can only access objects
27538of type @cite{Int1}, and @cite{Int2V} can only access objects of type
27539@cite{Int2}, there is no possibility that the assignment to
27540@cite{Int2V.all} affects the value of @cite{Int1V.all}. This means that
27541the compiler optimizer can "know" that the value @cite{Int1V.all} is constant
27542for all iterations of the loop and avoid the extra memory reference
27543required to dereference it each time through the loop.
27544
27545This kind of optimization, called strict aliasing analysis, is
27546triggered by specifying an optimization level of @emph{-O2} or
27547higher or @emph{-Os} and allows @cite{GNAT} to generate more efficient code
27548when access values are involved.
27549
27550However, although this optimization is always correct in terms of
27551the formal semantics of the Ada Reference Manual, difficulties can
27552arise if features like @cite{Unchecked_Conversion} are used to break
27553the typing system. Consider the following complete program example:
27554
27555@quotation
27556
27557@example
27558package p1 is
27559   type int1 is new integer;
27560   type int2 is new integer;
27561   type a1 is access int1;
27562   type a2 is access int2;
27563end p1;
27564
27565with p1; use p1;
27566package p2 is
27567   function to_a2 (Input : a1) return a2;
27568end p2;
27569
27570with Unchecked_Conversion;
27571package body p2 is
27572   function to_a2 (Input : a1) return a2 is
27573      function to_a2u is
27574        new Unchecked_Conversion (a1, a2);
27575   begin
27576      return to_a2u (Input);
27577   end to_a2;
27578end p2;
27579
27580with p2; use p2;
27581with p1; use p1;
27582with Text_IO; use Text_IO;
27583procedure m is
27584   v1 : a1 := new int1;
27585   v2 : a2 := to_a2 (v1);
27586begin
27587   v1.all := 1;
27588   v2.all := 0;
27589   put_line (int1'image (v1.all));
27590end;
27591@end example
27592@end quotation
27593
27594This program prints out 0 in @emph{-O0} or @emph{-O1}
27595mode, but it prints out 1 in @emph{-O2} mode. That's
27596because in strict aliasing mode, the compiler can and
27597does assume that the assignment to @cite{v2.all} could not
27598affect the value of @cite{v1.all}, since different types
27599are involved.
27600
27601This behavior is not a case of non-conformance with the standard, since
27602the Ada RM specifies that an unchecked conversion where the resulting
27603bit pattern is not a correct value of the target type can result in an
27604abnormal value and attempting to reference an abnormal value makes the
27605execution of a program erroneous.  That's the case here since the result
27606does not point to an object of type @cite{int2}.  This means that the
27607effect is entirely unpredictable.
27608
27609However, although that explanation may satisfy a language
27610lawyer, in practice an applications programmer expects an
27611unchecked conversion involving pointers to create true
27612aliases and the behavior of printing 1 seems plain wrong.
27613In this case, the strict aliasing optimization is unwelcome.
27614
27615Indeed the compiler recognizes this possibility, and the
27616unchecked conversion generates a warning:
27617
27618@quotation
27619
27620@example
27621p2.adb:5:07: warning: possible aliasing problem with type "a2"
27622p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
27623p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
27624@end example
27625@end quotation
27626
27627Unfortunately the problem is recognized when compiling the body of
27628package @cite{p2}, but the actual "bad" code is generated while
27629compiling the body of @cite{m} and this latter compilation does not see
27630the suspicious @cite{Unchecked_Conversion}.
27631
27632As implied by the warning message, there are approaches you can use to
27633avoid the unwanted strict aliasing optimization in a case like this.
27634
27635One possibility is to simply avoid the use of @emph{-O2}, but
27636that is a bit drastic, since it throws away a number of useful
27637optimizations that do not involve strict aliasing assumptions.
27638
27639A less drastic approach is to compile the program using the
27640option @emph{-fno-strict-aliasing}. Actually it is only the
27641unit containing the dereferencing of the suspicious pointer
27642that needs to be compiled. So in this case, if we compile
27643unit @cite{m} with this switch, then we get the expected
27644value of zero printed. Analyzing which units might need
27645the switch can be painful, so a more reasonable approach
27646is to compile the entire program with options @emph{-O2}
27647and @emph{-fno-strict-aliasing}. If the performance is
27648satisfactory with this combination of options, then the
27649advantage is that the entire issue of possible "wrong"
27650optimization due to strict aliasing is avoided.
27651
27652To avoid the use of compiler switches, the configuration
27653pragma @cite{No_Strict_Aliasing} with no parameters may be
27654used to specify that for all access types, the strict
27655aliasing optimization should be suppressed.
27656
27657However, these approaches are still overkill, in that they causes
27658all manipulations of all access values to be deoptimized. A more
27659refined approach is to concentrate attention on the specific
27660access type identified as problematic.
27661
27662First, if a careful analysis of uses of the pointer shows
27663that there are no possible problematic references, then
27664the warning can be suppressed by bracketing the
27665instantiation of @cite{Unchecked_Conversion} to turn
27666the warning off:
27667
27668@quotation
27669
27670@example
27671pragma Warnings (Off);
27672function to_a2u is
27673  new Unchecked_Conversion (a1, a2);
27674pragma Warnings (On);
27675@end example
27676@end quotation
27677
27678Of course that approach is not appropriate for this particular
27679example, since indeed there is a problematic reference. In this
27680case we can take one of two other approaches.
27681
27682The first possibility is to move the instantiation of unchecked
27683conversion to the unit in which the type is declared. In
27684this example, we would move the instantiation of
27685@cite{Unchecked_Conversion} from the body of package
27686@cite{p2} to the spec of package @cite{p1}. Now the
27687warning disappears. That's because any use of the
27688access type knows there is a suspicious unchecked
27689conversion, and the strict aliasing optimization
27690is automatically suppressed for the type.
27691
27692If it is not practical to move the unchecked conversion to the same unit
27693in which the destination access type is declared (perhaps because the
27694source type is not visible in that unit), you may use pragma
27695@cite{No_Strict_Aliasing} for the type. This pragma must occur in the
27696same declarative sequence as the declaration of the access type:
27697
27698@quotation
27699
27700@example
27701type a2 is access int2;
27702pragma No_Strict_Aliasing (a2);
27703@end example
27704@end quotation
27705
27706Here again, the compiler now knows that the strict aliasing optimization
27707should be suppressed for any reference to type @cite{a2} and the
27708expected behavior is obtained.
27709
27710Finally, note that although the compiler can generate warnings for
27711simple cases of unchecked conversions, there are tricker and more
27712indirect ways of creating type incorrect aliases which the compiler
27713cannot detect. Examples are the use of address overlays and unchecked
27714conversions involving composite types containing access types as
27715components. In such cases, no warnings are generated, but there can
27716still be aliasing problems. One safe coding practice is to forbid the
27717use of address clauses for type overlaying, and to allow unchecked
27718conversion only for primitive types. This is not really a significant
27719restriction since any possible desired effect can be achieved by
27720unchecked conversion of access values.
27721
27722The aliasing analysis done in strict aliasing mode can certainly
27723have significant benefits. We have seen cases of large scale
27724application code where the time is increased by up to 5% by turning
27725this optimization off. If you have code that includes significant
27726usage of unchecked conversion, you might want to just stick with
27727@emph{-O1} and avoid the entire issue. If you get adequate
27728performance at this level of optimization level, that's probably
27729the safest approach. If tests show that you really need higher
27730levels of optimization, then you can experiment with @emph{-O2}
27731and @emph{-O2 -fno-strict-aliasing} to see how much effect this
27732has on size and speed of the code. If you really need to use
27733@emph{-O2} with strict aliasing in effect, then you should
27734review any uses of unchecked conversion of access types,
27735particularly if you are getting the warnings described above.
27736
27737@node Aliased Variables and Optimization,Atomic Variables and Optimization,Optimization and Strict Aliasing,Performance Considerations
27738@anchor{gnat_ugn/gnat_and_program_execution aliased-variables-and-optimization}@anchor{238}@anchor{gnat_ugn/gnat_and_program_execution id39}@anchor{239}
27739@subsubsection Aliased Variables and Optimization
27740
27741
27742@geindex Aliasing
27743
27744There are scenarios in which programs may
27745use low level techniques to modify variables
27746that otherwise might be considered to be unassigned. For example,
27747a variable can be passed to a procedure by reference, which takes
27748the address of the parameter and uses the address to modify the
27749variable's value, even though it is passed as an IN parameter.
27750Consider the following example:
27751
27752@quotation
27753
27754@example
27755procedure P is
27756   Max_Length : constant Natural := 16;
27757   type Char_Ptr is access all Character;
27758
27759   procedure Get_String(Buffer: Char_Ptr; Size : Integer);
27760   pragma Import (C, Get_String, "get_string");
27761
27762   Name : aliased String (1 .. Max_Length) := (others => ' ');
27763   Temp : Char_Ptr;
27764
27765   function Addr (S : String) return Char_Ptr is
27766      function To_Char_Ptr is
27767        new Ada.Unchecked_Conversion (System.Address, Char_Ptr);
27768   begin
27769      return To_Char_Ptr (S (S'First)'Address);
27770   end;
27771
27772begin
27773   Temp := Addr (Name);
27774   Get_String (Temp, Max_Length);
27775end;
27776@end example
27777@end quotation
27778
27779where Get_String is a C function that uses the address in Temp to
27780modify the variable @cite{Name}. This code is dubious, and arguably
27781erroneous, and the compiler would be entitled to assume that
27782@cite{Name} is never modified, and generate code accordingly.
27783
27784However, in practice, this would cause some existing code that
27785seems to work with no optimization to start failing at high
27786levels of optimzization.
27787
27788What the compiler does for such cases is to assume that marking
27789a variable as aliased indicates that some "funny business" may
27790be going on. The optimizer recognizes the aliased keyword and
27791inhibits optimizations that assume the value cannot be assigned.
27792This means that the above example will in fact "work" reliably,
27793that is, it will produce the expected results.
27794
27795@node Atomic Variables and Optimization,Passive Task Optimization,Aliased Variables and Optimization,Performance Considerations
27796@anchor{gnat_ugn/gnat_and_program_execution atomic-variables-and-optimization}@anchor{23a}@anchor{gnat_ugn/gnat_and_program_execution id40}@anchor{23b}
27797@subsubsection Atomic Variables and Optimization
27798
27799
27800@geindex Atomic
27801
27802There are two considerations with regard to performance when
27803atomic variables are used.
27804
27805First, the RM only guarantees that access to atomic variables
27806be atomic, it has nothing to say about how this is achieved,
27807though there is a strong implication that this should not be
27808achieved by explicit locking code. Indeed GNAT will never
27809generate any locking code for atomic variable access (it will
27810simply reject any attempt to make a variable or type atomic
27811if the atomic access cannot be achieved without such locking code).
27812
27813That being said, it is important to understand that you cannot
27814assume that the entire variable will always be accessed. Consider
27815this example:
27816
27817@quotation
27818
27819@example
27820type R is record
27821   A,B,C,D : Character;
27822end record;
27823for R'Size use 32;
27824for R'Alignment use 4;
27825
27826RV : R;
27827pragma Atomic (RV);
27828X : Character;
27829...
27830X := RV.B;
27831@end example
27832@end quotation
27833
27834You cannot assume that the reference to @cite{RV.B}
27835will read the entire 32-bit
27836variable with a single load instruction. It is perfectly legitimate if
27837the hardware allows it to do a byte read of just the B field. This read
27838is still atomic, which is all the RM requires. GNAT can and does take
27839advantage of this, depending on the architecture and optimization level.
27840Any assumption to the contrary is non-portable and risky. Even if you
27841examine the assembly language and see a full 32-bit load, this might
27842change in a future version of the compiler.
27843
27844If your application requires that all accesses to @cite{RV} in this
27845example be full 32-bit loads, you need to make a copy for the access
27846as in:
27847
27848@quotation
27849
27850@example
27851declare
27852   RV_Copy : constant R := RV;
27853begin
27854   X := RV_Copy.B;
27855end;
27856@end example
27857@end quotation
27858
27859Now the reference to RV must read the whole variable.
27860Actually one can imagine some compiler which figures
27861out that the whole copy is not required (because only
27862the B field is actually accessed), but GNAT
27863certainly won't do that, and we don't know of any
27864compiler that would not handle this right, and the
27865above code will in practice work portably across
27866all architectures (that permit the Atomic declaration).
27867
27868The second issue with atomic variables has to do with
27869the possible requirement of generating synchronization
27870code. For more details on this, consult the sections on
27871the pragmas Enable/Disable_Atomic_Synchronization in the
27872GNAT Reference Manual. If performance is critical, and
27873such synchronization code is not required, it may be
27874useful to disable it.
27875
27876@node Passive Task Optimization,,Atomic Variables and Optimization,Performance Considerations
27877@anchor{gnat_ugn/gnat_and_program_execution id41}@anchor{23c}@anchor{gnat_ugn/gnat_and_program_execution passive-task-optimization}@anchor{23d}
27878@subsubsection Passive Task Optimization
27879
27880
27881@geindex Passive Task
27882
27883A passive task is one which is sufficiently simple that
27884in theory a compiler could recognize it an implement it
27885efficiently without creating a new thread. The original design
27886of Ada 83 had in mind this kind of passive task optimization, but
27887only a few Ada 83 compilers attempted it. The problem was that
27888it was difficult to determine the exact conditions under which
27889the optimization was possible. The result is a very fragile
27890optimization where a very minor change in the program can
27891suddenly silently make a task non-optimizable.
27892
27893With the revisiting of this issue in Ada 95, there was general
27894agreement that this approach was fundamentally flawed, and the
27895notion of protected types was introduced. When using protected
27896types, the restrictions are well defined, and you KNOW that the
27897operations will be optimized, and furthermore this optimized
27898performance is fully portable.
27899
27900Although it would theoretically be possible for GNAT to attempt to
27901do this optimization, but it really doesn't make sense in the
27902context of Ada 95, and none of the Ada 95 compilers implement
27903this optimization as far as we know. In particular GNAT never
27904attempts to perform this optimization.
27905
27906In any new Ada 95 code that is written, you should always
27907use protected types in place of tasks that might be able to
27908be optimized in this manner.
27909Of course this does not help if you have legacy Ada 83 code
27910that depends on this optimization, but it is unusual to encounter
27911a case where the performance gains from this optimization
27912are significant.
27913
27914Your program should work correctly without this optimization. If
27915you have performance problems, then the most practical
27916approach is to figure out exactly where these performance problems
27917arise, and update those particular tasks to be protected types. Note
27918that typically clients of the tasks who call entries, will not have
27919to be modified, only the task definition itself.
27920
27921@node Text_IO Suggestions,Reducing Size of Executables with Unused Subprogram/Data Elimination,Performance Considerations,Improving Performance
27922@anchor{gnat_ugn/gnat_and_program_execution text-io-suggestions}@anchor{23e}@anchor{gnat_ugn/gnat_and_program_execution id42}@anchor{23f}
27923@subsection @cite{Text_IO} Suggestions
27924
27925
27926@geindex Text_IO and performance
27927
27928The @cite{Ada.Text_IO} package has fairly high overheads due in part to
27929the requirement of maintaining page and line counts. If performance
27930is critical, a recommendation is to use @cite{Stream_IO} instead of
27931@cite{Text_IO} for volume output, since this package has less overhead.
27932
27933If @cite{Text_IO} must be used, note that by default output to the standard
27934output and standard error files is unbuffered (this provides better
27935behavior when output statements are used for debugging, or if the
27936progress of a program is observed by tracking the output, e.g. by
27937using the Unix @emph{tail -f} command to watch redirected output.
27938
27939If you are generating large volumes of output with @cite{Text_IO} and
27940performance is an important factor, use a designated file instead
27941of the standard output file, or change the standard output file to
27942be buffered using @cite{Interfaces.C_Streams.setvbuf}.
27943
27944@node Reducing Size of Executables with Unused Subprogram/Data Elimination,,Text_IO Suggestions,Improving Performance
27945@anchor{gnat_ugn/gnat_and_program_execution id43}@anchor{240}@anchor{gnat_ugn/gnat_and_program_execution reducing-size-of-executables-with-unused-subprogram-data-elimination}@anchor{241}
27946@subsection Reducing Size of Executables with Unused Subprogram/Data Elimination
27947
27948
27949@geindex Uunused subprogram/data elimination
27950
27951This section describes how you can eliminate unused subprograms and data from
27952your executable just by setting options at compilation time.
27953
27954@menu
27955* About unused subprogram/data elimination:: 
27956* Compilation options:: 
27957* Example of unused subprogram/data elimination:: 
27958
27959@end menu
27960
27961@node About unused subprogram/data elimination,Compilation options,,Reducing Size of Executables with Unused Subprogram/Data Elimination
27962@anchor{gnat_ugn/gnat_and_program_execution id44}@anchor{242}@anchor{gnat_ugn/gnat_and_program_execution about-unused-subprogram-data-elimination}@anchor{243}
27963@subsubsection About unused subprogram/data elimination
27964
27965
27966By default, an executable contains all code and data of its composing objects
27967(directly linked or coming from statically linked libraries), even data or code
27968never used by this executable.
27969
27970This feature will allow you to eliminate such unused code from your
27971executable, making it smaller (in disk and in memory).
27972
27973This functionality is available on all Linux platforms except for the IA-64
27974architecture and on all cross platforms using the ELF binary file format.
27975In both cases GNU binutils version 2.16 or later are required to enable it.
27976
27977@node Compilation options,Example of unused subprogram/data elimination,About unused subprogram/data elimination,Reducing Size of Executables with Unused Subprogram/Data Elimination
27978@anchor{gnat_ugn/gnat_and_program_execution id45}@anchor{244}@anchor{gnat_ugn/gnat_and_program_execution compilation-options}@anchor{245}
27979@subsubsection Compilation options
27980
27981
27982The operation of eliminating the unused code and data from the final executable
27983is directly performed by the linker.
27984
27985@geindex -ffunction-sections (gcc)
27986
27987@geindex -fdata-sections (gcc)
27988
27989In order to do this, it has to work with objects compiled with the
27990following options:
27991@emph{-ffunction-sections} @emph{-fdata-sections}.
27992
27993These options are usable with C and Ada files.
27994They will place respectively each
27995function or data in a separate section in the resulting object file.
27996
27997Once the objects and static libraries are created with these options, the
27998linker can perform the dead code elimination. You can do this by setting
27999the @emph{-Wl,--gc-sections} option to gcc command or in the
28000@emph{-largs} section of @emph{gnatmake}. This will perform a
28001garbage collection of code and data never referenced.
28002
28003If the linker performs a partial link (@emph{-r} linker option), then you
28004will need to provide the entry point using the @emph{-e} / @emph{--entry}
28005linker option.
28006
28007Note that objects compiled without the @emph{-ffunction-sections} and
28008@emph{-fdata-sections} options can still be linked with the executable.
28009However, no dead code elimination will be performed on those objects (they will
28010be linked as is).
28011
28012The GNAT static library is now compiled with -ffunction-sections and
28013-fdata-sections on some platforms. This allows you to eliminate the unused code
28014and data of the GNAT library from your executable.
28015
28016@node Example of unused subprogram/data elimination,,Compilation options,Reducing Size of Executables with Unused Subprogram/Data Elimination
28017@anchor{gnat_ugn/gnat_and_program_execution id46}@anchor{246}@anchor{gnat_ugn/gnat_and_program_execution example-of-unused-subprogram-data-elimination}@anchor{247}
28018@subsubsection Example of unused subprogram/data elimination
28019
28020
28021Here is a simple example:
28022
28023@quotation
28024
28025@example
28026with Aux;
28027
28028procedure Test is
28029begin
28030   Aux.Used (10);
28031end Test;
28032
28033package Aux is
28034   Used_Data   : Integer;
28035   Unused_Data : Integer;
28036
28037   procedure Used   (Data : Integer);
28038   procedure Unused (Data : Integer);
28039end Aux;
28040
28041package body Aux is
28042   procedure Used (Data : Integer) is
28043   begin
28044      Used_Data := Data;
28045   end Used;
28046
28047   procedure Unused (Data : Integer) is
28048   begin
28049      Unused_Data := Data;
28050   end Unused;
28051end Aux;
28052@end example
28053@end quotation
28054
28055@cite{Unused} and @cite{Unused_Data} are never referenced in this code
28056excerpt, and hence they may be safely removed from the final executable.
28057
28058@quotation
28059
28060@example
28061$ gnatmake test
28062
28063$ nm test | grep used
28064020015f0 T aux__unused
2806502005d88 B aux__unused_data
28066020015cc T aux__used
2806702005d84 B aux__used_data
28068
28069$ gnatmake test -cargs -fdata-sections -ffunction-sections \\
28070     -largs -Wl,--gc-sections
28071
28072$ nm test | grep used
2807302005350 T aux__used
280740201ffe0 B aux__used_data
28075@end example
28076@end quotation
28077
28078It can be observed that the procedure @cite{Unused} and the object
28079@cite{Unused_Data} are removed by the linker when using the
28080appropriate options.
28081
28082@geindex Overflow checks
28083
28084@geindex Checks (overflow)
28085
28086
28087@node Overflow Check Handling in GNAT,Performing Dimensionality Analysis in GNAT,Improving Performance,GNAT and Program Execution
28088@anchor{gnat_ugn/gnat_and_program_execution id54}@anchor{1f3}@anchor{gnat_ugn/gnat_and_program_execution overflow-check-handling-in-gnat}@anchor{29}
28089@section Overflow Check Handling in GNAT
28090
28091
28092This section explains how to control the handling of overflow checks.
28093
28094@menu
28095* Background:: 
28096* Overflow Checking Modes in GNAT:: 
28097* Specifying the Desired Mode:: 
28098* Default Settings:: 
28099* Implementation Notes:: 
28100
28101@end menu
28102
28103@node Background,Overflow Checking Modes in GNAT,,Overflow Check Handling in GNAT
28104@anchor{gnat_ugn/gnat_and_program_execution id55}@anchor{248}@anchor{gnat_ugn/gnat_and_program_execution background}@anchor{249}
28105@subsection Background
28106
28107
28108Overflow checks are checks that the compiler may make to ensure
28109that intermediate results are not out of range. For example:
28110
28111@quotation
28112
28113@example
28114A : Integer;
28115...
28116A := A + 1;
28117@end example
28118@end quotation
28119
28120If @cite{A} has the value @cite{Integer'Last}, then the addition may cause
28121overflow since the result is out of range of the type @cite{Integer}.
28122In this case @cite{Constraint_Error} will be raised if checks are
28123enabled.
28124
28125A trickier situation arises in examples like the following:
28126
28127@quotation
28128
28129@example
28130A, C : Integer;
28131...
28132A := (A + 1) + C;
28133@end example
28134@end quotation
28135
28136where @cite{A} is @cite{Integer'Last} and @cite{C} is @cite{-1}.
28137Now the final result of the expression on the right hand side is
28138@cite{Integer'Last} which is in range, but the question arises whether the
28139intermediate addition of @cite{(A + 1)} raises an overflow error.
28140
28141The (perhaps surprising) answer is that the Ada language
28142definition does not answer this question. Instead it leaves
28143it up to the implementation to do one of two things if overflow
28144checks are enabled.
28145
28146
28147@itemize *
28148
28149@item 
28150raise an exception (@cite{Constraint_Error}), or
28151
28152@item 
28153yield the correct mathematical result which is then used in
28154subsequent operations.
28155@end itemize
28156
28157If the compiler chooses the first approach, then the assignment of this
28158example will indeed raise @cite{Constraint_Error} if overflow checking is
28159enabled, or result in erroneous execution if overflow checks are suppressed.
28160
28161But if the compiler
28162chooses the second approach, then it can perform both additions yielding
28163the correct mathematical result, which is in range, so no exception
28164will be raised, and the right result is obtained, regardless of whether
28165overflow checks are suppressed.
28166
28167Note that in the first example an
28168exception will be raised in either case, since if the compiler
28169gives the correct mathematical result for the addition, it will
28170be out of range of the target type of the assignment, and thus
28171fails the range check.
28172
28173This lack of specified behavior in the handling of overflow for
28174intermediate results is a source of non-portability, and can thus
28175be problematic when programs are ported. Most typically this arises
28176in a situation where the original compiler did not raise an exception,
28177and then the application is moved to a compiler where the check is
28178performed on the intermediate result and an unexpected exception is
28179raised.
28180
28181Furthermore, when using Ada 2012's preconditions and other
28182assertion forms, another issue arises. Consider:
28183
28184@quotation
28185
28186@example
28187procedure P (A, B : Integer) with
28188  Pre => A + B <= Integer'Last;
28189@end example
28190@end quotation
28191
28192One often wants to regard arithmetic in a context like this from
28193a mathematical point of view. So for example, if the two actual parameters
28194for a call to @cite{P} are both @cite{Integer'Last}, then
28195the precondition should be regarded as False. If we are executing
28196in a mode with run-time checks enabled for preconditions, then we would
28197like this precondition to fail, rather than raising an exception
28198because of the intermediate overflow.
28199
28200However, the language definition leaves the specification of
28201whether the above condition fails (raising @cite{Assert_Error}) or
28202causes an intermediate overflow (raising @cite{Constraint_Error})
28203up to the implementation.
28204
28205The situation is worse in a case such as the following:
28206
28207@quotation
28208
28209@example
28210procedure Q (A, B, C : Integer) with
28211  Pre => A + B + C <= Integer'Last;
28212@end example
28213@end quotation
28214
28215Consider the call
28216
28217@quotation
28218
28219@example
28220Q (A => Integer'Last, B => 1, C => -1);
28221@end example
28222@end quotation
28223
28224From a mathematical point of view the precondition
28225is True, but at run time we may (but are not guaranteed to) get an
28226exception raised because of the intermediate overflow (and we really
28227would prefer this precondition to be considered True at run time).
28228
28229@node Overflow Checking Modes in GNAT,Specifying the Desired Mode,Background,Overflow Check Handling in GNAT
28230@anchor{gnat_ugn/gnat_and_program_execution id56}@anchor{24a}@anchor{gnat_ugn/gnat_and_program_execution overflow-checking-modes-in-gnat}@anchor{24b}
28231@subsection Overflow Checking Modes in GNAT
28232
28233
28234To deal with the portability issue, and with the problem of
28235mathematical versus run-time interpretation of the expressions in
28236assertions, GNAT provides comprehensive control over the handling
28237of intermediate overflow. GNAT can operate in three modes, and
28238furthemore, permits separate selection of operating modes for
28239the expressions within assertions (here the term 'assertions'
28240is used in the technical sense, which includes preconditions and so forth)
28241and for expressions appearing outside assertions.
28242
28243The three modes are:
28244
28245
28246@itemize *
28247
28248@item 
28249@emph{Use base type for intermediate operations} (@cite{STRICT})
28250
28251In this mode, all intermediate results for predefined arithmetic
28252operators are computed using the base type, and the result must
28253be in range of the base type. If this is not the
28254case then either an exception is raised (if overflow checks are
28255enabled) or the execution is erroneous (if overflow checks are suppressed).
28256This is the normal default mode.
28257
28258@item 
28259@emph{Most intermediate overflows avoided} (@cite{MINIMIZED})
28260
28261In this mode, the compiler attempts to avoid intermediate overflows by
28262using a larger integer type, typically @cite{Long_Long_Integer},
28263as the type in which arithmetic is
28264performed for predefined arithmetic operators. This may be slightly more
28265expensive at
28266run time (compared to suppressing intermediate overflow checks), though
28267the cost is negligible on modern 64-bit machines. For the examples given
28268earlier, no intermediate overflows would have resulted in exceptions,
28269since the intermediate results are all in the range of
28270@cite{Long_Long_Integer} (typically 64-bits on nearly all implementations
28271of GNAT). In addition, if checks are enabled, this reduces the number of
28272checks that must be made, so this choice may actually result in an
28273improvement in space and time behavior.
28274
28275However, there are cases where @cite{Long_Long_Integer} is not large
28276enough, consider the following example:
28277
28278@quotation
28279
28280@example
28281procedure R (A, B, C, D : Integer) with
28282  Pre => (A**2 * B**2) / (C**2 * D**2) <= 10;
28283@end example
28284@end quotation
28285
28286where @cite{A} = @cite{B} = @cite{C} = @cite{D} = @cite{Integer'Last}.
28287Now the intermediate results are
28288out of the range of @cite{Long_Long_Integer} even though the final result
28289is in range and the precondition is True (from a mathematical point
28290of view). In such a case, operating in this mode, an overflow occurs
28291for the intermediate computation (which is why this mode
28292says @emph{most} intermediate overflows are avoided). In this case,
28293an exception is raised if overflow checks are enabled, and the
28294execution is erroneous if overflow checks are suppressed.
28295
28296@item 
28297@emph{All intermediate overflows avoided} (@cite{ELIMINATED})
28298
28299In this mode, the compiler  avoids all intermediate overflows
28300by using arbitrary precision arithmetic as required. In this
28301mode, the above example with @cite{A**2 * B**2} would
28302not cause intermediate overflow, because the intermediate result
28303would be evaluated using sufficient precision, and the result
28304of evaluating the precondition would be True.
28305
28306This mode has the advantage of avoiding any intermediate
28307overflows, but at the expense of significant run-time overhead,
28308including the use of a library (included automatically in this
28309mode) for multiple-precision arithmetic.
28310
28311This mode provides cleaner semantics for assertions, since now
28312the run-time behavior emulates true arithmetic behavior for the
28313predefined arithmetic operators, meaning that there is never a
28314conflict between the mathematical view of the assertion, and its
28315run-time behavior.
28316
28317Note that in this mode, the behavior is unaffected by whether or
28318not overflow checks are suppressed, since overflow does not occur.
28319It is possible for gigantic intermediate expressions to raise
28320@cite{Storage_Error} as a result of attempting to compute the
28321results of such expressions (e.g. @cite{Integer'Last ** Integer'Last})
28322but overflow is impossible.
28323@end itemize
28324
28325Note that these modes apply only to the evaluation of predefined
28326arithmetic, membership, and comparison operators for signed integer
28327aritmetic.
28328
28329For fixed-point arithmetic, checks can be suppressed. But if checks
28330are enabled
28331then fixed-point values are always checked for overflow against the
28332base type for intermediate expressions (that is such checks always
28333operate in the equivalent of @cite{STRICT} mode).
28334
28335For floating-point, on nearly all architectures, @cite{Machine_Overflows}
28336is False, and IEEE infinities are generated, so overflow exceptions
28337are never raised. If you want to avoid infinities, and check that
28338final results of expressions are in range, then you can declare a
28339constrained floating-point type, and range checks will be carried
28340out in the normal manner (with infinite values always failing all
28341range checks).
28342
28343@node Specifying the Desired Mode,Default Settings,Overflow Checking Modes in GNAT,Overflow Check Handling in GNAT
28344@anchor{gnat_ugn/gnat_and_program_execution specifying-the-desired-mode}@anchor{fd}@anchor{gnat_ugn/gnat_and_program_execution id57}@anchor{24c}
28345@subsection Specifying the Desired Mode
28346
28347
28348@geindex pragma Overflow_Mode
28349
28350The desired mode of for handling intermediate overflow can be specified using
28351either the @cite{Overflow_Mode} pragma or an equivalent compiler switch.
28352The pragma has the form
28353
28354@quotation
28355
28356@example
28357pragma Overflow_Mode ([General =>] MODE [, [Assertions =>] MODE]);
28358@end example
28359@end quotation
28360
28361where @cite{MODE} is one of
28362
28363
28364@itemize *
28365
28366@item 
28367@cite{STRICT}:  intermediate overflows checked (using base type)
28368
28369@item 
28370@cite{MINIMIZED}: minimize intermediate overflows
28371
28372@item 
28373@cite{ELIMINATED}: eliminate intermediate overflows
28374@end itemize
28375
28376The case is ignored, so @cite{MINIMIZED}, @cite{Minimized} and
28377@cite{minimized} all have the same effect.
28378
28379If only the @cite{General} parameter is present, then the given @cite{MODE}
28380applies
28381to expressions both within and outside assertions. If both arguments
28382are present, then @cite{General} applies to expressions outside assertions,
28383and @cite{Assertions} applies to expressions within assertions. For example:
28384
28385@quotation
28386
28387@example
28388pragma Overflow_Mode
28389  (General => Minimized, Assertions => Eliminated);
28390@end example
28391@end quotation
28392
28393specifies that general expressions outside assertions be evaluated
28394in 'minimize intermediate overflows' mode, and expressions within
28395assertions be evaluated in 'eliminate intermediate overflows' mode.
28396This is often a reasonable choice, avoiding excessive overhead
28397outside assertions, but assuring a high degree of portability
28398when importing code from another compiler, while incurring
28399the extra overhead for assertion expressions to ensure that
28400the behavior at run time matches the expected mathematical
28401behavior.
28402
28403The @cite{Overflow_Mode} pragma has the same scoping and placement
28404rules as pragma @cite{Suppress}, so it can occur either as a
28405configuration pragma, specifying a default for the whole
28406program, or in a declarative scope, where it applies to the
28407remaining declarations and statements in that scope.
28408
28409Note that pragma @cite{Overflow_Mode} does not affect whether
28410overflow checks are enabled or suppressed. It only controls the
28411method used to compute intermediate values. To control whether
28412overflow checking is enabled or suppressed, use pragma @cite{Suppress}
28413or @cite{Unsuppress} in the usual manner
28414
28415@geindex -gnato? (gcc)
28416
28417@geindex -gnato?? (gcc)
28418
28419Additionally, a compiler switch @emph{-gnato?} or @emph{-gnato??}
28420can be used to control the checking mode default (which can be subsequently
28421overridden using pragmas).
28422
28423Here @code{?} is one of the digits @code{1} through @code{3}:
28424
28425@quotation
28426
28427
28428@multitable {xxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
28429@item
28430
28431@code{1}
28432
28433@tab
28434
28435use base type for intermediate operations (@cite{STRICT})
28436
28437@item
28438
28439@code{2}
28440
28441@tab
28442
28443minimize intermediate overflows (@cite{MINIMIZED})
28444
28445@item
28446
28447@code{3}
28448
28449@tab
28450
28451eliminate intermediate overflows (@cite{ELIMINATED})
28452
28453@end multitable
28454
28455@end quotation
28456
28457As with the pragma, if only one digit appears then it applies to all
28458cases; if two digits are given, then the first applies outside
28459assertions, and the second within assertions. Thus the equivalent
28460of the example pragma above would be
28461@emph{-gnato23}.
28462
28463If no digits follow the @emph{-gnato}, then it is equivalent to
28464@emph{-gnato11},
28465causing all intermediate operations to be computed using the base
28466type (@cite{STRICT} mode).
28467
28468In addition to setting the mode used for computation of intermediate
28469results, the @cite{-gnato} switch also enables overflow checking (which
28470is suppressed by default). It thus combines the effect of using
28471a pragma @cite{Overflow_Mode} and pragma @cite{Unsuppress}.
28472
28473@node Default Settings,Implementation Notes,Specifying the Desired Mode,Overflow Check Handling in GNAT
28474@anchor{gnat_ugn/gnat_and_program_execution id58}@anchor{24d}@anchor{gnat_ugn/gnat_and_program_execution default-settings}@anchor{24e}
28475@subsection Default Settings
28476
28477
28478The default mode for overflow checks is
28479
28480@quotation
28481
28482@example
28483General => Strict
28484@end example
28485@end quotation
28486
28487which causes all computations both inside and outside assertions to use
28488the base type. In addition overflow checks are suppressed.
28489
28490This retains compatibility with previous versions of
28491GNAT which suppressed overflow checks by default and always
28492used the base type for computation of intermediate results.
28493
28494The switch @emph{-gnato} (with no digits following) is equivalent to
28495.. index:: -gnato (gcc)
28496
28497@quotation
28498
28499@example
28500General => Strict
28501@end example
28502@end quotation
28503
28504which causes overflow checking of all intermediate overflows
28505both inside and outside assertions against the base type.
28506This provides compatibility
28507with this switch as implemented in previous versions of GNAT.
28508
28509The pragma @cite{Suppress (Overflow_Check)} disables overflow
28510checking, but it has no effect on the method used for computing
28511intermediate results.
28512
28513The pragma @cite{Unsuppress (Overflow_Check)} enables overflow
28514checking, but it has no effect on the method used for computing
28515intermediate results.
28516
28517@node Implementation Notes,,Default Settings,Overflow Check Handling in GNAT
28518@anchor{gnat_ugn/gnat_and_program_execution implementation-notes}@anchor{24f}@anchor{gnat_ugn/gnat_and_program_execution id59}@anchor{250}
28519@subsection Implementation Notes
28520
28521
28522In practice on typical 64-bit machines, the @cite{MINIMIZED} mode is
28523reasonably efficient, and can be generally used. It also helps
28524to ensure compatibility with code imported from some other
28525compiler to GNAT.
28526
28527Setting all intermediate overflows checking (@cite{CHECKED} mode)
28528makes sense if you want to
28529make sure that your code is compatible with any other possible
28530Ada implementation. This may be useful in ensuring portability
28531for code that is to be exported to some other compiler than GNAT.
28532
28533The Ada standard allows the reassociation of expressions at
28534the same precedence level if no parentheses are present. For
28535example, @cite{A+B+C} parses as though it were @cite{(A+B)+C}, but
28536the compiler can reintepret this as @cite{A+(B+C)}, possibly
28537introducing or eliminating an overflow exception. The GNAT
28538compiler never takes advantage of this freedom, and the
28539expression @cite{A+B+C} will be evaluated as @cite{(A+B)+C}.
28540If you need the other order, you can write the parentheses
28541explicitly @cite{A+(B+C)} and GNAT will respect this order.
28542
28543The use of @cite{ELIMINATED} mode will cause the compiler to
28544automatically include an appropriate arbitrary precision
28545integer arithmetic package. The compiler will make calls
28546to this package, though only in cases where it cannot be
28547sure that @cite{Long_Long_Integer} is sufficient to guard against
28548intermediate overflows. This package does not use dynamic
28549alllocation, but it does use the secondary stack, so an
28550appropriate secondary stack package must be present (this
28551is always true for standard full Ada, but may require
28552specific steps for restricted run times such as ZFP).
28553
28554Although @cite{ELIMINATED} mode causes expressions to use arbitrary
28555precision arithmetic, avoiding overflow, the final result
28556must be in an appropriate range. This is true even if the
28557final result is of type @cite{[Long_[Long_]]Integer'Base}, which
28558still has the same bounds as its associated constrained
28559type at run-time.
28560
28561Currently, the @cite{ELIMINATED} mode is only available on target
28562platforms for which @cite{Long_Long_Integer} is 64-bits (nearly all GNAT
28563platforms).
28564
28565@node Performing Dimensionality Analysis in GNAT,Stack Related Facilities,Overflow Check Handling in GNAT,GNAT and Program Execution
28566@anchor{gnat_ugn/gnat_and_program_execution performing-dimensionality-analysis-in-gnat}@anchor{2a}@anchor{gnat_ugn/gnat_and_program_execution id60}@anchor{1f4}
28567@section Performing Dimensionality Analysis in GNAT
28568
28569
28570@geindex Dimensionality analysis
28571
28572The GNAT compiler supports dimensionality checking. The user can
28573specify physical units for objects, and the compiler will verify that uses
28574of these objects are compatible with their dimensions, in a fashion that is
28575familiar to engineering practice. The dimensions of algebraic expressions
28576(including powers with static exponents) are computed from their constituents.
28577
28578@geindex Dimension_System aspect
28579
28580@geindex Dimension aspect
28581
28582This feature depends on Ada 2012 aspect specifications, and is available from
28583version 7.0.1 of GNAT onwards.
28584The GNAT-specific aspect @cite{Dimension_System}
28585allows you to define a system of units; the aspect @cite{Dimension}
28586then allows the user to declare dimensioned quantities within a given system.
28587(These aspects are described in the @emph{Implementation Defined Aspects}
28588chapter of the @emph{GNAT Reference Manual}).
28589
28590The major advantage of this model is that it does not require the declaration of
28591multiple operators for all possible combinations of types: it is only necessary
28592to use the proper subtypes in object declarations.
28593
28594@geindex System.Dim.Mks package (GNAT library)
28595
28596@geindex MKS_Type type
28597
28598The simplest way to impose dimensionality checking on a computation is to make
28599use of the package @cite{System.Dim.Mks},
28600which is part of the GNAT library. This
28601package defines a floating-point type @cite{MKS_Type},
28602for which a sequence of
28603dimension names are specified, together with their conventional abbreviations.
28604The following should be read together with the full specification of the
28605package, in file @code{s-dimmks.ads}.
28606
28607@quotation
28608
28609@geindex s-dimmks.ads file
28610
28611@example
28612type Mks_Type is new Long_Long_Float
28613  with
28614   Dimension_System => (
28615     (Unit_Name => Meter,    Unit_Symbol => 'm',   Dim_Symbol => 'L'),
28616     (Unit_Name => Kilogram, Unit_Symbol => "kg",  Dim_Symbol => 'M'),
28617     (Unit_Name => Second,   Unit_Symbol => 's',   Dim_Symbol => 'T'),
28618     (Unit_Name => Ampere,   Unit_Symbol => 'A',   Dim_Symbol => 'I'),
28619     (Unit_Name => Kelvin,   Unit_Symbol => 'K',   Dim_Symbol => "Theta"),
28620     (Unit_Name => Mole,     Unit_Symbol => "mol", Dim_Symbol => 'N'),
28621     (Unit_Name => Candela,  Unit_Symbol => "cd",  Dim_Symbol => 'J'));
28622@end example
28623@end quotation
28624
28625The package then defines a series of subtypes that correspond to these
28626conventional units. For example:
28627
28628@quotation
28629
28630@example
28631subtype Length is Mks_Type
28632  with
28633   Dimension => (Symbol => 'm', Meter  => 1, others => 0);
28634@end example
28635@end quotation
28636
28637and similarly for @cite{Mass}, @cite{Time}, @cite{Electric_Current},
28638@cite{Thermodynamic_Temperature}, @cite{Amount_Of_Substance}, and
28639@cite{Luminous_Intensity} (the standard set of units of the SI system).
28640
28641The package also defines conventional names for values of each unit, for
28642example:
28643
28644@quotation
28645
28646@c code-block":: ada
28647@c 
28648@c m   : constant Length           := 1.0;
28649@c kg  : constant Mass             := 1.0;
28650@c s   : constant Time             := 1.0;
28651@c A   : constant Electric_Current := 1.0;
28652@end quotation
28653
28654as well as useful multiples of these units:
28655
28656@quotation
28657
28658@example
28659 cm  : constant Length := 1.0E-02;
28660 g   : constant Mass   := 1.0E-03;
28661 min : constant Time   := 60.0;
28662 day : constant Time   := 60.0 * 24.0 * min;
28663...
28664@end example
28665@end quotation
28666
28667Using this package, you can then define a derived unit by
28668providing the aspect that
28669specifies its dimensions within the MKS system, as well as the string to
28670be used for output of a value of that unit:
28671
28672@quotation
28673
28674@example
28675subtype Acceleration is Mks_Type
28676  with Dimension => ("m/sec^2",
28677                     Meter => 1,
28678                     Second => -2,
28679                     others => 0);
28680@end example
28681@end quotation
28682
28683Here is a complete example of use:
28684
28685@quotation
28686
28687@example
28688with System.Dim.MKS; use System.Dim.Mks;
28689with System.Dim.Mks_IO; use System.Dim.Mks_IO;
28690with Text_IO; use Text_IO;
28691procedure Free_Fall is
28692  subtype Acceleration is Mks_Type
28693    with Dimension => ("m/sec^2", 1, 0, -2, others => 0);
28694  G : constant acceleration := 9.81 * m / (s ** 2);
28695  T : Time := 10.0*s;
28696  Distance : Length;
28697
28698begin
28699  Put ("Gravitational constant: ");
28700  Put (G, Aft => 2, Exp => 0); Put_Line ("");
28701  Distance := 0.5 * G * T ** 2;
28702  Put ("distance travelled in 10 seconds of free fall ");
28703  Put (Distance, Aft => 2, Exp => 0);
28704  Put_Line ("");
28705end Free_Fall;
28706@end example
28707@end quotation
28708
28709Execution of this program yields:
28710
28711@quotation
28712
28713@example
28714Gravitational constant:  9.81 m/sec^2
28715distance travelled in 10 seconds of free fall 490.50 m
28716@end example
28717@end quotation
28718
28719However, incorrect assignments such as:
28720
28721@quotation
28722
28723@example
28724Distance := 5.0;
28725Distance := 5.0 * kg:
28726@end example
28727@end quotation
28728
28729are rejected with the following diagnoses:
28730
28731@quotation
28732
28733@example
28734Distance := 5.0;
28735   >>> dimensions mismatch in assignment
28736   >>> left-hand side has dimension [L]
28737   >>> right-hand side is dimensionless
28738
28739Distance := 5.0 * kg:
28740   >>> dimensions mismatch in assignment
28741   >>> left-hand side has dimension [L]
28742   >>> right-hand side has dimension [M]
28743@end example
28744@end quotation
28745
28746The dimensions of an expression are properly displayed, even if there is
28747no explicit subtype for it. If we add to the program:
28748
28749@quotation
28750
28751@example
28752Put ("Final velocity: ");
28753Put (G * T, Aft =>2, Exp =>0);
28754Put_Line ("");
28755@end example
28756@end quotation
28757
28758then the output includes:
28759
28760@quotation
28761
28762@example
28763Final velocity: 98.10 m.s**(-1)
28764@end example
28765@end quotation
28766
28767@node Stack Related Facilities,Memory Management Issues,Performing Dimensionality Analysis in GNAT,GNAT and Program Execution
28768@anchor{gnat_ugn/gnat_and_program_execution id61}@anchor{1f5}@anchor{gnat_ugn/gnat_and_program_execution stack-related-facilities}@anchor{2b}
28769@section Stack Related Facilities
28770
28771
28772This section describes some useful tools associated with stack
28773checking and analysis. In
28774particular, it deals with dynamic and static stack usage measurements.
28775
28776@menu
28777* Stack Overflow Checking:: 
28778* Static Stack Usage Analysis:: 
28779* Dynamic Stack Usage Analysis:: 
28780
28781@end menu
28782
28783@node Stack Overflow Checking,Static Stack Usage Analysis,,Stack Related Facilities
28784@anchor{gnat_ugn/gnat_and_program_execution id62}@anchor{251}@anchor{gnat_ugn/gnat_and_program_execution stack-overflow-checking}@anchor{f9}
28785@subsection Stack Overflow Checking
28786
28787
28788@geindex Stack Overflow Checking
28789
28790@geindex -fstack-check (gcc)
28791
28792For most operating systems, @emph{gcc} does not perform stack overflow
28793checking by default. This means that if the main environment task or
28794some other task exceeds the available stack space, then unpredictable
28795behavior will occur. Most native systems offer some level of protection by
28796adding a guard page at the end of each task stack. This mechanism is usually
28797not enough for dealing properly with stack overflow situations because
28798a large local variable could "jump" above the guard page.
28799Furthermore, when the
28800guard page is hit, there may not be any space left on the stack for executing
28801the exception propagation code. Enabling stack checking avoids
28802such situations.
28803
28804To activate stack checking, compile all units with the gcc option
28805@cite{-fstack-check}. For example:
28806
28807@quotation
28808
28809@example
28810$ gcc -c -fstack-check package1.adb
28811@end example
28812@end quotation
28813
28814Units compiled with this option will generate extra instructions to check
28815that any use of the stack (for procedure calls or for declaring local
28816variables in declare blocks) does not exceed the available stack space.
28817If the space is exceeded, then a @cite{Storage_Error} exception is raised.
28818
28819For declared tasks, the stack size is controlled by the size
28820given in an applicable @cite{Storage_Size} pragma or by the value specified
28821at bind time with @code{-d} (@ref{123,,Switches for gnatbind}) or is set to
28822the default size as defined in the GNAT runtime otherwise.
28823
28824@geindex GNAT_STACK_LIMIT
28825
28826For the environment task, the stack size depends on
28827system defaults and is unknown to the compiler. Stack checking
28828may still work correctly if a fixed
28829size stack is allocated, but this cannot be guaranteed.
28830To ensure that a clean exception is signalled for stack
28831overflow, set the environment variable
28832@geindex GNAT_STACK_LIMIT
28833@geindex environment variable; GNAT_STACK_LIMIT
28834@code{GNAT_STACK_LIMIT} to indicate the maximum
28835stack area that can be used, as in:
28836
28837@quotation
28838
28839@example
28840$ SET GNAT_STACK_LIMIT 1600
28841@end example
28842@end quotation
28843
28844The limit is given in kilobytes, so the above declaration would
28845set the stack limit of the environment task to 1.6 megabytes.
28846Note that the only purpose of this usage is to limit the amount
28847of stack used by the environment task. If it is necessary to
28848increase the amount of stack for the environment task, then this
28849is an operating systems issue, and must be addressed with the
28850appropriate operating systems commands.
28851
28852@node Static Stack Usage Analysis,Dynamic Stack Usage Analysis,Stack Overflow Checking,Stack Related Facilities
28853@anchor{gnat_ugn/gnat_and_program_execution static-stack-usage-analysis}@anchor{fa}@anchor{gnat_ugn/gnat_and_program_execution id63}@anchor{252}
28854@subsection Static Stack Usage Analysis
28855
28856
28857@geindex Static Stack Usage Analysis
28858
28859@geindex -fstack-usage
28860
28861A unit compiled with @code{-fstack-usage} will generate an extra file
28862that specifies
28863the maximum amount of stack used, on a per-function basis.
28864The file has the same
28865basename as the target object file with a @code{.su} extension.
28866Each line of this file is made up of three fields:
28867
28868
28869@itemize *
28870
28871@item 
28872The name of the function.
28873
28874@item 
28875A number of bytes.
28876
28877@item 
28878One or more qualifiers: @cite{static}, @cite{dynamic}, @cite{bounded}.
28879@end itemize
28880
28881The second field corresponds to the size of the known part of the function
28882frame.
28883
28884The qualifier @cite{static} means that the function frame size
28885is purely static.
28886It usually means that all local variables have a static size.
28887In this case, the second field is a reliable measure of the function stack
28888utilization.
28889
28890The qualifier @cite{dynamic} means that the function frame size is not static.
28891It happens mainly when some local variables have a dynamic size. When this
28892qualifier appears alone, the second field is not a reliable measure
28893of the function stack analysis. When it is qualified with  @cite{bounded}, it
28894means that the second field is a reliable maximum of the function stack
28895utilization.
28896
28897A unit compiled with @code{-Wstack-usage} will issue a warning for each
28898subprogram whose stack usage might be larger than the specified amount of
28899bytes.  The wording is in keeping with the qualifier documented above.
28900
28901@node Dynamic Stack Usage Analysis,,Static Stack Usage Analysis,Stack Related Facilities
28902@anchor{gnat_ugn/gnat_and_program_execution id64}@anchor{253}@anchor{gnat_ugn/gnat_and_program_execution dynamic-stack-usage-analysis}@anchor{125}
28903@subsection Dynamic Stack Usage Analysis
28904
28905
28906It is possible to measure the maximum amount of stack used by a task, by
28907adding a switch to @emph{gnatbind}, as:
28908
28909@quotation
28910
28911@example
28912$ gnatbind -u0 file
28913@end example
28914@end quotation
28915
28916With this option, at each task termination, its stack usage is  output on
28917@code{stderr}.
28918It is not always convenient to output the stack usage when the program
28919is still running. Hence, it is possible to delay this output until program
28920termination. for a given number of tasks specified as the argument of the
28921@code{-u} option. For instance:
28922
28923@quotation
28924
28925@example
28926$ gnatbind -u100 file
28927@end example
28928@end quotation
28929
28930will buffer the stack usage information of the first 100 tasks to terminate and
28931output this info at program termination. Results are displayed in four
28932columns:
28933
28934@quotation
28935
28936@example
28937Index | Task Name | Stack Size | Stack Usage
28938@end example
28939@end quotation
28940
28941where:
28942
28943
28944@itemize *
28945
28946@item 
28947@emph{Index} is a number associated with each task.
28948
28949@item 
28950@emph{Task Name} is the name of the task analyzed.
28951
28952@item 
28953@emph{Stack Size} is the maximum size for the stack.
28954
28955@item 
28956@emph{Stack Usage} is the measure done by the stack analyzer.
28957In order to prevent overflow, the stack
28958is not entirely analyzed, and it's not possible to know exactly how
28959much has actually been used.
28960@end itemize
28961
28962The environment task stack, e.g., the stack that contains the main unit, is
28963only processed when the environment variable GNAT_STACK_LIMIT is set.
28964
28965The package @cite{GNAT.Task_Stack_Usage} provides facilities to get
28966stack usage reports at run-time. See its body for the details.
28967
28968@node Memory Management Issues,,Stack Related Facilities,GNAT and Program Execution
28969@anchor{gnat_ugn/gnat_and_program_execution id65}@anchor{1f6}@anchor{gnat_ugn/gnat_and_program_execution memory-management-issues}@anchor{2c}
28970@section Memory Management Issues
28971
28972
28973This section describes some useful memory pools provided in the GNAT library
28974and in particular the GNAT Debug Pool facility, which can be used to detect
28975incorrect uses of access values (including 'dangling references').
28976
28977
28978@menu
28979* Some Useful Memory Pools:: 
28980* The GNAT Debug Pool Facility:: 
28981
28982@end menu
28983
28984@node Some Useful Memory Pools,The GNAT Debug Pool Facility,,Memory Management Issues
28985@anchor{gnat_ugn/gnat_and_program_execution id66}@anchor{254}@anchor{gnat_ugn/gnat_and_program_execution some-useful-memory-pools}@anchor{255}
28986@subsection Some Useful Memory Pools
28987
28988
28989@geindex Memory Pool
28990
28991@geindex storage
28992@geindex pool
28993
28994The @cite{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
28995storage pool. Allocations use the standard system call @cite{malloc} while
28996deallocations use the standard system call @cite{free}. No reclamation is
28997performed when the pool goes out of scope. For performance reasons, the
28998standard default Ada allocators/deallocators do not use any explicit storage
28999pools but if they did, they could use this storage pool without any change in
29000behavior. That is why this storage pool is used  when the user
29001manages to make the default implicit allocator explicit as in this example:
29002
29003@quotation
29004
29005@example
29006type T1 is access Something;
29007 -- no Storage pool is defined for T2
29008
29009type T2 is access Something_Else;
29010for T2'Storage_Pool use T1'Storage_Pool;
29011-- the above is equivalent to
29012for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
29013@end example
29014@end quotation
29015
29016The @cite{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
29017pool. The allocation strategy is similar to @cite{Pool_Local}'s
29018except that the all
29019storage allocated with this pool is reclaimed when the pool object goes out of
29020scope. This pool provides a explicit mechanism similar to the implicit one
29021provided by several Ada 83 compilers for allocations performed through a local
29022access type and whose purpose was to reclaim memory when exiting the
29023scope of a given local access. As an example, the following program does not
29024leak memory even though it does not perform explicit deallocation:
29025
29026@quotation
29027
29028@example
29029with System.Pool_Local;
29030procedure Pooloc1 is
29031   procedure Internal is
29032      type A is access Integer;
29033      X : System.Pool_Local.Unbounded_Reclaim_Pool;
29034      for A'Storage_Pool use X;
29035      v : A;
29036   begin
29037      for I in  1 .. 50 loop
29038         v := new Integer;
29039      end loop;
29040   end Internal;
29041begin
29042   for I in  1 .. 100 loop
29043      Internal;
29044   end loop;
29045end Pooloc1;
29046@end example
29047@end quotation
29048
29049The @cite{System.Pool_Size} package implements the Stack_Bounded_Pool used when
29050@cite{Storage_Size} is specified for an access type.
29051The whole storage for the pool is
29052allocated at once, usually on the stack at the point where the access type is
29053elaborated. It is automatically reclaimed when exiting the scope where the
29054access type is defined. This package is not intended to be used directly by the
29055user and it is implicitly used for each such declaration:
29056
29057@quotation
29058
29059@example
29060type T1 is access Something;
29061for T1'Storage_Size use 10_000;
29062@end example
29063@end quotation
29064
29065@node The GNAT Debug Pool Facility,,Some Useful Memory Pools,Memory Management Issues
29066@anchor{gnat_ugn/gnat_and_program_execution id67}@anchor{256}@anchor{gnat_ugn/gnat_and_program_execution the-gnat-debug-pool-facility}@anchor{257}
29067@subsection The GNAT Debug Pool Facility
29068
29069
29070@geindex Debug Pool
29071
29072@geindex storage
29073@geindex pool
29074@geindex memory corruption
29075
29076The use of unchecked deallocation and unchecked conversion can easily
29077lead to incorrect memory references. The problems generated by such
29078references are usually difficult to tackle because the symptoms can be
29079very remote from the origin of the problem. In such cases, it is
29080very helpful to detect the problem as early as possible. This is the
29081purpose of the Storage Pool provided by @cite{GNAT.Debug_Pools}.
29082
29083In order to use the GNAT specific debugging pool, the user must
29084associate a debug pool object with each of the access types that may be
29085related to suspected memory problems. See Ada Reference Manual 13.11.
29086
29087@quotation
29088
29089@example
29090type Ptr is access Some_Type;
29091Pool : GNAT.Debug_Pools.Debug_Pool;
29092for Ptr'Storage_Pool use Pool;
29093@end example
29094@end quotation
29095
29096@cite{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
29097pool: the @cite{Checked_Pool}. Such pools, like standard Ada storage pools,
29098allow the user to redefine allocation and deallocation strategies. They
29099also provide a checkpoint for each dereference, through the use of
29100the primitive operation @cite{Dereference} which is implicitly called at
29101each dereference of an access value.
29102
29103Once an access type has been associated with a debug pool, operations on
29104values of the type may raise four distinct exceptions,
29105which correspond to four potential kinds of memory corruption:
29106
29107
29108@itemize *
29109
29110@item 
29111@cite{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
29112
29113@item 
29114@cite{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
29115
29116@item 
29117@cite{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
29118
29119@item 
29120@cite{GNAT.Debug_Pools.Freeing_Deallocated_Storage}
29121@end itemize
29122
29123For types associated with a Debug_Pool, dynamic allocation is performed using
29124the standard GNAT allocation routine. References to all allocated chunks of
29125memory are kept in an internal dictionary. Several deallocation strategies are
29126provided, whereupon the user can choose to release the memory to the system,
29127keep it allocated for further invalid access checks, or fill it with an easily
29128recognizable pattern for debug sessions. The memory pattern is the old IBM
29129hexadecimal convention: @cite{16#DEADBEEF#}.
29130
29131See the documentation in the file g-debpoo.ads for more information on the
29132various strategies.
29133
29134Upon each dereference, a check is made that the access value denotes a
29135properly allocated memory location. Here is a complete example of use of
29136@cite{Debug_Pools}, that includes typical instances of  memory corruption:
29137
29138@quotation
29139
29140@example
29141with Gnat.Io; use Gnat.Io;
29142with Unchecked_Deallocation;
29143with Unchecked_Conversion;
29144with GNAT.Debug_Pools;
29145with System.Storage_Elements;
29146with Ada.Exceptions; use Ada.Exceptions;
29147procedure Debug_Pool_Test is
29148
29149   type T is access Integer;
29150   type U is access all T;
29151
29152   P : GNAT.Debug_Pools.Debug_Pool;
29153   for T'Storage_Pool use P;
29154
29155   procedure Free is new Unchecked_Deallocation (Integer, T);
29156   function UC is new Unchecked_Conversion (U, T);
29157   A, B : aliased T;
29158
29159   procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
29160
29161begin
29162   Info (P);
29163   A := new Integer;
29164   B := new Integer;
29165   B := A;
29166   Info (P);
29167   Free (A);
29168   begin
29169      Put_Line (Integer'Image(B.all));
29170   exception
29171      when E : others => Put_Line ("raised: " & Exception_Name (E));
29172   end;
29173   begin
29174      Free (B);
29175   exception
29176      when E : others => Put_Line ("raised: " & Exception_Name (E));
29177   end;
29178   B := UC(A'Access);
29179   begin
29180      Put_Line (Integer'Image(B.all));
29181   exception
29182      when E : others => Put_Line ("raised: " & Exception_Name (E));
29183   end;
29184   begin
29185      Free (B);
29186   exception
29187      when E : others => Put_Line ("raised: " & Exception_Name (E));
29188   end;
29189   Info (P);
29190end Debug_Pool_Test;
29191@end example
29192@end quotation
29193
29194The debug pool mechanism provides the following precise diagnostics on the
29195execution of this erroneous program:
29196
29197@quotation
29198
29199@example
29200Debug Pool info:
29201  Total allocated bytes :  0
29202  Total deallocated bytes :  0
29203  Current Water Mark:  0
29204  High Water Mark:  0
29205
29206Debug Pool info:
29207  Total allocated bytes :  8
29208  Total deallocated bytes :  0
29209  Current Water Mark:  8
29210  High Water Mark:  8
29211
29212raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
29213raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
29214raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
29215raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
29216Debug Pool info:
29217  Total allocated bytes :  8
29218  Total deallocated bytes :  4
29219  Current Water Mark:  4
29220  High Water Mark:  8
29221@end example
29222@end quotation
29223
29224
29225@c -- Non-breaking space in running text
29226@c -- E.g. Ada |nbsp| 95
29227
29228@node Platform-Specific Information,Example of Binder Output File,GNAT and Program Execution,Top
29229@anchor{gnat_ugn/platform_specific_information platform-specific-information}@anchor{f}@anchor{gnat_ugn/platform_specific_information doc}@anchor{258}@anchor{gnat_ugn/platform_specific_information id1}@anchor{259}
29230@chapter Platform-Specific Information
29231
29232
29233This appendix contains information relating to the implementation
29234of run-time libraries on various platforms and also covers
29235topics related to the GNAT implementation on Windows and Mac OS.
29236
29237@menu
29238* Run-Time Libraries:: 
29239* Specifying a Run-Time Library:: 
29240* Microsoft Windows Topics:: 
29241* Mac OS Topics:: 
29242
29243@end menu
29244
29245@node Run-Time Libraries,Specifying a Run-Time Library,,Platform-Specific Information
29246@anchor{gnat_ugn/platform_specific_information id2}@anchor{25a}@anchor{gnat_ugn/platform_specific_information run-time-libraries}@anchor{2d}
29247@section Run-Time Libraries
29248
29249
29250@geindex Tasking and threads libraries
29251
29252@geindex Threads libraries and tasking
29253
29254@geindex Run-time libraries (platform-specific information)
29255
29256The GNAT run-time implementation may vary with respect to both the
29257underlying threads library and the exception handling scheme.
29258For threads support, one or more of the following are supplied:
29259
29260
29261@itemize *
29262
29263@item 
29264@strong{native threads library}, a binding to the thread package from
29265the underlying operating system
29266
29267@item 
29268@strong{pthreads library} (Sparc Solaris only), a binding to the Solaris
29269POSIX thread package
29270@end itemize
29271
29272For exception handling, either or both of two models are supplied:
29273
29274@quotation
29275
29276@geindex Zero-Cost Exceptions
29277
29278@geindex ZCX (Zero-Cost Exceptions)
29279@end quotation
29280
29281
29282@itemize *
29283
29284@item 
29285@strong{Zero-Cost Exceptions} ("ZCX"),
29286which uses binder-generated tables that
29287are interrogated at run time to locate a handler.
29288
29289@geindex setjmp/longjmp Exception Model
29290
29291@geindex SJLJ (setjmp/longjmp Exception Model)
29292
29293@item 
29294@strong{setjmp / longjmp} ('SJLJ'),
29295which uses dynamically-set data to establish
29296the set of handlers
29297@end itemize
29298
29299Most programs should experience a substantial speed improvement by
29300being compiled with a ZCX run-time.
29301This is especially true for
29302tasking applications or applications with many exception handlers.@}
29303
29304This section summarizes which combinations of threads and exception support
29305are supplied on various GNAT platforms.
29306It then shows how to select a particular library either
29307permanently or temporarily,
29308explains the properties of (and tradeoffs among) the various threads
29309libraries, and provides some additional
29310information about several specific platforms.
29311
29312@menu
29313* Summary of Run-Time Configurations:: 
29314
29315@end menu
29316
29317@node Summary of Run-Time Configurations,,,Run-Time Libraries
29318@anchor{gnat_ugn/platform_specific_information summary-of-run-time-configurations}@anchor{25b}@anchor{gnat_ugn/platform_specific_information id3}@anchor{25c}
29319@subsection Summary of Run-Time Configurations
29320
29321
29322
29323@multitable {xxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxx} 
29324@headitem
29325
29326Platform
29327
29328@tab
29329
29330Run-Time
29331
29332@tab
29333
29334Tasking
29335
29336@tab
29337
29338Exceptions
29339
29340@item
29341
29342ppc-aix
29343
29344@tab
29345
29346rts-native
29347(default)
29348
29349@tab
29350
29351native AIX threads
29352
29353@tab
29354
29355ZCX
29356
29357@item
29358
29359rts-sjlj
29360
29361@tab
29362
29363native AIX threads
29364
29365@tab
29366
29367SJLJ
29368
29369@item
29370
29371sparc-solaris
29372
29373@tab
29374
29375rts-native
29376(default)
29377
29378@tab
29379
29380native Solaris
29381threads library
29382
29383@tab
29384
29385ZCX
29386
29387@item
29388
29389rts-pthread
29390
29391@tab
29392
29393pthread library
29394
29395@tab
29396
29397ZCX
29398
29399@item
29400
29401rts-sjlj
29402
29403@tab
29404
29405native Solaris
29406threads library
29407
29408@tab
29409
29410SJLJ
29411
29412@item
29413
29414sparc64-solaris
29415
29416@tab
29417
29418rts-native
29419(default)
29420
29421@tab
29422
29423native Solaris
29424threads library
29425
29426@tab
29427
29428ZCX
29429
29430@item
29431
29432x86-linux
29433
29434@tab
29435
29436rts-native
29437(default)
29438
29439@tab
29440
29441pthread library
29442
29443@tab
29444
29445ZCX
29446
29447@item
29448
29449rts-sjlj
29450
29451@tab
29452
29453pthread library
29454
29455@tab
29456
29457SJLJ
29458
29459@item
29460
29461x86-lynx
29462
29463@tab
29464
29465rts-native
29466(default)
29467
29468@tab
29469
29470native LynxOS threads
29471
29472@tab
29473
29474SJLJ
29475
29476@item
29477
29478x86-solaris
29479
29480@tab
29481
29482rts-native
29483(default)
29484
29485@tab
29486
29487native Solaris
29488threads library
29489
29490@tab
29491
29492ZCX
29493
29494@item
29495
29496rts-sjlj
29497
29498@tab
29499
29500native Solaris
29501threads library
29502
29503@tab
29504
29505SJLJ
29506
29507@item
29508
29509x86-windows
29510
29511@tab
29512
29513rts-native
29514(default)
29515
29516@tab
29517
29518native Win32 threads
29519
29520@tab
29521
29522ZCX
29523
29524@item
29525
29526rts-sjlj
29527
29528@tab
29529
29530native Win32 threads
29531
29532@tab
29533
29534SJLJ
29535
29536@item
29537
29538x86_64-linux
29539
29540@tab
29541
29542rts-native
29543(default)
29544
29545@tab
29546
29547pthread library
29548
29549@tab
29550
29551ZCX
29552
29553@item
29554
29555rts-sjlj
29556
29557@tab
29558
29559pthread library
29560
29561@tab
29562
29563SJLJ
29564
29565@end multitable
29566
29567
29568@node Specifying a Run-Time Library,Microsoft Windows Topics,Run-Time Libraries,Platform-Specific Information
29569@anchor{gnat_ugn/platform_specific_information specifying-a-run-time-library}@anchor{25d}@anchor{gnat_ugn/platform_specific_information id4}@anchor{25e}
29570@section Specifying a Run-Time Library
29571
29572
29573The @code{adainclude} subdirectory containing the sources of the GNAT
29574run-time library, and the @code{adalib} subdirectory containing the
29575@code{ALI} files and the static and/or shared GNAT library, are located
29576in the gcc target-dependent area:
29577
29578@quotation
29579
29580@example
29581target=$prefix/lib/gcc/gcc-*dumpmachine*/gcc-*dumpversion*/
29582@end example
29583@end quotation
29584
29585As indicated above, on some platforms several run-time libraries are supplied.
29586These libraries are installed in the target dependent area and
29587contain a complete source and binary subdirectory. The detailed description
29588below explains the differences between the different libraries in terms of
29589their thread support.
29590
29591The default run-time library (when GNAT is installed) is @emph{rts-native}.
29592This default run time is selected by the means of soft links.
29593For example on x86-linux:
29594
29595@example
29596--
29597--  $(target-dir)
29598--      |
29599--      +--- adainclude----------+
29600--      |                        |
29601--      +--- adalib-----------+  |
29602--      |                     |  |
29603--      +--- rts-native       |  |
29604--      |    |                |  |
29605--      |    +--- adainclude <---+
29606--      |    |                |
29607--      |    +--- adalib <----+
29608--      |
29609--      +--- rts-sjlj
29610--           |
29611--           +--- adainclude
29612--           |
29613--           +--- adalib
29614@end example
29615
29616If the @emph{rts-sjlj} library is to be selected on a permanent basis,
29617these soft links can be modified with the following commands:
29618
29619@quotation
29620
29621@example
29622$ cd $target
29623$ rm -f adainclude adalib
29624$ ln -s rts-sjlj/adainclude adainclude
29625$ ln -s rts-sjlj/adalib adalib
29626@end example
29627@end quotation
29628
29629Alternatively, you can specify @code{rts-sjlj/adainclude} in the file
29630@code{$target/ada_source_path} and @code{rts-sjlj/adalib} in
29631@code{$target/ada_object_path}.
29632
29633@geindex --RTS option
29634
29635Selecting another run-time library temporarily can be
29636achieved by using the @emph{--RTS} switch, e.g., @emph{--RTS=sjlj}
29637@anchor{gnat_ugn/platform_specific_information choosing-the-scheduling-policy}@anchor{25f}
29638@geindex SCHED_FIFO scheduling policy
29639
29640@geindex SCHED_RR scheduling policy
29641
29642@geindex SCHED_OTHER scheduling policy
29643
29644@menu
29645* Choosing the Scheduling Policy:: 
29646* Solaris-Specific Considerations:: 
29647* Solaris Threads Issues:: 
29648* AIX-Specific Considerations:: 
29649
29650@end menu
29651
29652@node Choosing the Scheduling Policy,Solaris-Specific Considerations,,Specifying a Run-Time Library
29653@anchor{gnat_ugn/platform_specific_information id5}@anchor{260}
29654@subsection Choosing the Scheduling Policy
29655
29656
29657When using a POSIX threads implementation, you have a choice of several
29658scheduling policies: @cite{SCHED_FIFO}, @cite{SCHED_RR} and @cite{SCHED_OTHER}.
29659
29660Typically, the default is @cite{SCHED_OTHER}, while using @cite{SCHED_FIFO}
29661or @cite{SCHED_RR} requires special (e.g., root) privileges.
29662
29663@geindex pragma Time_Slice
29664
29665@geindex -T0 option
29666
29667@geindex pragma Task_Dispatching_Policy
29668
29669By default, GNAT uses the @cite{SCHED_OTHER} policy. To specify
29670@cite{SCHED_FIFO},
29671you can use one of the following:
29672
29673
29674@itemize *
29675
29676@item 
29677@cite{pragma Time_Slice (0.0)}
29678
29679@item 
29680the corresponding binder option @emph{-T0}
29681
29682@item 
29683@cite{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
29684@end itemize
29685
29686To specify @cite{SCHED_RR},
29687you should use @cite{pragma Time_Slice} with a
29688value greater than 0.0, or else use the corresponding @emph{-T}
29689binder option.
29690
29691@geindex Solaris Sparc threads libraries
29692
29693@node Solaris-Specific Considerations,Solaris Threads Issues,Choosing the Scheduling Policy,Specifying a Run-Time Library
29694@anchor{gnat_ugn/platform_specific_information id6}@anchor{261}@anchor{gnat_ugn/platform_specific_information solaris-specific-considerations}@anchor{262}
29695@subsection Solaris-Specific Considerations
29696
29697
29698This section addresses some topics related to the various threads libraries
29699on Sparc Solaris.
29700
29701@geindex rts-pthread threads library
29702
29703@node Solaris Threads Issues,AIX-Specific Considerations,Solaris-Specific Considerations,Specifying a Run-Time Library
29704@anchor{gnat_ugn/platform_specific_information id7}@anchor{263}@anchor{gnat_ugn/platform_specific_information solaris-threads-issues}@anchor{264}
29705@subsection Solaris Threads Issues
29706
29707
29708GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
29709library based on POSIX threads --- @emph{rts-pthread}.
29710
29711@geindex PTHREAD_PRIO_INHERIT policy (under rts-pthread)
29712
29713@geindex PTHREAD_PRIO_PROTECT policy (under rts-pthread)
29714
29715@geindex pragma Locking_Policy (under rts-pthread)
29716
29717@geindex Inheritance_Locking (under rts-pthread)
29718
29719@geindex Ceiling_Locking (under rts-pthread)
29720
29721This run-time library has the advantage of being mostly shared across all
29722POSIX-compliant thread implementations, and it also provides under
29723Solaris��8 the @cite{PTHREAD_PRIO_INHERIT}
29724and @cite{PTHREAD_PRIO_PROTECT}
29725semantics that can be selected using the predefined pragma
29726@cite{Locking_Policy}
29727with respectively
29728@cite{Inheritance_Locking} and @cite{Ceiling_Locking} as the policy.
29729
29730As explained above, the native run-time library is based on the Solaris thread
29731library (@cite{libthread}) and is the default library.
29732
29733@geindex GNAT_PROCESSOR environment variable (on Sparc Solaris)
29734
29735When the Solaris threads library is used (this is the default), programs
29736compiled with GNAT can automatically take advantage of
29737and can thus execute on multiple processors.
29738The user can alternatively specify a processor on which the program should run
29739to emulate a single-processor system. The multiprocessor / uniprocessor choice
29740is made by
29741setting the environment variable 
29742@geindex GNAT_PROCESSOR
29743@geindex environment variable; GNAT_PROCESSOR
29744@code{GNAT_PROCESSOR}
29745to one of the following:
29746
29747@quotation
29748
29749
29750@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
29751@headitem
29752
29753@code{GNAT_PROCESSOR} Value
29754
29755@tab
29756
29757Effect
29758
29759@item
29760
29761@emph{-2}
29762
29763@tab
29764
29765Use the default configuration (run the program on all
29766available processors) - this is the same as having @cite{GNAT_PROCESSOR}
29767unset
29768
29769@item
29770
29771@emph{-1}
29772
29773@tab
29774
29775Let the run-time implementation choose one processor and run the
29776program on that processor
29777
29778@item
29779
29780@emph{0 .. Last_Proc}
29781
29782@tab
29783
29784Run the program on the specified processor.
29785@cite{Last_Proc} is equal to @cite{_SC_NPROCESSORS_CONF - 1}
29786(where @cite{_SC_NPROCESSORS_CONF} is a system variable).
29787
29788@end multitable
29789
29790@end quotation
29791
29792@node AIX-Specific Considerations,,Solaris Threads Issues,Specifying a Run-Time Library
29793@anchor{gnat_ugn/platform_specific_information aix-specific-considerations}@anchor{265}@anchor{gnat_ugn/platform_specific_information id8}@anchor{266}
29794@subsection AIX-Specific Considerations
29795
29796
29797@geindex AIX resolver library
29798
29799On AIX, the resolver library initializes some internal structure on
29800the first call to @cite{get*by*} functions, which are used to implement
29801@cite{GNAT.Sockets.Get_Host_By_Name} and
29802@cite{GNAT.Sockets.Get_Host_By_Address}.
29803If such initialization occurs within an Ada task, and the stack size for
29804the task is the default size, a stack overflow may occur.
29805
29806To avoid this overflow, the user should either ensure that the first call
29807to @cite{GNAT.Sockets.Get_Host_By_Name} or
29808@cite{GNAT.Sockets.Get_Host_By_Addrss}
29809occurs in the environment task, or use @cite{pragma Storage_Size} to
29810specify a sufficiently large size for the stack of the task that contains
29811this call.
29812
29813@geindex Windows NT
29814
29815@geindex Windows 95
29816
29817@geindex Windows 98
29818
29819@node Microsoft Windows Topics,Mac OS Topics,Specifying a Run-Time Library,Platform-Specific Information
29820@anchor{gnat_ugn/platform_specific_information microsoft-windows-topics}@anchor{2e}@anchor{gnat_ugn/platform_specific_information id9}@anchor{267}
29821@section Microsoft Windows Topics
29822
29823
29824This section describes topics that are specific to the Microsoft Windows
29825platforms.
29826
29827
29828
29829
29830
29831@menu
29832* Using GNAT on Windows:: 
29833* Using a network installation of GNAT:: 
29834* CONSOLE and WINDOWS subsystems:: 
29835* Temporary Files:: 
29836* Mixed-Language Programming on Windows:: 
29837
29838@end menu
29839
29840@node Using GNAT on Windows,Using a network installation of GNAT,,Microsoft Windows Topics
29841@anchor{gnat_ugn/platform_specific_information using-gnat-on-windows}@anchor{268}@anchor{gnat_ugn/platform_specific_information id10}@anchor{269}
29842@subsection Using GNAT on Windows
29843
29844
29845One of the strengths of the GNAT technology is that its tool set
29846(@emph{gcc}, @emph{gnatbind}, @emph{gnatlink}, @emph{gnatmake}, the
29847@cite{gdb} debugger, etc.) is used in the same way regardless of the
29848platform.
29849
29850On Windows this tool set is complemented by a number of Microsoft-specific
29851tools that have been provided to facilitate interoperability with Windows
29852when this is required. With these tools:
29853
29854
29855@itemize *
29856
29857@item 
29858You can build applications using the @cite{CONSOLE} or @cite{WINDOWS}
29859subsystems.
29860
29861@item 
29862You can use any Dynamically Linked Library (DLL) in your Ada code (both
29863relocatable and non-relocatable DLLs are supported).
29864
29865@item 
29866You can build Ada DLLs for use in other applications. These applications
29867can be written in a language other than Ada (e.g., C, C++, etc). Again both
29868relocatable and non-relocatable Ada DLLs are supported.
29869
29870@item 
29871You can include Windows resources in your Ada application.
29872
29873@item 
29874You can use or create COM/DCOM objects.
29875@end itemize
29876
29877Immediately below are listed all known general GNAT-for-Windows restrictions.
29878Other restrictions about specific features like Windows Resources and DLLs
29879are listed in separate sections below.
29880
29881
29882@itemize *
29883
29884@item 
29885It is not possible to use @cite{GetLastError} and @cite{SetLastError}
29886when tasking, protected records, or exceptions are used. In these
29887cases, in order to implement Ada semantics, the GNAT run-time system
29888calls certain Win32 routines that set the last error variable to 0 upon
29889success. It should be possible to use @cite{GetLastError} and
29890@cite{SetLastError} when tasking, protected record, and exception
29891features are not used, but it is not guaranteed to work.
29892
29893@item 
29894It is not possible to link against Microsoft C++ libraries except for
29895import libraries. Interfacing must be done by the mean of DLLs.
29896
29897@item 
29898It is possible to link against Microsoft C libraries. Yet the preferred
29899solution is to use C/C++ compiler that comes with GNAT, since it
29900doesn't require having two different development environments and makes the
29901inter-language debugging experience smoother.
29902
29903@item 
29904When the compilation environment is located on FAT32 drives, users may
29905experience recompilations of the source files that have not changed if
29906Daylight Saving Time (DST) state has changed since the last time files
29907were compiled. NTFS drives do not have this problem.
29908
29909@item 
29910No components of the GNAT toolset use any entries in the Windows
29911registry. The only entries that can be created are file associations and
29912PATH settings, provided the user has chosen to create them at installation
29913time, as well as some minimal book-keeping information needed to correctly
29914uninstall or integrate different GNAT products.
29915@end itemize
29916
29917@node Using a network installation of GNAT,CONSOLE and WINDOWS subsystems,Using GNAT on Windows,Microsoft Windows Topics
29918@anchor{gnat_ugn/platform_specific_information id11}@anchor{26a}@anchor{gnat_ugn/platform_specific_information using-a-network-installation-of-gnat}@anchor{26b}
29919@subsection Using a network installation of GNAT
29920
29921
29922Make sure the system on which GNAT is installed is accessible from the
29923current machine, i.e., the install location is shared over the network.
29924Shared resources are accessed on Windows by means of UNC paths, which
29925have the format @cite{\\server\sharename\path}
29926
29927In order to use such a network installation, simply add the UNC path of the
29928@code{bin} directory of your GNAT installation in front of your PATH. For
29929example, if GNAT is installed in @code{\GNAT} directory of a share location
29930called @code{c-drive} on a machine @code{LOKI}, the following command will
29931make it available:
29932
29933@quotation
29934
29935@example
29936$ path \\loki\c-drive\gnat\bin;%path%`
29937@end example
29938@end quotation
29939
29940Be aware that every compilation using the network installation results in the
29941transfer of large amounts of data across the network and will likely cause
29942serious performance penalty.
29943
29944@node CONSOLE and WINDOWS subsystems,Temporary Files,Using a network installation of GNAT,Microsoft Windows Topics
29945@anchor{gnat_ugn/platform_specific_information id12}@anchor{26c}@anchor{gnat_ugn/platform_specific_information console-and-windows-subsystems}@anchor{26d}
29946@subsection CONSOLE and WINDOWS subsystems
29947
29948
29949@geindex CONSOLE Subsystem
29950
29951@geindex WINDOWS Subsystem
29952
29953@geindex -mwindows
29954
29955There are two main subsystems under Windows. The @cite{CONSOLE} subsystem
29956(which is the default subsystem) will always create a console when
29957launching the application. This is not something desirable when the
29958application has a Windows GUI. To get rid of this console the
29959application must be using the @cite{WINDOWS} subsystem. To do so
29960the @emph{-mwindows} linker option must be specified.
29961
29962@quotation
29963
29964@example
29965$ gnatmake winprog -largs -mwindows
29966@end example
29967@end quotation
29968
29969@node Temporary Files,Mixed-Language Programming on Windows,CONSOLE and WINDOWS subsystems,Microsoft Windows Topics
29970@anchor{gnat_ugn/platform_specific_information id13}@anchor{26e}@anchor{gnat_ugn/platform_specific_information temporary-files}@anchor{26f}
29971@subsection Temporary Files
29972
29973
29974@geindex Temporary files
29975
29976It is possible to control where temporary files gets created by setting
29977the 
29978@geindex TMP
29979@geindex environment variable; TMP
29980@code{TMP} environment variable. The file will be created:
29981
29982
29983@itemize *
29984
29985@item 
29986Under the directory pointed to by the 
29987@geindex TMP
29988@geindex environment variable; TMP
29989@code{TMP} environment variable if
29990this directory exists.
29991
29992@item 
29993Under @code{c:\temp}, if the 
29994@geindex TMP
29995@geindex environment variable; TMP
29996@code{TMP} environment variable is not
29997set (or not pointing to a directory) and if this directory exists.
29998
29999@item 
30000Under the current working directory otherwise.
30001@end itemize
30002
30003This allows you to determine exactly where the temporary
30004file will be created. This is particularly useful in networked
30005environments where you may not have write access to some
30006directories.
30007
30008@node Mixed-Language Programming on Windows,,Temporary Files,Microsoft Windows Topics
30009@anchor{gnat_ugn/platform_specific_information mixed-language-programming-on-windows}@anchor{270}@anchor{gnat_ugn/platform_specific_information id14}@anchor{271}
30010@subsection Mixed-Language Programming on Windows
30011
30012
30013Developing pure Ada applications on Windows is no different than on
30014other GNAT-supported platforms. However, when developing or porting an
30015application that contains a mix of Ada and C/C++, the choice of your
30016Windows C/C++ development environment conditions your overall
30017interoperability strategy.
30018
30019If you use @emph{gcc} or Microsoft C to compile the non-Ada part of
30020your application, there are no Windows-specific restrictions that
30021affect the overall interoperability with your Ada code. If you do want
30022to use the Microsoft tools for your C++ code, you have two choices:
30023
30024
30025@itemize *
30026
30027@item 
30028Encapsulate your C++ code in a DLL to be linked with your Ada
30029application. In this case, use the Microsoft or whatever environment to
30030build the DLL and use GNAT to build your executable
30031(@ref{272,,Using DLLs with GNAT}).
30032
30033@item 
30034Or you can encapsulate your Ada code in a DLL to be linked with the
30035other part of your application. In this case, use GNAT to build the DLL
30036(@ref{273,,Building DLLs with GNAT Project files}) and use the Microsoft
30037or whatever environment to build your executable.
30038@end itemize
30039
30040In addition to the description about C main in
30041@ref{46,,Mixed Language Programming} section, if the C main uses a
30042stand-alone library it is required on x86-windows to
30043setup the SEH context. For this the C main must looks like this:
30044
30045@quotation
30046
30047@example
30048/* main.c */
30049extern void adainit (void);
30050extern void adafinal (void);
30051extern void __gnat_initialize(void*);
30052extern void call_to_ada (void);
30053
30054int main (int argc, char *argv[])
30055@{
30056  int SEH [2];
30057
30058  /* Initialize the SEH context */
30059  __gnat_initialize (&SEH);
30060
30061  adainit();
30062
30063  /* Then call Ada services in the stand-alone library */
30064
30065  call_to_ada();
30066
30067  adafinal();
30068@}
30069@end example
30070@end quotation
30071
30072Note that this is not needed on x86_64-windows where the Windows
30073native SEH support is used.
30074
30075@menu
30076* Windows Calling Conventions:: 
30077* Introduction to Dynamic Link Libraries (DLLs): Introduction to Dynamic Link Libraries DLLs. 
30078* Using DLLs with GNAT:: 
30079* Building DLLs with GNAT Project files:: 
30080* Building DLLs with GNAT:: 
30081* Building DLLs with gnatdll:: 
30082* Ada DLLs and Finalization:: 
30083* Creating a Spec for Ada DLLs:: 
30084* GNAT and Windows Resources:: 
30085* Debugging a DLL:: 
30086* Setting Stack Size from gnatlink:: 
30087* Setting Heap Size from gnatlink:: 
30088
30089@end menu
30090
30091@node Windows Calling Conventions,Introduction to Dynamic Link Libraries DLLs,,Mixed-Language Programming on Windows
30092@anchor{gnat_ugn/platform_specific_information windows-calling-conventions}@anchor{274}@anchor{gnat_ugn/platform_specific_information id15}@anchor{275}
30093@subsubsection Windows Calling Conventions
30094
30095
30096@geindex Stdcall
30097
30098@geindex APIENTRY
30099
30100This section pertain only to Win32. On Win64 there is a single native
30101calling convention. All convention specifiers are ignored on this
30102platform.
30103
30104When a subprogram @cite{F} (caller) calls a subprogram @cite{G}
30105(callee), there are several ways to push @cite{G}'s parameters on the
30106stack and there are several possible scenarios to clean up the stack
30107upon @cite{G}'s return. A calling convention is an agreed upon software
30108protocol whereby the responsibilities between the caller (@cite{F}) and
30109the callee (@cite{G}) are clearly defined. Several calling conventions
30110are available for Windows:
30111
30112
30113@itemize *
30114
30115@item 
30116@cite{C} (Microsoft defined)
30117
30118@item 
30119@cite{Stdcall} (Microsoft defined)
30120
30121@item 
30122@cite{Win32} (GNAT specific)
30123
30124@item 
30125@cite{DLL} (GNAT specific)
30126@end itemize
30127
30128@menu
30129* C Calling Convention:: 
30130* Stdcall Calling Convention:: 
30131* Win32 Calling Convention:: 
30132* DLL Calling Convention:: 
30133
30134@end menu
30135
30136@node C Calling Convention,Stdcall Calling Convention,,Windows Calling Conventions
30137@anchor{gnat_ugn/platform_specific_information c-calling-convention}@anchor{276}@anchor{gnat_ugn/platform_specific_information id16}@anchor{277}
30138@subsubsection @cite{C} Calling Convention
30139
30140
30141This is the default calling convention used when interfacing to C/C++
30142routines compiled with either @emph{gcc} or Microsoft Visual C++.
30143
30144In the @cite{C} calling convention subprogram parameters are pushed on the
30145stack by the caller from right to left. The caller itself is in charge of
30146cleaning up the stack after the call. In addition, the name of a routine
30147with @cite{C} calling convention is mangled by adding a leading underscore.
30148
30149The name to use on the Ada side when importing (or exporting) a routine
30150with @cite{C} calling convention is the name of the routine. For
30151instance the C function:
30152
30153@quotation
30154
30155@example
30156int get_val (long);
30157@end example
30158@end quotation
30159
30160should be imported from Ada as follows:
30161
30162@quotation
30163
30164@example
30165function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30166pragma Import (C, Get_Val, External_Name => "get_val");
30167@end example
30168@end quotation
30169
30170Note that in this particular case the @cite{External_Name} parameter could
30171have been omitted since, when missing, this parameter is taken to be the
30172name of the Ada entity in lower case. When the @cite{Link_Name} parameter
30173is missing, as in the above example, this parameter is set to be the
30174@cite{External_Name} with a leading underscore.
30175
30176When importing a variable defined in C, you should always use the @cite{C}
30177calling convention unless the object containing the variable is part of a
30178DLL (in which case you should use the @cite{Stdcall} calling
30179convention, @ref{278,,Stdcall Calling Convention}).
30180
30181@node Stdcall Calling Convention,Win32 Calling Convention,C Calling Convention,Windows Calling Conventions
30182@anchor{gnat_ugn/platform_specific_information stdcall-calling-convention}@anchor{278}@anchor{gnat_ugn/platform_specific_information id17}@anchor{279}
30183@subsubsection @cite{Stdcall} Calling Convention
30184
30185
30186This convention, which was the calling convention used for Pascal
30187programs, is used by Microsoft for all the routines in the Win32 API for
30188efficiency reasons. It must be used to import any routine for which this
30189convention was specified.
30190
30191In the @cite{Stdcall} calling convention subprogram parameters are pushed
30192on the stack by the caller from right to left. The callee (and not the
30193caller) is in charge of cleaning the stack on routine exit. In addition,
30194the name of a routine with @cite{Stdcall} calling convention is mangled by
30195adding a leading underscore (as for the @cite{C} calling convention) and a
30196trailing @code{@@@emph{nn}}, where @cite{nn} is the overall size (in
30197bytes) of the parameters passed to the routine.
30198
30199The name to use on the Ada side when importing a C routine with a
30200@cite{Stdcall} calling convention is the name of the C routine. The leading
30201underscore and trailing @code{@@@emph{nn}} are added automatically by
30202the compiler. For instance the Win32 function:
30203
30204@quotation
30205
30206@example
30207APIENTRY int get_val (long);
30208@end example
30209@end quotation
30210
30211should be imported from Ada as follows:
30212
30213@quotation
30214
30215@example
30216function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30217pragma Import (Stdcall, Get_Val);
30218--  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
30219@end example
30220@end quotation
30221
30222As for the @cite{C} calling convention, when the @cite{External_Name}
30223parameter is missing, it is taken to be the name of the Ada entity in lower
30224case. If instead of writing the above import pragma you write:
30225
30226@quotation
30227
30228@example
30229function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30230pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
30231@end example
30232@end quotation
30233
30234then the imported routine is @cite{_retrieve_val@@4}. However, if instead
30235of specifying the @cite{External_Name} parameter you specify the
30236@cite{Link_Name} as in the following example:
30237
30238@quotation
30239
30240@example
30241function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30242pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
30243@end example
30244@end quotation
30245
30246then the imported routine is @cite{retrieve_val}, that is, there is no
30247decoration at all. No leading underscore and no Stdcall suffix
30248@code{@@@emph{nn}}.
30249
30250This is especially important as in some special cases a DLL's entry
30251point name lacks a trailing @code{@@@emph{nn}} while the exported
30252name generated for a call has it.
30253
30254It is also possible to import variables defined in a DLL by using an
30255import pragma for a variable. As an example, if a DLL contains a
30256variable defined as:
30257
30258@quotation
30259
30260@example
30261int my_var;
30262@end example
30263@end quotation
30264
30265then, to access this variable from Ada you should write:
30266
30267@quotation
30268
30269@example
30270My_Var : Interfaces.C.int;
30271pragma Import (Stdcall, My_Var);
30272@end example
30273@end quotation
30274
30275Note that to ease building cross-platform bindings this convention
30276will be handled as a @cite{C} calling convention on non-Windows platforms.
30277
30278@node Win32 Calling Convention,DLL Calling Convention,Stdcall Calling Convention,Windows Calling Conventions
30279@anchor{gnat_ugn/platform_specific_information id18}@anchor{27a}@anchor{gnat_ugn/platform_specific_information win32-calling-convention}@anchor{27b}
30280@subsubsection @cite{Win32} Calling Convention
30281
30282
30283This convention, which is GNAT-specific is fully equivalent to the
30284@cite{Stdcall} calling convention described above.
30285
30286@node DLL Calling Convention,,Win32 Calling Convention,Windows Calling Conventions
30287@anchor{gnat_ugn/platform_specific_information id19}@anchor{27c}@anchor{gnat_ugn/platform_specific_information dll-calling-convention}@anchor{27d}
30288@subsubsection @cite{DLL} Calling Convention
30289
30290
30291This convention, which is GNAT-specific is fully equivalent to the
30292@cite{Stdcall} calling convention described above.
30293
30294@node Introduction to Dynamic Link Libraries DLLs,Using DLLs with GNAT,Windows Calling Conventions,Mixed-Language Programming on Windows
30295@anchor{gnat_ugn/platform_specific_information id20}@anchor{27e}@anchor{gnat_ugn/platform_specific_information introduction-to-dynamic-link-libraries-dlls}@anchor{27f}
30296@subsubsection Introduction to Dynamic Link Libraries (DLLs)
30297
30298
30299@geindex DLL
30300
30301A Dynamically Linked Library (DLL) is a library that can be shared by
30302several applications running under Windows. A DLL can contain any number of
30303routines and variables.
30304
30305One advantage of DLLs is that you can change and enhance them without
30306forcing all the applications that depend on them to be relinked or
30307recompiled. However, you should be aware than all calls to DLL routines are
30308slower since, as you will understand below, such calls are indirect.
30309
30310To illustrate the remainder of this section, suppose that an application
30311wants to use the services of a DLL @code{API.dll}. To use the services
30312provided by @code{API.dll} you must statically link against the DLL or
30313an import library which contains a jump table with an entry for each
30314routine and variable exported by the DLL. In the Microsoft world this
30315import library is called @code{API.lib}. When using GNAT this import
30316library is called either @code{libAPI.dll.a}, @code{libapi.dll.a},
30317@code{libAPI.a} or @code{libapi.a} (names are case insensitive).
30318
30319After you have linked your application with the DLL or the import library
30320and you run your application, here is what happens:
30321
30322
30323@itemize *
30324
30325@item 
30326Your application is loaded into memory.
30327
30328@item 
30329The DLL @code{API.dll} is mapped into the address space of your
30330application. This means that:
30331
30332
30333@itemize -
30334
30335@item 
30336The DLL will use the stack of the calling thread.
30337
30338@item 
30339The DLL will use the virtual address space of the calling process.
30340
30341@item 
30342The DLL will allocate memory from the virtual address space of the calling
30343process.
30344
30345@item 
30346Handles (pointers) can be safely exchanged between routines in the DLL
30347routines and routines in the application using the DLL.
30348@end itemize
30349
30350@item 
30351The entries in the jump table (from the import library @code{libAPI.dll.a}
30352or @code{API.lib} or automatically created when linking against a DLL)
30353which is part of your application are initialized with the addresses
30354of the routines and variables in @code{API.dll}.
30355
30356@item 
30357If present in @code{API.dll}, routines @cite{DllMain} or
30358@cite{DllMainCRTStartup} are invoked. These routines typically contain
30359the initialization code needed for the well-being of the routines and
30360variables exported by the DLL.
30361@end itemize
30362
30363There is an additional point which is worth mentioning. In the Windows
30364world there are two kind of DLLs: relocatable and non-relocatable
30365DLLs. Non-relocatable DLLs can only be loaded at a very specific address
30366in the target application address space. If the addresses of two
30367non-relocatable DLLs overlap and these happen to be used by the same
30368application, a conflict will occur and the application will run
30369incorrectly. Hence, when possible, it is always preferable to use and
30370build relocatable DLLs. Both relocatable and non-relocatable DLLs are
30371supported by GNAT. Note that the @emph{-s} linker option (see GNU Linker
30372User's Guide) removes the debugging symbols from the DLL but the DLL can
30373still be relocated.
30374
30375As a side note, an interesting difference between Microsoft DLLs and
30376Unix shared libraries, is the fact that on most Unix systems all public
30377routines are exported by default in a Unix shared library, while under
30378Windows it is possible (but not required) to list exported routines in
30379a definition file (see @ref{280,,The Definition File}).
30380
30381@node Using DLLs with GNAT,Building DLLs with GNAT Project files,Introduction to Dynamic Link Libraries DLLs,Mixed-Language Programming on Windows
30382@anchor{gnat_ugn/platform_specific_information id21}@anchor{281}@anchor{gnat_ugn/platform_specific_information using-dlls-with-gnat}@anchor{272}
30383@subsubsection Using DLLs with GNAT
30384
30385
30386To use the services of a DLL, say @code{API.dll}, in your Ada application
30387you must have:
30388
30389
30390@itemize *
30391
30392@item 
30393The Ada spec for the routines and/or variables you want to access in
30394@code{API.dll}. If not available this Ada spec must be built from the C/C++
30395header files provided with the DLL.
30396
30397@item 
30398The import library (@code{libAPI.dll.a} or @code{API.lib}). As previously
30399mentioned an import library is a statically linked library containing the
30400import table which will be filled at load time to point to the actual
30401@code{API.dll} routines. Sometimes you don't have an import library for the
30402DLL you want to use. The following sections will explain how to build
30403one. Note that this is optional.
30404
30405@item 
30406The actual DLL, @code{API.dll}.
30407@end itemize
30408
30409Once you have all the above, to compile an Ada application that uses the
30410services of @code{API.dll} and whose main subprogram is @cite{My_Ada_App},
30411you simply issue the command
30412
30413@quotation
30414
30415@example
30416$ gnatmake my_ada_app -largs -lAPI
30417@end example
30418@end quotation
30419
30420The argument @emph{-largs -lAPI} at the end of the @emph{gnatmake} command
30421tells the GNAT linker to look for an import library. The linker will
30422look for a library name in this specific order:
30423
30424
30425@itemize *
30426
30427@item 
30428@code{libAPI.dll.a}
30429
30430@item 
30431@code{API.dll.a}
30432
30433@item 
30434@code{libAPI.a}
30435
30436@item 
30437@code{API.lib}
30438
30439@item 
30440@code{libAPI.dll}
30441
30442@item 
30443@code{API.dll}
30444@end itemize
30445
30446The first three are the GNU style import libraries. The third is the
30447Microsoft style import libraries. The last two are the actual DLL names.
30448
30449Note that if the Ada package spec for @code{API.dll} contains the
30450following pragma
30451
30452@quotation
30453
30454@example
30455pragma Linker_Options ("-lAPI");
30456@end example
30457@end quotation
30458
30459you do not have to add @emph{-largs -lAPI} at the end of the
30460@emph{gnatmake} command.
30461
30462If any one of the items above is missing you will have to create it
30463yourself. The following sections explain how to do so using as an
30464example a fictitious DLL called @code{API.dll}.
30465
30466@menu
30467* Creating an Ada Spec for the DLL Services:: 
30468* Creating an Import Library:: 
30469
30470@end menu
30471
30472@node Creating an Ada Spec for the DLL Services,Creating an Import Library,,Using DLLs with GNAT
30473@anchor{gnat_ugn/platform_specific_information creating-an-ada-spec-for-the-dll-services}@anchor{282}@anchor{gnat_ugn/platform_specific_information id22}@anchor{283}
30474@subsubsection Creating an Ada Spec for the DLL Services
30475
30476
30477A DLL typically comes with a C/C++ header file which provides the
30478definitions of the routines and variables exported by the DLL. The Ada
30479equivalent of this header file is a package spec that contains definitions
30480for the imported entities. If the DLL you intend to use does not come with
30481an Ada spec you have to generate one such spec yourself. For example if
30482the header file of @code{API.dll} is a file @code{api.h} containing the
30483following two definitions:
30484
30485@quotation
30486
30487@example
30488int some_var;
30489int get (char *);
30490@end example
30491@end quotation
30492
30493then the equivalent Ada spec could be:
30494
30495@quotation
30496
30497@example
30498with Interfaces.C.Strings;
30499package API is
30500   use Interfaces;
30501
30502   Some_Var : C.int;
30503   function Get (Str : C.Strings.Chars_Ptr) return C.int;
30504
30505private
30506   pragma Import (C, Get);
30507   pragma Import (DLL, Some_Var);
30508end API;
30509@end example
30510@end quotation
30511
30512@node Creating an Import Library,,Creating an Ada Spec for the DLL Services,Using DLLs with GNAT
30513@anchor{gnat_ugn/platform_specific_information id23}@anchor{284}@anchor{gnat_ugn/platform_specific_information creating-an-import-library}@anchor{285}
30514@subsubsection Creating an Import Library
30515
30516
30517@geindex Import library
30518
30519If a Microsoft-style import library @code{API.lib} or a GNAT-style
30520import library @code{libAPI.dll.a} or @code{libAPI.a} is available
30521with @code{API.dll} you can skip this section. You can also skip this
30522section if @code{API.dll} or @code{libAPI.dll} is built with GNU tools
30523as in this case it is possible to link directly against the
30524DLL. Otherwise read on.
30525
30526@geindex Definition file
30527@anchor{gnat_ugn/platform_specific_information the-definition-file}@anchor{280}
30528@subsubheading The Definition File
30529
30530
30531As previously mentioned, and unlike Unix systems, the list of symbols
30532that are exported from a DLL must be provided explicitly in Windows.
30533The main goal of a definition file is precisely that: list the symbols
30534exported by a DLL. A definition file (usually a file with a @cite{.def}
30535suffix) has the following structure:
30536
30537@quotation
30538
30539@example
30540[LIBRARY `name`]
30541[DESCRIPTION `string`]
30542EXPORTS
30543   `symbol1`
30544   `symbol2`
30545   ...
30546@end example
30547@end quotation
30548
30549
30550@table @asis
30551
30552@item @emph{LIBRARY `name`}
30553
30554This section, which is optional, gives the name of the DLL.
30555
30556@item @emph{DESCRIPTION `string`}
30557
30558This section, which is optional, gives a description string that will be
30559embedded in the import library.
30560
30561@item @emph{EXPORTS}
30562
30563This section gives the list of exported symbols (procedures, functions or
30564variables). For instance in the case of @code{API.dll} the @cite{EXPORTS}
30565section of @code{API.def} looks like:
30566
30567@example
30568EXPORTS
30569   some_var
30570   get
30571@end example
30572@end table
30573
30574Note that you must specify the correct suffix (@code{@@@emph{nn}})
30575(see @ref{274,,Windows Calling Conventions}) for a Stdcall
30576calling convention function in the exported symbols list.
30577
30578There can actually be other sections in a definition file, but these
30579sections are not relevant to the discussion at hand.
30580
30581@subsubheading GNAT-Style Import Library
30582
30583@anchor{gnat_ugn/platform_specific_information gnat-style-import-library}@anchor{286}
30584To create a static import library from @code{API.dll} with the GNAT tools
30585you should proceed as follows:
30586
30587
30588@itemize *
30589
30590@item 
30591Create the definition file @code{API.def}
30592(see @ref{280,,The Definition File}).
30593For that use the @cite{dll2def} tool as follows:
30594
30595@example
30596$ dll2def API.dll > API.def
30597@end example
30598
30599@cite{dll2def} is a very simple tool: it takes as input a DLL and prints
30600to standard output the list of entry points in the DLL. Note that if
30601some routines in the DLL have the @cite{Stdcall} convention
30602(@ref{274,,Windows Calling Conventions}) with stripped @code{@@@emph{nn}}
30603suffix then you'll have to edit @code{api.def} to add it, and specify
30604@emph{-k} to @emph{gnatdll} when creating the import library.
30605
30606Here are some hints to find the right @code{@@@emph{nn}} suffix.
30607
30608
30609@itemize -
30610
30611@item 
30612If you have the Microsoft import library (.lib), it is possible to get
30613the right symbols by using Microsoft @cite{dumpbin} tool (see the
30614corresponding Microsoft documentation for further details).
30615
30616@example
30617$ dumpbin /exports api.lib
30618@end example
30619
30620@item 
30621If you have a message about a missing symbol at link time the compiler
30622tells you what symbol is expected. You just have to go back to the
30623definition file and add the right suffix.
30624@end itemize
30625
30626@item 
30627Build the import library @cite{libAPI.dll.a}, using @cite{gnatdll}
30628(see @ref{287,,Using gnatdll}) as follows:
30629
30630@example
30631$ gnatdll -e API.def -d API.dll
30632@end example
30633
30634@cite{gnatdll} takes as input a definition file @code{API.def} and the
30635name of the DLL containing the services listed in the definition file
30636@code{API.dll}. The name of the static import library generated is
30637computed from the name of the definition file as follows: if the
30638definition file name is @cite{xyz`}.def`, the import library name will
30639be @cite{lib`@w{`}xyz`}.a`. Note that in the previous example option
30640@emph{-e} could have been removed because the name of the definition
30641file (before the '@cite{.def}' suffix) is the same as the name of the
30642DLL (@ref{287,,Using gnatdll} for more information about @cite{gnatdll}).
30643@end itemize
30644
30645@subsubheading Microsoft-Style Import Library
30646
30647
30648With GNAT you can either use a GNAT-style or Microsoft-style import
30649library. A Microsoft import library is needed only if you plan to make an
30650Ada DLL available to applications developed with Microsoft
30651tools (@ref{270,,Mixed-Language Programming on Windows}).
30652
30653To create a Microsoft-style import library for @code{API.dll} you
30654should proceed as follows:
30655
30656
30657@itemize *
30658
30659@item 
30660Create the definition file @code{API.def} from the DLL. For this use either
30661the @cite{dll2def} tool as described above or the Microsoft @cite{dumpbin}
30662tool (see the corresponding Microsoft documentation for further details).
30663
30664@item 
30665Build the actual import library using Microsoft's @cite{lib} utility:
30666
30667@example
30668$ lib -machine:IX86 -def:API.def -out:API.lib
30669@end example
30670
30671If you use the above command the definition file @code{API.def} must
30672contain a line giving the name of the DLL:
30673
30674@example
30675LIBRARY      "API"
30676@end example
30677
30678See the Microsoft documentation for further details about the usage of
30679@cite{lib}.
30680@end itemize
30681
30682@node Building DLLs with GNAT Project files,Building DLLs with GNAT,Using DLLs with GNAT,Mixed-Language Programming on Windows
30683@anchor{gnat_ugn/platform_specific_information id24}@anchor{288}@anchor{gnat_ugn/platform_specific_information building-dlls-with-gnat-project-files}@anchor{273}
30684@subsubsection Building DLLs with GNAT Project files
30685
30686
30687@geindex DLLs
30688@geindex building
30689
30690There is nothing specific to Windows in the build process.
30691@ref{8a,,Library Projects}.
30692
30693Due to a system limitation, it is not possible under Windows to create threads
30694when inside the @cite{DllMain} routine which is used for auto-initialization
30695of shared libraries, so it is not possible to have library level tasks in SALs.
30696
30697@node Building DLLs with GNAT,Building DLLs with gnatdll,Building DLLs with GNAT Project files,Mixed-Language Programming on Windows
30698@anchor{gnat_ugn/platform_specific_information building-dlls-with-gnat}@anchor{289}@anchor{gnat_ugn/platform_specific_information id25}@anchor{28a}
30699@subsubsection Building DLLs with GNAT
30700
30701
30702@geindex DLLs
30703@geindex building
30704
30705This section explain how to build DLLs using the GNAT built-in DLL
30706support. With the following procedure it is straight forward to build
30707and use DLLs with GNAT.
30708
30709
30710@itemize *
30711
30712@item 
30713Building object files.
30714The first step is to build all objects files that are to be included
30715into the DLL. This is done by using the standard @emph{gnatmake} tool.
30716
30717@item 
30718Building the DLL.
30719To build the DLL you must use @emph{gcc}'s @emph{-shared} and
30720@emph{-shared-libgcc} options. It is quite simple to use this method:
30721
30722@example
30723$ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o ...
30724@end example
30725
30726It is important to note that in this case all symbols found in the
30727object files are automatically exported. It is possible to restrict
30728the set of symbols to export by passing to @emph{gcc} a definition
30729file (see @ref{280,,The Definition File}).
30730For example:
30731
30732@example
30733$ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o ...
30734@end example
30735
30736If you use a definition file you must export the elaboration procedures
30737for every package that required one. Elaboration procedures are named
30738using the package name followed by "_E".
30739
30740@item 
30741Preparing DLL to be used.
30742For the DLL to be used by client programs the bodies must be hidden
30743from it and the .ali set with read-only attribute. This is very important
30744otherwise GNAT will recompile all packages and will not actually use
30745the code in the DLL. For example:
30746
30747@example
30748$ mkdir apilib
30749$ copy *.ads *.ali api.dll apilib
30750$ attrib +R apilib\\*.ali
30751@end example
30752@end itemize
30753
30754At this point it is possible to use the DLL by directly linking
30755against it. Note that you must use the GNAT shared runtime when using
30756GNAT shared libraries. This is achieved by using @emph{-shared} binder's
30757option.
30758
30759@quotation
30760
30761@example
30762$ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
30763@end example
30764@end quotation
30765
30766@node Building DLLs with gnatdll,Ada DLLs and Finalization,Building DLLs with GNAT,Mixed-Language Programming on Windows
30767@anchor{gnat_ugn/platform_specific_information building-dlls-with-gnatdll}@anchor{28b}@anchor{gnat_ugn/platform_specific_information id26}@anchor{28c}
30768@subsubsection Building DLLs with gnatdll
30769
30770
30771@geindex DLLs
30772@geindex building
30773
30774Note that it is preferred to use GNAT Project files
30775(@ref{273,,Building DLLs with GNAT Project files}) or the built-in GNAT
30776DLL support (@ref{289,,Building DLLs with GNAT}) or to build DLLs.
30777
30778This section explains how to build DLLs containing Ada code using
30779@cite{gnatdll}. These DLLs will be referred to as Ada DLLs in the
30780remainder of this section.
30781
30782The steps required to build an Ada DLL that is to be used by Ada as well as
30783non-Ada applications are as follows:
30784
30785
30786@itemize *
30787
30788@item 
30789You need to mark each Ada @emph{entity} exported by the DLL with a @cite{C} or
30790@cite{Stdcall} calling convention to avoid any Ada name mangling for the
30791entities exported by the DLL
30792(see @ref{28d,,Exporting Ada Entities}). You can
30793skip this step if you plan to use the Ada DLL only from Ada applications.
30794
30795@item 
30796Your Ada code must export an initialization routine which calls the routine
30797@cite{adainit} generated by @emph{gnatbind} to perform the elaboration of
30798the Ada code in the DLL (@ref{28e,,Ada DLLs and Elaboration}). The initialization
30799routine exported by the Ada DLL must be invoked by the clients of the DLL
30800to initialize the DLL.
30801
30802@item 
30803When useful, the DLL should also export a finalization routine which calls
30804routine @cite{adafinal} generated by @emph{gnatbind} to perform the
30805finalization of the Ada code in the DLL (@ref{28f,,Ada DLLs and Finalization}).
30806The finalization routine exported by the Ada DLL must be invoked by the
30807clients of the DLL when the DLL services are no further needed.
30808
30809@item 
30810You must provide a spec for the services exported by the Ada DLL in each
30811of the programming languages to which you plan to make the DLL available.
30812
30813@item 
30814You must provide a definition file listing the exported entities
30815(@ref{280,,The Definition File}).
30816
30817@item 
30818Finally you must use @cite{gnatdll} to produce the DLL and the import
30819library (@ref{287,,Using gnatdll}).
30820@end itemize
30821
30822Note that a relocatable DLL stripped using the @cite{strip}
30823binutils tool will not be relocatable anymore. To build a DLL without
30824debug information pass @cite{-largs -s} to @cite{gnatdll}. This
30825restriction does not apply to a DLL built using a Library Project.
30826See @ref{8a,,Library Projects}.
30827
30828@c Limitations_When_Using_Ada_DLLs_from Ada:
30829
30830@menu
30831* Limitations When Using Ada DLLs from Ada:: 
30832* Exporting Ada Entities:: 
30833* Ada DLLs and Elaboration:: 
30834
30835@end menu
30836
30837@node Limitations When Using Ada DLLs from Ada,Exporting Ada Entities,,Building DLLs with gnatdll
30838@anchor{gnat_ugn/platform_specific_information limitations-when-using-ada-dlls-from-ada}@anchor{290}
30839@subsubsection Limitations When Using Ada DLLs from Ada
30840
30841
30842When using Ada DLLs from Ada applications there is a limitation users
30843should be aware of. Because on Windows the GNAT run time is not in a DLL of
30844its own, each Ada DLL includes a part of the GNAT run time. Specifically,
30845each Ada DLL includes the services of the GNAT run time that are necessary
30846to the Ada code inside the DLL. As a result, when an Ada program uses an
30847Ada DLL there are two independent GNAT run times: one in the Ada DLL and
30848one in the main program.
30849
30850It is therefore not possible to exchange GNAT run-time objects between the
30851Ada DLL and the main Ada program. Example of GNAT run-time objects are file
30852handles (e.g., @cite{Text_IO.File_Type}), tasks types, protected objects
30853types, etc.
30854
30855It is completely safe to exchange plain elementary, array or record types,
30856Windows object handles, etc.
30857
30858@node Exporting Ada Entities,Ada DLLs and Elaboration,Limitations When Using Ada DLLs from Ada,Building DLLs with gnatdll
30859@anchor{gnat_ugn/platform_specific_information exporting-ada-entities}@anchor{28d}@anchor{gnat_ugn/platform_specific_information id27}@anchor{291}
30860@subsubsection Exporting Ada Entities
30861
30862
30863@geindex Export table
30864
30865Building a DLL is a way to encapsulate a set of services usable from any
30866application. As a result, the Ada entities exported by a DLL should be
30867exported with the @cite{C} or @cite{Stdcall} calling conventions to avoid
30868any Ada name mangling. As an example here is an Ada package
30869@cite{API}, spec and body, exporting two procedures, a function, and a
30870variable:
30871
30872@quotation
30873
30874@example
30875with Interfaces.C; use Interfaces;
30876package API is
30877   Count : C.int := 0;
30878   function Factorial (Val : C.int) return C.int;
30879
30880   procedure Initialize_API;
30881   procedure Finalize_API;
30882   --  Initialization & Finalization routines. More in the next section.
30883private
30884   pragma Export (C, Initialize_API);
30885   pragma Export (C, Finalize_API);
30886   pragma Export (C, Count);
30887   pragma Export (C, Factorial);
30888end API;
30889@end example
30890
30891@example
30892package body API is
30893   function Factorial (Val : C.int) return C.int is
30894      Fact : C.int := 1;
30895   begin
30896      Count := Count + 1;
30897      for K in 1 .. Val loop
30898         Fact := Fact * K;
30899      end loop;
30900      return Fact;
30901   end Factorial;
30902
30903   procedure Initialize_API is
30904      procedure Adainit;
30905      pragma Import (C, Adainit);
30906   begin
30907      Adainit;
30908   end Initialize_API;
30909
30910   procedure Finalize_API is
30911      procedure Adafinal;
30912      pragma Import (C, Adafinal);
30913   begin
30914      Adafinal;
30915   end Finalize_API;
30916end API;
30917@end example
30918@end quotation
30919
30920If the Ada DLL you are building will only be used by Ada applications
30921you do not have to export Ada entities with a @cite{C} or @cite{Stdcall}
30922convention. As an example, the previous package could be written as
30923follows:
30924
30925@quotation
30926
30927@example
30928package API is
30929   Count : Integer := 0;
30930   function Factorial (Val : Integer) return Integer;
30931
30932   procedure Initialize_API;
30933   procedure Finalize_API;
30934   --  Initialization and Finalization routines.
30935end API;
30936@end example
30937
30938@example
30939package body API is
30940   function Factorial (Val : Integer) return Integer is
30941      Fact : Integer := 1;
30942   begin
30943      Count := Count + 1;
30944      for K in 1 .. Val loop
30945         Fact := Fact * K;
30946      end loop;
30947      return Fact;
30948   end Factorial;
30949
30950   ...
30951   --  The remainder of this package body is unchanged.
30952end API;
30953@end example
30954@end quotation
30955
30956Note that if you do not export the Ada entities with a @cite{C} or
30957@cite{Stdcall} convention you will have to provide the mangled Ada names
30958in the definition file of the Ada DLL
30959(@ref{292,,Creating the Definition File}).
30960
30961@node Ada DLLs and Elaboration,,Exporting Ada Entities,Building DLLs with gnatdll
30962@anchor{gnat_ugn/platform_specific_information ada-dlls-and-elaboration}@anchor{28e}@anchor{gnat_ugn/platform_specific_information id28}@anchor{293}
30963@subsubsection Ada DLLs and Elaboration
30964
30965
30966@geindex DLLs and elaboration
30967
30968The DLL that you are building contains your Ada code as well as all the
30969routines in the Ada library that are needed by it. The first thing a
30970user of your DLL must do is elaborate the Ada code
30971(@ref{11,,Elaboration Order Handling in GNAT}).
30972
30973To achieve this you must export an initialization routine
30974(@cite{Initialize_API} in the previous example), which must be invoked
30975before using any of the DLL services. This elaboration routine must call
30976the Ada elaboration routine @cite{adainit} generated by the GNAT binder
30977(@ref{ba,,Binding with Non-Ada Main Programs}). See the body of
30978@cite{Initialize_Api} for an example. Note that the GNAT binder is
30979automatically invoked during the DLL build process by the @cite{gnatdll}
30980tool (@ref{287,,Using gnatdll}).
30981
30982When a DLL is loaded, Windows systematically invokes a routine called
30983@cite{DllMain}. It would therefore be possible to call @cite{adainit}
30984directly from @cite{DllMain} without having to provide an explicit
30985initialization routine. Unfortunately, it is not possible to call
30986@cite{adainit} from the @cite{DllMain} if your program has library level
30987tasks because access to the @cite{DllMain} entry point is serialized by
30988the system (that is, only a single thread can execute 'through' it at a
30989time), which means that the GNAT run time will deadlock waiting for the
30990newly created task to complete its initialization.
30991
30992@node Ada DLLs and Finalization,Creating a Spec for Ada DLLs,Building DLLs with gnatdll,Mixed-Language Programming on Windows
30993@anchor{gnat_ugn/platform_specific_information id29}@anchor{294}@anchor{gnat_ugn/platform_specific_information ada-dlls-and-finalization}@anchor{28f}
30994@subsubsection Ada DLLs and Finalization
30995
30996
30997@geindex DLLs and finalization
30998
30999When the services of an Ada DLL are no longer needed, the client code should
31000invoke the DLL finalization routine, if available. The DLL finalization
31001routine is in charge of releasing all resources acquired by the DLL. In the
31002case of the Ada code contained in the DLL, this is achieved by calling
31003routine @cite{adafinal} generated by the GNAT binder
31004(@ref{ba,,Binding with Non-Ada Main Programs}).
31005See the body of @cite{Finalize_Api} for an
31006example. As already pointed out the GNAT binder is automatically invoked
31007during the DLL build process by the @cite{gnatdll} tool
31008(@ref{287,,Using gnatdll}).
31009
31010@node Creating a Spec for Ada DLLs,GNAT and Windows Resources,Ada DLLs and Finalization,Mixed-Language Programming on Windows
31011@anchor{gnat_ugn/platform_specific_information id30}@anchor{295}@anchor{gnat_ugn/platform_specific_information creating-a-spec-for-ada-dlls}@anchor{296}
31012@subsubsection Creating a Spec for Ada DLLs
31013
31014
31015To use the services exported by the Ada DLL from another programming
31016language (e.g., C), you have to translate the specs of the exported Ada
31017entities in that language. For instance in the case of @cite{API.dll},
31018the corresponding C header file could look like:
31019
31020@quotation
31021
31022@example
31023extern int *_imp__count;
31024#define count (*_imp__count)
31025int factorial (int);
31026@end example
31027@end quotation
31028
31029It is important to understand that when building an Ada DLL to be used by
31030other Ada applications, you need two different specs for the packages
31031contained in the DLL: one for building the DLL and the other for using
31032the DLL. This is because the @cite{DLL} calling convention is needed to
31033use a variable defined in a DLL, but when building the DLL, the variable
31034must have either the @cite{Ada} or @cite{C} calling convention. As an
31035example consider a DLL comprising the following package @cite{API}:
31036
31037@quotation
31038
31039@example
31040package API is
31041   Count : Integer := 0;
31042   ...
31043   --  Remainder of the package omitted.
31044end API;
31045@end example
31046@end quotation
31047
31048After producing a DLL containing package @cite{API}, the spec that
31049must be used to import @cite{API.Count} from Ada code outside of the
31050DLL is:
31051
31052@quotation
31053
31054@example
31055package API is
31056   Count : Integer;
31057   pragma Import (DLL, Count);
31058end API;
31059@end example
31060@end quotation
31061
31062@menu
31063* Creating the Definition File:: 
31064* Using gnatdll:: 
31065
31066@end menu
31067
31068@node Creating the Definition File,Using gnatdll,,Creating a Spec for Ada DLLs
31069@anchor{gnat_ugn/platform_specific_information creating-the-definition-file}@anchor{292}@anchor{gnat_ugn/platform_specific_information id31}@anchor{297}
31070@subsubsection Creating the Definition File
31071
31072
31073The definition file is the last file needed to build the DLL. It lists
31074the exported symbols. As an example, the definition file for a DLL
31075containing only package @cite{API} (where all the entities are exported
31076with a @cite{C} calling convention) is:
31077
31078@quotation
31079
31080@example
31081EXPORTS
31082    count
31083    factorial
31084    finalize_api
31085    initialize_api
31086@end example
31087@end quotation
31088
31089If the @cite{C} calling convention is missing from package @cite{API},
31090then the definition file contains the mangled Ada names of the above
31091entities, which in this case are:
31092
31093@quotation
31094
31095@example
31096EXPORTS
31097    api__count
31098    api__factorial
31099    api__finalize_api
31100    api__initialize_api
31101@end example
31102@end quotation
31103
31104@node Using gnatdll,,Creating the Definition File,Creating a Spec for Ada DLLs
31105@anchor{gnat_ugn/platform_specific_information using-gnatdll}@anchor{287}@anchor{gnat_ugn/platform_specific_information id32}@anchor{298}
31106@subsubsection Using @cite{gnatdll}
31107
31108
31109@geindex gnatdll
31110
31111@cite{gnatdll} is a tool to automate the DLL build process once all the Ada
31112and non-Ada sources that make up your DLL have been compiled.
31113@cite{gnatdll} is actually in charge of two distinct tasks: build the
31114static import library for the DLL and the actual DLL. The form of the
31115@cite{gnatdll} command is
31116
31117@quotation
31118
31119@example
31120$ gnatdll [`switches`] `list-of-files` [-largs `opts`]
31121@end example
31122@end quotation
31123
31124where @cite{list-of-files} is a list of ALI and object files. The object
31125file list must be the exact list of objects corresponding to the non-Ada
31126sources whose services are to be included in the DLL. The ALI file list
31127must be the exact list of ALI files for the corresponding Ada sources
31128whose services are to be included in the DLL. If @cite{list-of-files} is
31129missing, only the static import library is generated.
31130
31131You may specify any of the following switches to @cite{gnatdll}:
31132
31133@quotation
31134
31135@geindex -a (gnatdll)
31136@end quotation
31137
31138
31139@table @asis
31140
31141@item @code{-a[@emph{address}]}
31142
31143Build a non-relocatable DLL at @cite{address}. If @cite{address} is not
31144specified the default address @cite{0x11000000} will be used. By default,
31145when this switch is missing, @cite{gnatdll} builds relocatable DLL. We
31146advise the reader to build relocatable DLL.
31147
31148@geindex -b (gnatdll)
31149
31150@item @code{-b @emph{address}}
31151
31152Set the relocatable DLL base address. By default the address is
31153@cite{0x11000000}.
31154
31155@geindex -bargs (gnatdll)
31156
31157@item @code{-bargs @emph{opts}}
31158
31159Binder options. Pass @cite{opts} to the binder.
31160
31161@geindex -d (gnatdll)
31162
31163@item @code{-d @emph{dllfile}}
31164
31165@cite{dllfile} is the name of the DLL. This switch must be present for
31166@cite{gnatdll} to do anything. The name of the generated import library is
31167obtained algorithmically from @cite{dllfile} as shown in the following
31168example: if @cite{dllfile} is @cite{xyz.dll}, the import library name is
31169@cite{libxyz.dll.a}. The name of the definition file to use (if not specified
31170by option @emph{-e}) is obtained algorithmically from @cite{dllfile}
31171as shown in the following example:
31172if @cite{dllfile} is @cite{xyz.dll}, the definition
31173file used is @cite{xyz.def}.
31174
31175@geindex -e (gnatdll)
31176
31177@item @code{-e @emph{deffile}}
31178
31179@cite{deffile} is the name of the definition file.
31180
31181@geindex -g (gnatdll)
31182
31183@item @code{-g}
31184
31185Generate debugging information. This information is stored in the object
31186file and copied from there to the final DLL file by the linker,
31187where it can be read by the debugger. You must use the
31188@emph{-g} switch if you plan on using the debugger or the symbolic
31189stack traceback.
31190
31191@geindex -h (gnatdll)
31192
31193@item @code{-h}
31194
31195Help mode. Displays @cite{gnatdll} switch usage information.
31196
31197@geindex -I (gnatdll)
31198
31199@item @code{-I@emph{dir}}
31200
31201Direct @cite{gnatdll} to search the @cite{dir} directory for source and
31202object files needed to build the DLL.
31203(@ref{8e,,Search Paths and the Run-Time Library (RTL)}).
31204
31205@geindex -k (gnatdll)
31206
31207@item @code{-k}
31208
31209Removes the @code{@@@emph{nn}} suffix from the import library's exported
31210names, but keeps them for the link names. You must specify this
31211option if you want to use a @cite{Stdcall} function in a DLL for which
31212the @code{@@@emph{nn}} suffix has been removed. This is the case for most
31213of the Windows NT DLL for example. This option has no effect when
31214@emph{-n} option is specified.
31215
31216@geindex -l (gnatdll)
31217
31218@item @code{-l @emph{file}}
31219
31220The list of ALI and object files used to build the DLL are listed in
31221@cite{file}, instead of being given in the command line. Each line in
31222@cite{file} contains the name of an ALI or object file.
31223
31224@geindex -n (gnatdll)
31225
31226@item @code{-n}
31227
31228No Import. Do not create the import library.
31229
31230@geindex -q (gnatdll)
31231
31232@item @code{-q}
31233
31234Quiet mode. Do not display unnecessary messages.
31235
31236@geindex -v (gnatdll)
31237
31238@item @code{-v}
31239
31240Verbose mode. Display extra information.
31241
31242@geindex -largs (gnatdll)
31243
31244@item @code{-largs @emph{opts}}
31245
31246Linker options. Pass @cite{opts} to the linker.
31247@end table
31248
31249@subsubheading @cite{gnatdll} Example
31250
31251
31252As an example the command to build a relocatable DLL from @code{api.adb}
31253once @code{api.adb} has been compiled and @code{api.def} created is
31254
31255@quotation
31256
31257@example
31258$ gnatdll -d api.dll api.ali
31259@end example
31260@end quotation
31261
31262The above command creates two files: @code{libapi.dll.a} (the import
31263library) and @code{api.dll} (the actual DLL). If you want to create
31264only the DLL, just type:
31265
31266@quotation
31267
31268@example
31269$ gnatdll -d api.dll -n api.ali
31270@end example
31271@end quotation
31272
31273Alternatively if you want to create just the import library, type:
31274
31275@quotation
31276
31277@example
31278$ gnatdll -d api.dll
31279@end example
31280@end quotation
31281
31282@subsubheading @cite{gnatdll} behind the Scenes
31283
31284
31285This section details the steps involved in creating a DLL. @cite{gnatdll}
31286does these steps for you. Unless you are interested in understanding what
31287goes on behind the scenes, you should skip this section.
31288
31289We use the previous example of a DLL containing the Ada package @cite{API},
31290to illustrate the steps necessary to build a DLL. The starting point is a
31291set of objects that will make up the DLL and the corresponding ALI
31292files. In the case of this example this means that @code{api.o} and
31293@code{api.ali} are available. To build a relocatable DLL, @cite{gnatdll} does
31294the following:
31295
31296
31297@itemize *
31298
31299@item 
31300@cite{gnatdll} builds the base file (@code{api.base}). A base file gives
31301the information necessary to generate relocation information for the
31302DLL.
31303
31304@example
31305$ gnatbind -n api
31306$ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
31307@end example
31308
31309In addition to the base file, the @emph{gnatlink} command generates an
31310output file @code{api.jnk} which can be discarded. The @emph{-mdll} switch
31311asks @emph{gnatlink} to generate the routines @cite{DllMain} and
31312@cite{DllMainCRTStartup} that are called by the Windows loader when the DLL
31313is loaded into memory.
31314
31315@item 
31316@cite{gnatdll} uses @cite{dlltool} (see @ref{299,,Using dlltool}) to build the
31317export table (@code{api.exp}). The export table contains the relocation
31318information in a form which can be used during the final link to ensure
31319that the Windows loader is able to place the DLL anywhere in memory.
31320
31321@example
31322$ dlltool --dllname api.dll --def api.def --base-file api.base \\
31323          --output-exp api.exp
31324@end example
31325
31326@item 
31327@cite{gnatdll} builds the base file using the new export table. Note that
31328@emph{gnatbind} must be called once again since the binder generated file
31329has been deleted during the previous call to @emph{gnatlink}.
31330
31331@example
31332$ gnatbind -n api
31333$ gnatlink api -o api.jnk api.exp -mdll
31334      -Wl,--base-file,api.base
31335@end example
31336
31337@item 
31338@cite{gnatdll} builds the new export table using the new base file and
31339generates the DLL import library @code{libAPI.dll.a}.
31340
31341@example
31342$ dlltool --dllname api.dll --def api.def --base-file api.base \\
31343          --output-exp api.exp --output-lib libAPI.a
31344@end example
31345
31346@item 
31347Finally @cite{gnatdll} builds the relocatable DLL using the final export
31348table.
31349
31350@example
31351$ gnatbind -n api
31352$ gnatlink api api.exp -o api.dll -mdll
31353@end example
31354@end itemize
31355@anchor{gnat_ugn/platform_specific_information using-dlltool}@anchor{299}
31356@subsubheading Using @cite{dlltool}
31357
31358
31359@cite{dlltool} is the low-level tool used by @cite{gnatdll} to build
31360DLLs and static import libraries. This section summarizes the most
31361common @cite{dlltool} switches. The form of the @cite{dlltool} command
31362is
31363
31364@quotation
31365
31366@example
31367$ dlltool [`switches`]
31368@end example
31369@end quotation
31370
31371@cite{dlltool} switches include:
31372
31373@geindex --base-file (dlltool)
31374
31375
31376@table @asis
31377
31378@item @code{--base-file @emph{basefile}}
31379
31380Read the base file @cite{basefile} generated by the linker. This switch
31381is used to create a relocatable DLL.
31382@end table
31383
31384@geindex --def (dlltool)
31385
31386
31387@table @asis
31388
31389@item @code{--def @emph{deffile}}
31390
31391Read the definition file.
31392@end table
31393
31394@geindex --dllname (dlltool)
31395
31396
31397@table @asis
31398
31399@item @code{--dllname @emph{name}}
31400
31401Gives the name of the DLL. This switch is used to embed the name of the
31402DLL in the static import library generated by @cite{dlltool} with switch
31403@emph{--output-lib}.
31404@end table
31405
31406@geindex -k (dlltool)
31407
31408
31409@table @asis
31410
31411@item @code{-k}
31412
31413Kill @code{@@@emph{nn}} from exported names
31414(@ref{274,,Windows Calling Conventions}
31415for a discussion about @cite{Stdcall}-style symbols.
31416@end table
31417
31418@geindex --help (dlltool)
31419
31420
31421@table @asis
31422
31423@item @code{--help}
31424
31425Prints the @cite{dlltool} switches with a concise description.
31426@end table
31427
31428@geindex --output-exp (dlltool)
31429
31430
31431@table @asis
31432
31433@item @code{--output-exp @emph{exportfile}}
31434
31435Generate an export file @cite{exportfile}. The export file contains the
31436export table (list of symbols in the DLL) and is used to create the DLL.
31437@end table
31438
31439@geindex --output-lib (dlltool)
31440
31441
31442@table @asis
31443
31444@item @code{--output-lib @emph{libfile}}
31445
31446Generate a static import library @cite{libfile}.
31447@end table
31448
31449@geindex -v (dlltool)
31450
31451
31452@table @asis
31453
31454@item @code{-v}
31455
31456Verbose mode.
31457@end table
31458
31459@geindex --as (dlltool)
31460
31461
31462@table @asis
31463
31464@item @code{--as @emph{assembler-name}}
31465
31466Use @cite{assembler-name} as the assembler. The default is @cite{as}.
31467@end table
31468
31469@node GNAT and Windows Resources,Debugging a DLL,Creating a Spec for Ada DLLs,Mixed-Language Programming on Windows
31470@anchor{gnat_ugn/platform_specific_information gnat-and-windows-resources}@anchor{29a}@anchor{gnat_ugn/platform_specific_information id33}@anchor{29b}
31471@subsubsection GNAT and Windows Resources
31472
31473
31474@geindex Resources
31475@geindex windows
31476
31477Resources are an easy way to add Windows specific objects to your
31478application. The objects that can be added as resources include:
31479
31480
31481@itemize *
31482
31483@item 
31484menus
31485
31486@item 
31487accelerators
31488
31489@item 
31490dialog boxes
31491
31492@item 
31493string tables
31494
31495@item 
31496bitmaps
31497
31498@item 
31499cursors
31500
31501@item 
31502icons
31503
31504@item 
31505fonts
31506
31507@item 
31508version information
31509@end itemize
31510
31511For example, a version information resource can be defined as follow and
31512embedded into an executable or DLL:
31513
31514A version information resource can be used to embed information into an
31515executable or a DLL. These information can be viewed using the file properties
31516from the Windows Explorer. Here is an example of a version information
31517resource:
31518
31519@quotation
31520
31521@example
315221 VERSIONINFO
31523FILEVERSION     1,0,0,0
31524PRODUCTVERSION  1,0,0,0
31525BEGIN
31526  BLOCK "StringFileInfo"
31527  BEGIN
31528    BLOCK "080904E4"
31529    BEGIN
31530      VALUE "CompanyName", "My Company Name"
31531      VALUE "FileDescription", "My application"
31532      VALUE "FileVersion", "1.0"
31533      VALUE "InternalName", "my_app"
31534      VALUE "LegalCopyright", "My Name"
31535      VALUE "OriginalFilename", "my_app.exe"
31536      VALUE "ProductName", "My App"
31537      VALUE "ProductVersion", "1.0"
31538    END
31539  END
31540
31541  BLOCK "VarFileInfo"
31542  BEGIN
31543    VALUE "Translation", 0x809, 1252
31544  END
31545END
31546@end example
31547@end quotation
31548
31549The value @cite{0809} (langID) is for the U.K English language and
31550@cite{04E4} (charsetID), which is equal to @cite{1252} decimal, for
31551multilingual.
31552
31553This section explains how to build, compile and use resources. Note that this
31554section does not cover all resource objects, for a complete description see
31555the corresponding Microsoft documentation.
31556
31557@menu
31558* Building Resources:: 
31559* Compiling Resources:: 
31560* Using Resources:: 
31561
31562@end menu
31563
31564@node Building Resources,Compiling Resources,,GNAT and Windows Resources
31565@anchor{gnat_ugn/platform_specific_information building-resources}@anchor{29c}@anchor{gnat_ugn/platform_specific_information id34}@anchor{29d}
31566@subsubsection Building Resources
31567
31568
31569@geindex Resources
31570@geindex building
31571
31572A resource file is an ASCII file. By convention resource files have an
31573@code{.rc} extension.
31574The easiest way to build a resource file is to use Microsoft tools
31575such as @cite{imagedit.exe} to build bitmaps, icons and cursors and
31576@cite{dlgedit.exe} to build dialogs.
31577It is always possible to build an @code{.rc} file yourself by writing a
31578resource script.
31579
31580It is not our objective to explain how to write a resource file. A
31581complete description of the resource script language can be found in the
31582Microsoft documentation.
31583
31584@node Compiling Resources,Using Resources,Building Resources,GNAT and Windows Resources
31585@anchor{gnat_ugn/platform_specific_information compiling-resources}@anchor{29e}@anchor{gnat_ugn/platform_specific_information id35}@anchor{29f}
31586@subsubsection Compiling Resources
31587
31588
31589@geindex rc
31590
31591@geindex windres
31592
31593@geindex Resources
31594@geindex compiling
31595
31596This section describes how to build a GNAT-compatible (COFF) object file
31597containing the resources. This is done using the Resource Compiler
31598@cite{windres} as follows:
31599
31600@quotation
31601
31602@example
31603$ windres -i myres.rc -o myres.o
31604@end example
31605@end quotation
31606
31607By default @cite{windres} will run @emph{gcc} to preprocess the @code{.rc}
31608file. You can specify an alternate preprocessor (usually named
31609@code{cpp.exe}) using the @cite{windres} @emph{--preprocessor}
31610parameter. A list of all possible options may be obtained by entering
31611the command @cite{windres} @emph{--help}.
31612
31613It is also possible to use the Microsoft resource compiler @cite{rc.exe}
31614to produce a @code{.res} file (binary resource file). See the
31615corresponding Microsoft documentation for further details. In this case
31616you need to use @cite{windres} to translate the @code{.res} file to a
31617GNAT-compatible object file as follows:
31618
31619@quotation
31620
31621@example
31622$ windres -i myres.res -o myres.o
31623@end example
31624@end quotation
31625
31626@node Using Resources,,Compiling Resources,GNAT and Windows Resources
31627@anchor{gnat_ugn/platform_specific_information id36}@anchor{2a0}@anchor{gnat_ugn/platform_specific_information using-resources}@anchor{2a1}
31628@subsubsection Using Resources
31629
31630
31631@geindex Resources
31632@geindex using
31633
31634To include the resource file in your program just add the
31635GNAT-compatible object file for the resource(s) to the linker
31636arguments. With @emph{gnatmake} this is done by using the @emph{-largs}
31637option:
31638
31639@quotation
31640
31641@example
31642$ gnatmake myprog -largs myres.o
31643@end example
31644@end quotation
31645
31646@node Debugging a DLL,Setting Stack Size from gnatlink,GNAT and Windows Resources,Mixed-Language Programming on Windows
31647@anchor{gnat_ugn/platform_specific_information id37}@anchor{2a2}@anchor{gnat_ugn/platform_specific_information debugging-a-dll}@anchor{2a3}
31648@subsubsection Debugging a DLL
31649
31650
31651@geindex DLL debugging
31652
31653Debugging a DLL is similar to debugging a standard program. But
31654we have to deal with two different executable parts: the DLL and the
31655program that uses it. We have the following four possibilities:
31656
31657
31658@itemize *
31659
31660@item 
31661The program and the DLL are built with @cite{GCC/GNAT}.
31662
31663@item 
31664The program is built with foreign tools and the DLL is built with
31665@cite{GCC/GNAT}.
31666
31667@item 
31668The program is built with @cite{GCC/GNAT} and the DLL is built with
31669foreign tools.
31670@end itemize
31671
31672In this section we address only cases one and two above.
31673There is no point in trying to debug
31674a DLL with @cite{GNU/GDB}, if there is no GDB-compatible debugging
31675information in it. To do so you must use a debugger compatible with the
31676tools suite used to build the DLL.
31677
31678@menu
31679* Program and DLL Both Built with GCC/GNAT:: 
31680* Program Built with Foreign Tools and DLL Built with GCC/GNAT:: 
31681
31682@end menu
31683
31684@node Program and DLL Both Built with GCC/GNAT,Program Built with Foreign Tools and DLL Built with GCC/GNAT,,Debugging a DLL
31685@anchor{gnat_ugn/platform_specific_information program-and-dll-both-built-with-gcc-gnat}@anchor{2a4}@anchor{gnat_ugn/platform_specific_information id38}@anchor{2a5}
31686@subsubsection Program and DLL Both Built with GCC/GNAT
31687
31688
31689This is the simplest case. Both the DLL and the program have @cite{GDB}
31690compatible debugging information. It is then possible to break anywhere in
31691the process. Let's suppose here that the main procedure is named
31692@cite{ada_main} and that in the DLL there is an entry point named
31693@cite{ada_dll}.
31694
31695The DLL (@ref{27f,,Introduction to Dynamic Link Libraries (DLLs)}) and
31696program must have been built with the debugging information (see GNAT -g
31697switch). Here are the step-by-step instructions for debugging it:
31698
31699
31700@itemize *
31701
31702@item 
31703Launch @cite{GDB} on the main program.
31704
31705@example
31706$ gdb -nw ada_main
31707@end example
31708
31709@item 
31710Start the program and stop at the beginning of the main procedure
31711
31712@example
31713(gdb) start
31714@end example
31715
31716This step is required to be able to set a breakpoint inside the DLL. As long
31717as the program is not run, the DLL is not loaded. This has the
31718consequence that the DLL debugging information is also not loaded, so it is not
31719possible to set a breakpoint in the DLL.
31720
31721@item 
31722Set a breakpoint inside the DLL
31723
31724@example
31725(gdb) break ada_dll
31726(gdb) cont
31727@end example
31728@end itemize
31729
31730At this stage a breakpoint is set inside the DLL. From there on
31731you can use the standard approach to debug the whole program
31732(@ref{26,,Running and Debugging Ada Programs}).
31733
31734@node Program Built with Foreign Tools and DLL Built with GCC/GNAT,,Program and DLL Both Built with GCC/GNAT,Debugging a DLL
31735@anchor{gnat_ugn/platform_specific_information program-built-with-foreign-tools-and-dll-built-with-gcc-gnat}@anchor{2a6}@anchor{gnat_ugn/platform_specific_information id39}@anchor{2a7}
31736@subsubsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
31737
31738
31739In this case things are slightly more complex because it is not possible to
31740start the main program and then break at the beginning to load the DLL and the
31741associated DLL debugging information. It is not possible to break at the
31742beginning of the program because there is no @cite{GDB} debugging information,
31743and therefore there is no direct way of getting initial control. This
31744section addresses this issue by describing some methods that can be used
31745to break somewhere in the DLL to debug it.
31746
31747First suppose that the main procedure is named @cite{main} (this is for
31748example some C code built with Microsoft Visual C) and that there is a
31749DLL named @cite{test.dll} containing an Ada entry point named
31750@cite{ada_dll}.
31751
31752The DLL (see @ref{27f,,Introduction to Dynamic Link Libraries (DLLs)}) must have
31753been built with debugging information (see GNAT @cite{-g} option).
31754
31755@subsubheading Debugging the DLL Directly
31756
31757
31758
31759@itemize *
31760
31761@item 
31762Find out the executable starting address
31763
31764@example
31765$ objdump --file-header main.exe
31766@end example
31767
31768The starting address is reported on the last line. For example:
31769
31770@example
31771main.exe:     file format pei-i386
31772architecture: i386, flags 0x0000010a:
31773EXEC_P, HAS_DEBUG, D_PAGED
31774start address 0x00401010
31775@end example
31776
31777@item 
31778Launch the debugger on the executable.
31779
31780@example
31781$ gdb main.exe
31782@end example
31783
31784@item 
31785Set a breakpoint at the starting address, and launch the program.
31786
31787@example
31788$ (gdb) break *0x00401010
31789$ (gdb) run
31790@end example
31791
31792The program will stop at the given address.
31793
31794@item 
31795Set a breakpoint on a DLL subroutine.
31796
31797@example
31798(gdb) break ada_dll.adb:45
31799@end example
31800
31801Or if you want to break using a symbol on the DLL, you need first to
31802select the Ada language (language used by the DLL).
31803
31804@example
31805(gdb) set language ada
31806(gdb) break ada_dll
31807@end example
31808
31809@item 
31810Continue the program.
31811
31812@example
31813(gdb) cont
31814@end example
31815
31816This will run the program until it reaches the breakpoint that has been
31817set. From that point you can use the standard way to debug a program
31818as described in (@ref{26,,Running and Debugging Ada Programs}).
31819@end itemize
31820
31821It is also possible to debug the DLL by attaching to a running process.
31822
31823@subsubheading Attaching to a Running Process
31824
31825
31826@geindex DLL debugging
31827@geindex attach to process
31828
31829With @cite{GDB} it is always possible to debug a running process by
31830attaching to it. It is possible to debug a DLL this way. The limitation
31831of this approach is that the DLL must run long enough to perform the
31832attach operation. It may be useful for instance to insert a time wasting
31833loop in the code of the DLL to meet this criterion.
31834
31835
31836@itemize *
31837
31838@item 
31839Launch the main program @code{main.exe}.
31840
31841@example
31842$ main
31843@end example
31844
31845@item 
31846Use the Windows @emph{Task Manager} to find the process ID. Let's say
31847that the process PID for @code{main.exe} is 208.
31848
31849@item 
31850Launch gdb.
31851
31852@example
31853$ gdb
31854@end example
31855
31856@item 
31857Attach to the running process to be debugged.
31858
31859@example
31860(gdb) attach 208
31861@end example
31862
31863@item 
31864Load the process debugging information.
31865
31866@example
31867(gdb) symbol-file main.exe
31868@end example
31869
31870@item 
31871Break somewhere in the DLL.
31872
31873@example
31874(gdb) break ada_dll
31875@end example
31876
31877@item 
31878Continue process execution.
31879
31880@example
31881(gdb) cont
31882@end example
31883@end itemize
31884
31885This last step will resume the process execution, and stop at
31886the breakpoint we have set. From there you can use the standard
31887approach to debug a program as described in
31888@ref{26,,Running and Debugging Ada Programs}.
31889
31890@node Setting Stack Size from gnatlink,Setting Heap Size from gnatlink,Debugging a DLL,Mixed-Language Programming on Windows
31891@anchor{gnat_ugn/platform_specific_information setting-stack-size-from-gnatlink}@anchor{13a}@anchor{gnat_ugn/platform_specific_information id40}@anchor{2a8}
31892@subsubsection Setting Stack Size from @emph{gnatlink}
31893
31894
31895It is possible to specify the program stack size at link time. On modern
31896versions of Windows, starting with XP, this is mostly useful to set the size of
31897the main stack (environment task). The other task stacks are set with pragma
31898Storage_Size or with the @emph{gnatbind -d} command.
31899
31900Since older versions of Windows (2000, NT4, etc.) do not allow setting the
31901reserve size of individual tasks, the link-time stack size applies to all
31902tasks, and pragma Storage_Size has no effect.
31903In particular, Stack Overflow checks are made against this
31904link-time specified size.
31905
31906This setting can be done with @emph{gnatlink} using either of the following:
31907
31908
31909@itemize *
31910
31911@item 
31912@emph{-Xlinker} linker option
31913
31914@example
31915$ gnatlink hello -Xlinker --stack=0x10000,0x1000
31916@end example
31917
31918This sets the stack reserve size to 0x10000 bytes and the stack commit
31919size to 0x1000 bytes.
31920
31921@item 
31922@emph{-Wl} linker option
31923
31924@example
31925$ gnatlink hello -Wl,--stack=0x1000000
31926@end example
31927
31928This sets the stack reserve size to 0x1000000 bytes. Note that with
31929@emph{-Wl} option it is not possible to set the stack commit size
31930because the coma is a separator for this option.
31931@end itemize
31932
31933@node Setting Heap Size from gnatlink,,Setting Stack Size from gnatlink,Mixed-Language Programming on Windows
31934@anchor{gnat_ugn/platform_specific_information setting-heap-size-from-gnatlink}@anchor{13b}@anchor{gnat_ugn/platform_specific_information id41}@anchor{2a9}
31935@subsubsection Setting Heap Size from @emph{gnatlink}
31936
31937
31938Under Windows systems, it is possible to specify the program heap size from
31939@emph{gnatlink} using either of the following:
31940
31941
31942@itemize *
31943
31944@item 
31945@emph{-Xlinker} linker option
31946
31947@example
31948$ gnatlink hello -Xlinker --heap=0x10000,0x1000
31949@end example
31950
31951This sets the heap reserve size to 0x10000 bytes and the heap commit
31952size to 0x1000 bytes.
31953
31954@item 
31955@emph{-Wl} linker option
31956
31957@example
31958$ gnatlink hello -Wl,--heap=0x1000000
31959@end example
31960
31961This sets the heap reserve size to 0x1000000 bytes. Note that with
31962@emph{-Wl} option it is not possible to set the heap commit size
31963because the coma is a separator for this option.
31964@end itemize
31965
31966@node Mac OS Topics,,Microsoft Windows Topics,Platform-Specific Information
31967@anchor{gnat_ugn/platform_specific_information mac-os-topics}@anchor{2f}@anchor{gnat_ugn/platform_specific_information id42}@anchor{2aa}
31968@section Mac OS Topics
31969
31970
31971@geindex OS X
31972
31973This section describes topics that are specific to Apple's OS X
31974platform.
31975
31976@menu
31977* Codesigning the Debugger:: 
31978
31979@end menu
31980
31981@node Codesigning the Debugger,,,Mac OS Topics
31982@anchor{gnat_ugn/platform_specific_information codesigning-the-debugger}@anchor{2ab}
31983@subsection Codesigning the Debugger
31984
31985
31986The Darwin Kernel requires the debugger to have special permissions
31987before it is allowed to control other processes. These permissions
31988are granted by codesigning the GDB executable. Without these
31989permissions, the debugger will report error messages such as:
31990
31991@example
31992Starting program: /x/y/foo
31993Unable to find Mach task port for process-id 28885: (os/kern) failure (0x5).
31994(please check gdb is codesigned - see taskgated(8))
31995@end example
31996
31997Codesigning requires a certificate.  The following procedure explains
31998how to create one:
31999
32000
32001@itemize *
32002
32003@item 
32004Start the Keychain Access application (in
32005/Applications/Utilities/Keychain Access.app)
32006
32007@item 
32008Select the Keychain Access -> Certificate Assistant ->
32009Create a Certificate... menu
32010
32011@item 
32012Then:
32013
32014
32015@itemize *
32016
32017@item 
32018Choose a name for the new certificate (this procedure will use
32019"gdb-cert" as an example)
32020
32021@item 
32022Set "Identity Type" to "Self Signed Root"
32023
32024@item 
32025Set "Certificate Type" to "Code Signing"
32026
32027@item 
32028Activate the "Let me override defaults" option
32029@end itemize
32030
32031@item 
32032Click several times on "Continue" until the "Specify a Location
32033For The Certificate" screen appears, then set "Keychain" to "System"
32034
32035@item 
32036Click on "Continue" until the certificate is created
32037
32038@item 
32039Finally, in the view, double-click on the new certificate,
32040and set "When using this certificate" to "Always Trust"
32041
32042@item 
32043Exit the Keychain Access application and restart the computer
32044(this is unfortunately required)
32045@end itemize
32046
32047Once a certificate has been created, the debugger can be codesigned
32048as follow. In a Terminal, run the following command:
32049
32050@quotation
32051
32052@example
32053$ codesign -f -s  "gdb-cert"  <gnat_install_prefix>/bin/gdb
32054@end example
32055@end quotation
32056
32057where "gdb-cert" should be replaced by the actual certificate
32058name chosen above, and <gnat_install_prefix> should be replaced by
32059the location where you installed GNAT.  Also, be sure that users are
32060in the Unix group @code{_developer}.
32061
32062@node Example of Binder Output File,Elaboration Order Handling in GNAT,Platform-Specific Information,Top
32063@anchor{gnat_ugn/example_of_binder_output example-of-binder-output-file}@anchor{10}@anchor{gnat_ugn/example_of_binder_output doc}@anchor{2ac}@anchor{gnat_ugn/example_of_binder_output id1}@anchor{2ad}
32064@chapter Example of Binder Output File
32065
32066
32067@geindex Binder output (example)
32068
32069This Appendix displays the source code for the output file
32070generated by @emph{gnatbind} for a simple 'Hello World' program.
32071Comments have been added for clarification purposes.
32072
32073@example
32074--  The package is called Ada_Main unless this name is actually used
32075--  as a unit name in the partition, in which case some other unique
32076--  name is used.
32077
32078pragma Ada_95;
32079with System;
32080package ada_main is
32081   pragma Warnings (Off);
32082
32083   --  The main program saves the parameters (argument count,
32084   --  argument values, environment pointer) in global variables
32085   --  for later access by other units including
32086   --  Ada.Command_Line.
32087
32088   gnat_argc : Integer;
32089   gnat_argv : System.Address;
32090   gnat_envp : System.Address;
32091
32092   --  The actual variables are stored in a library routine. This
32093   --  is useful for some shared library situations, where there
32094   --  are problems if variables are not in the library.
32095
32096   pragma Import (C, gnat_argc);
32097   pragma Import (C, gnat_argv);
32098   pragma Import (C, gnat_envp);
32099
32100   --  The exit status is similarly an external location
32101
32102   gnat_exit_status : Integer;
32103   pragma Import (C, gnat_exit_status);
32104
32105   GNAT_Version : constant String :=
32106                    "GNAT Version: Pro 7.4.0w (20141119-49)" & ASCII.NUL;
32107   pragma Export (C, GNAT_Version, "__gnat_version");
32108
32109   Ada_Main_Program_Name : constant String := "_ada_hello" & ASCII.NUL;
32110   pragma Export (C, Ada_Main_Program_Name, "__gnat_ada_main_program_name");
32111
32112   --  This is the generated adainit routine that performs
32113   --  initialization at the start of execution. In the case
32114   --  where Ada is the main program, this main program makes
32115   --  a call to adainit at program startup.
32116
32117   procedure adainit;
32118   pragma Export (C, adainit, "adainit");
32119
32120   --  This is the generated adafinal routine that performs
32121   --  finalization at the end of execution. In the case where
32122   --  Ada is the main program, this main program makes a call
32123   --  to adafinal at program termination.
32124
32125   procedure adafinal;
32126   pragma Export (C, adafinal, "adafinal");
32127
32128   --  This routine is called at the start of execution. It is
32129   --  a dummy routine that is used by the debugger to breakpoint
32130   --  at the start of execution.
32131
32132   --  This is the actual generated main program (it would be
32133   --  suppressed if the no main program switch were used). As
32134   --  required by standard system conventions, this program has
32135   --  the external name main.
32136
32137   function main
32138     (argc : Integer;
32139      argv : System.Address;
32140      envp : System.Address)
32141      return Integer;
32142   pragma Export (C, main, "main");
32143
32144   --  The following set of constants give the version
32145   --  identification values for every unit in the bound
32146   --  partition. This identification is computed from all
32147   --  dependent semantic units, and corresponds to the
32148   --  string that would be returned by use of the
32149   --  Body_Version or Version attributes.
32150
32151   --  The following Export pragmas export the version numbers
32152   --  with symbolic names ending in B (for body) or S
32153   --  (for spec) so that they can be located in a link. The
32154   --  information provided here is sufficient to track down
32155   --  the exact versions of units used in a given build.
32156
32157   type Version_32 is mod 2 ** 32;
32158   u00001 : constant Version_32 := 16#8ad6e54a#;
32159   pragma Export (C, u00001, "helloB");
32160   u00002 : constant Version_32 := 16#fbff4c67#;
32161   pragma Export (C, u00002, "system__standard_libraryB");
32162   u00003 : constant Version_32 := 16#1ec6fd90#;
32163   pragma Export (C, u00003, "system__standard_libraryS");
32164   u00004 : constant Version_32 := 16#3ffc8e18#;
32165   pragma Export (C, u00004, "adaS");
32166   u00005 : constant Version_32 := 16#28f088c2#;
32167   pragma Export (C, u00005, "ada__text_ioB");
32168   u00006 : constant Version_32 := 16#f372c8ac#;
32169   pragma Export (C, u00006, "ada__text_ioS");
32170   u00007 : constant Version_32 := 16#2c143749#;
32171   pragma Export (C, u00007, "ada__exceptionsB");
32172   u00008 : constant Version_32 := 16#f4f0cce8#;
32173   pragma Export (C, u00008, "ada__exceptionsS");
32174   u00009 : constant Version_32 := 16#a46739c0#;
32175   pragma Export (C, u00009, "ada__exceptions__last_chance_handlerB");
32176   u00010 : constant Version_32 := 16#3aac8c92#;
32177   pragma Export (C, u00010, "ada__exceptions__last_chance_handlerS");
32178   u00011 : constant Version_32 := 16#1d274481#;
32179   pragma Export (C, u00011, "systemS");
32180   u00012 : constant Version_32 := 16#a207fefe#;
32181   pragma Export (C, u00012, "system__soft_linksB");
32182   u00013 : constant Version_32 := 16#467d9556#;
32183   pragma Export (C, u00013, "system__soft_linksS");
32184   u00014 : constant Version_32 := 16#b01dad17#;
32185   pragma Export (C, u00014, "system__parametersB");
32186   u00015 : constant Version_32 := 16#630d49fe#;
32187   pragma Export (C, u00015, "system__parametersS");
32188   u00016 : constant Version_32 := 16#b19b6653#;
32189   pragma Export (C, u00016, "system__secondary_stackB");
32190   u00017 : constant Version_32 := 16#b6468be8#;
32191   pragma Export (C, u00017, "system__secondary_stackS");
32192   u00018 : constant Version_32 := 16#39a03df9#;
32193   pragma Export (C, u00018, "system__storage_elementsB");
32194   u00019 : constant Version_32 := 16#30e40e85#;
32195   pragma Export (C, u00019, "system__storage_elementsS");
32196   u00020 : constant Version_32 := 16#41837d1e#;
32197   pragma Export (C, u00020, "system__stack_checkingB");
32198   u00021 : constant Version_32 := 16#93982f69#;
32199   pragma Export (C, u00021, "system__stack_checkingS");
32200   u00022 : constant Version_32 := 16#393398c1#;
32201   pragma Export (C, u00022, "system__exception_tableB");
32202   u00023 : constant Version_32 := 16#b33e2294#;
32203   pragma Export (C, u00023, "system__exception_tableS");
32204   u00024 : constant Version_32 := 16#ce4af020#;
32205   pragma Export (C, u00024, "system__exceptionsB");
32206   u00025 : constant Version_32 := 16#75442977#;
32207   pragma Export (C, u00025, "system__exceptionsS");
32208   u00026 : constant Version_32 := 16#37d758f1#;
32209   pragma Export (C, u00026, "system__exceptions__machineS");
32210   u00027 : constant Version_32 := 16#b895431d#;
32211   pragma Export (C, u00027, "system__exceptions_debugB");
32212   u00028 : constant Version_32 := 16#aec55d3f#;
32213   pragma Export (C, u00028, "system__exceptions_debugS");
32214   u00029 : constant Version_32 := 16#570325c8#;
32215   pragma Export (C, u00029, "system__img_intB");
32216   u00030 : constant Version_32 := 16#1ffca443#;
32217   pragma Export (C, u00030, "system__img_intS");
32218   u00031 : constant Version_32 := 16#b98c3e16#;
32219   pragma Export (C, u00031, "system__tracebackB");
32220   u00032 : constant Version_32 := 16#831a9d5a#;
32221   pragma Export (C, u00032, "system__tracebackS");
32222   u00033 : constant Version_32 := 16#9ed49525#;
32223   pragma Export (C, u00033, "system__traceback_entriesB");
32224   u00034 : constant Version_32 := 16#1d7cb2f1#;
32225   pragma Export (C, u00034, "system__traceback_entriesS");
32226   u00035 : constant Version_32 := 16#8c33a517#;
32227   pragma Export (C, u00035, "system__wch_conB");
32228   u00036 : constant Version_32 := 16#065a6653#;
32229   pragma Export (C, u00036, "system__wch_conS");
32230   u00037 : constant Version_32 := 16#9721e840#;
32231   pragma Export (C, u00037, "system__wch_stwB");
32232   u00038 : constant Version_32 := 16#2b4b4a52#;
32233   pragma Export (C, u00038, "system__wch_stwS");
32234   u00039 : constant Version_32 := 16#92b797cb#;
32235   pragma Export (C, u00039, "system__wch_cnvB");
32236   u00040 : constant Version_32 := 16#09eddca0#;
32237   pragma Export (C, u00040, "system__wch_cnvS");
32238   u00041 : constant Version_32 := 16#6033a23f#;
32239   pragma Export (C, u00041, "interfacesS");
32240   u00042 : constant Version_32 := 16#ece6fdb6#;
32241   pragma Export (C, u00042, "system__wch_jisB");
32242   u00043 : constant Version_32 := 16#899dc581#;
32243   pragma Export (C, u00043, "system__wch_jisS");
32244   u00044 : constant Version_32 := 16#10558b11#;
32245   pragma Export (C, u00044, "ada__streamsB");
32246   u00045 : constant Version_32 := 16#2e6701ab#;
32247   pragma Export (C, u00045, "ada__streamsS");
32248   u00046 : constant Version_32 := 16#db5c917c#;
32249   pragma Export (C, u00046, "ada__io_exceptionsS");
32250   u00047 : constant Version_32 := 16#12c8cd7d#;
32251   pragma Export (C, u00047, "ada__tagsB");
32252   u00048 : constant Version_32 := 16#ce72c228#;
32253   pragma Export (C, u00048, "ada__tagsS");
32254   u00049 : constant Version_32 := 16#c3335bfd#;
32255   pragma Export (C, u00049, "system__htableB");
32256   u00050 : constant Version_32 := 16#99e5f76b#;
32257   pragma Export (C, u00050, "system__htableS");
32258   u00051 : constant Version_32 := 16#089f5cd0#;
32259   pragma Export (C, u00051, "system__string_hashB");
32260   u00052 : constant Version_32 := 16#3bbb9c15#;
32261   pragma Export (C, u00052, "system__string_hashS");
32262   u00053 : constant Version_32 := 16#807fe041#;
32263   pragma Export (C, u00053, "system__unsigned_typesS");
32264   u00054 : constant Version_32 := 16#d27be59e#;
32265   pragma Export (C, u00054, "system__val_lluB");
32266   u00055 : constant Version_32 := 16#fa8db733#;
32267   pragma Export (C, u00055, "system__val_lluS");
32268   u00056 : constant Version_32 := 16#27b600b2#;
32269   pragma Export (C, u00056, "system__val_utilB");
32270   u00057 : constant Version_32 := 16#b187f27f#;
32271   pragma Export (C, u00057, "system__val_utilS");
32272   u00058 : constant Version_32 := 16#d1060688#;
32273   pragma Export (C, u00058, "system__case_utilB");
32274   u00059 : constant Version_32 := 16#392e2d56#;
32275   pragma Export (C, u00059, "system__case_utilS");
32276   u00060 : constant Version_32 := 16#84a27f0d#;
32277   pragma Export (C, u00060, "interfaces__c_streamsB");
32278   u00061 : constant Version_32 := 16#8bb5f2c0#;
32279   pragma Export (C, u00061, "interfaces__c_streamsS");
32280   u00062 : constant Version_32 := 16#6db6928f#;
32281   pragma Export (C, u00062, "system__crtlS");
32282   u00063 : constant Version_32 := 16#4e6a342b#;
32283   pragma Export (C, u00063, "system__file_ioB");
32284   u00064 : constant Version_32 := 16#ba56a5e4#;
32285   pragma Export (C, u00064, "system__file_ioS");
32286   u00065 : constant Version_32 := 16#b7ab275c#;
32287   pragma Export (C, u00065, "ada__finalizationB");
32288   u00066 : constant Version_32 := 16#19f764ca#;
32289   pragma Export (C, u00066, "ada__finalizationS");
32290   u00067 : constant Version_32 := 16#95817ed8#;
32291   pragma Export (C, u00067, "system__finalization_rootB");
32292   u00068 : constant Version_32 := 16#52d53711#;
32293   pragma Export (C, u00068, "system__finalization_rootS");
32294   u00069 : constant Version_32 := 16#769e25e6#;
32295   pragma Export (C, u00069, "interfaces__cB");
32296   u00070 : constant Version_32 := 16#4a38bedb#;
32297   pragma Export (C, u00070, "interfaces__cS");
32298   u00071 : constant Version_32 := 16#07e6ee66#;
32299   pragma Export (C, u00071, "system__os_libB");
32300   u00072 : constant Version_32 := 16#d7b69782#;
32301   pragma Export (C, u00072, "system__os_libS");
32302   u00073 : constant Version_32 := 16#1a817b8e#;
32303   pragma Export (C, u00073, "system__stringsB");
32304   u00074 : constant Version_32 := 16#639855e7#;
32305   pragma Export (C, u00074, "system__stringsS");
32306   u00075 : constant Version_32 := 16#e0b8de29#;
32307   pragma Export (C, u00075, "system__file_control_blockS");
32308   u00076 : constant Version_32 := 16#b5b2aca1#;
32309   pragma Export (C, u00076, "system__finalization_mastersB");
32310   u00077 : constant Version_32 := 16#69316dc1#;
32311   pragma Export (C, u00077, "system__finalization_mastersS");
32312   u00078 : constant Version_32 := 16#57a37a42#;
32313   pragma Export (C, u00078, "system__address_imageB");
32314   u00079 : constant Version_32 := 16#bccbd9bb#;
32315   pragma Export (C, u00079, "system__address_imageS");
32316   u00080 : constant Version_32 := 16#7268f812#;
32317   pragma Export (C, u00080, "system__img_boolB");
32318   u00081 : constant Version_32 := 16#e8fe356a#;
32319   pragma Export (C, u00081, "system__img_boolS");
32320   u00082 : constant Version_32 := 16#d7aac20c#;
32321   pragma Export (C, u00082, "system__ioB");
32322   u00083 : constant Version_32 := 16#8365b3ce#;
32323   pragma Export (C, u00083, "system__ioS");
32324   u00084 : constant Version_32 := 16#6d4d969a#;
32325   pragma Export (C, u00084, "system__storage_poolsB");
32326   u00085 : constant Version_32 := 16#e87cc305#;
32327   pragma Export (C, u00085, "system__storage_poolsS");
32328   u00086 : constant Version_32 := 16#e34550ca#;
32329   pragma Export (C, u00086, "system__pool_globalB");
32330   u00087 : constant Version_32 := 16#c88d2d16#;
32331   pragma Export (C, u00087, "system__pool_globalS");
32332   u00088 : constant Version_32 := 16#9d39c675#;
32333   pragma Export (C, u00088, "system__memoryB");
32334   u00089 : constant Version_32 := 16#445a22b5#;
32335   pragma Export (C, u00089, "system__memoryS");
32336   u00090 : constant Version_32 := 16#6a859064#;
32337   pragma Export (C, u00090, "system__storage_pools__subpoolsB");
32338   u00091 : constant Version_32 := 16#e3b008dc#;
32339   pragma Export (C, u00091, "system__storage_pools__subpoolsS");
32340   u00092 : constant Version_32 := 16#63f11652#;
32341   pragma Export (C, u00092, "system__storage_pools__subpools__finalizationB");
32342   u00093 : constant Version_32 := 16#fe2f4b3a#;
32343   pragma Export (C, u00093, "system__storage_pools__subpools__finalizationS");
32344
32345   --  BEGIN ELABORATION ORDER
32346   --  ada%s
32347   --  interfaces%s
32348   --  system%s
32349   --  system.case_util%s
32350   --  system.case_util%b
32351   --  system.htable%s
32352   --  system.img_bool%s
32353   --  system.img_bool%b
32354   --  system.img_int%s
32355   --  system.img_int%b
32356   --  system.io%s
32357   --  system.io%b
32358   --  system.parameters%s
32359   --  system.parameters%b
32360   --  system.crtl%s
32361   --  interfaces.c_streams%s
32362   --  interfaces.c_streams%b
32363   --  system.standard_library%s
32364   --  system.exceptions_debug%s
32365   --  system.exceptions_debug%b
32366   --  system.storage_elements%s
32367   --  system.storage_elements%b
32368   --  system.stack_checking%s
32369   --  system.stack_checking%b
32370   --  system.string_hash%s
32371   --  system.string_hash%b
32372   --  system.htable%b
32373   --  system.strings%s
32374   --  system.strings%b
32375   --  system.os_lib%s
32376   --  system.traceback_entries%s
32377   --  system.traceback_entries%b
32378   --  ada.exceptions%s
32379   --  system.soft_links%s
32380   --  system.unsigned_types%s
32381   --  system.val_llu%s
32382   --  system.val_util%s
32383   --  system.val_util%b
32384   --  system.val_llu%b
32385   --  system.wch_con%s
32386   --  system.wch_con%b
32387   --  system.wch_cnv%s
32388   --  system.wch_jis%s
32389   --  system.wch_jis%b
32390   --  system.wch_cnv%b
32391   --  system.wch_stw%s
32392   --  system.wch_stw%b
32393   --  ada.exceptions.last_chance_handler%s
32394   --  ada.exceptions.last_chance_handler%b
32395   --  system.address_image%s
32396   --  system.exception_table%s
32397   --  system.exception_table%b
32398   --  ada.io_exceptions%s
32399   --  ada.tags%s
32400   --  ada.streams%s
32401   --  ada.streams%b
32402   --  interfaces.c%s
32403   --  system.exceptions%s
32404   --  system.exceptions%b
32405   --  system.exceptions.machine%s
32406   --  system.finalization_root%s
32407   --  system.finalization_root%b
32408   --  ada.finalization%s
32409   --  ada.finalization%b
32410   --  system.storage_pools%s
32411   --  system.storage_pools%b
32412   --  system.finalization_masters%s
32413   --  system.storage_pools.subpools%s
32414   --  system.storage_pools.subpools.finalization%s
32415   --  system.storage_pools.subpools.finalization%b
32416   --  system.memory%s
32417   --  system.memory%b
32418   --  system.standard_library%b
32419   --  system.pool_global%s
32420   --  system.pool_global%b
32421   --  system.file_control_block%s
32422   --  system.file_io%s
32423   --  system.secondary_stack%s
32424   --  system.file_io%b
32425   --  system.storage_pools.subpools%b
32426   --  system.finalization_masters%b
32427   --  interfaces.c%b
32428   --  ada.tags%b
32429   --  system.soft_links%b
32430   --  system.os_lib%b
32431   --  system.secondary_stack%b
32432   --  system.address_image%b
32433   --  system.traceback%s
32434   --  ada.exceptions%b
32435   --  system.traceback%b
32436   --  ada.text_io%s
32437   --  ada.text_io%b
32438   --  hello%b
32439   --  END ELABORATION ORDER
32440
32441end ada_main;
32442@end example
32443
32444@example
32445pragma Ada_95;
32446--  The following source file name pragmas allow the generated file
32447--  names to be unique for different main programs. They are needed
32448--  since the package name will always be Ada_Main.
32449
32450pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
32451pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
32452
32453pragma Suppress (Overflow_Check);
32454with Ada.Exceptions;
32455
32456--  Generated package body for Ada_Main starts here
32457
32458package body ada_main is
32459   pragma Warnings (Off);
32460
32461   --  These values are reference counter associated to units which have
32462   --  been elaborated. It is also used to avoid elaborating the
32463   --  same unit twice.
32464
32465   E72 : Short_Integer; pragma Import (Ada, E72, "system__os_lib_E");
32466   E13 : Short_Integer; pragma Import (Ada, E13, "system__soft_links_E");
32467   E23 : Short_Integer; pragma Import (Ada, E23, "system__exception_table_E");
32468   E46 : Short_Integer; pragma Import (Ada, E46, "ada__io_exceptions_E");
32469   E48 : Short_Integer; pragma Import (Ada, E48, "ada__tags_E");
32470   E45 : Short_Integer; pragma Import (Ada, E45, "ada__streams_E");
32471   E70 : Short_Integer; pragma Import (Ada, E70, "interfaces__c_E");
32472   E25 : Short_Integer; pragma Import (Ada, E25, "system__exceptions_E");
32473   E68 : Short_Integer; pragma Import (Ada, E68, "system__finalization_root_E");
32474   E66 : Short_Integer; pragma Import (Ada, E66, "ada__finalization_E");
32475   E85 : Short_Integer; pragma Import (Ada, E85, "system__storage_pools_E");
32476   E77 : Short_Integer; pragma Import (Ada, E77, "system__finalization_masters_E");
32477   E91 : Short_Integer; pragma Import (Ada, E91, "system__storage_pools__subpools_E");
32478   E87 : Short_Integer; pragma Import (Ada, E87, "system__pool_global_E");
32479   E75 : Short_Integer; pragma Import (Ada, E75, "system__file_control_block_E");
32480   E64 : Short_Integer; pragma Import (Ada, E64, "system__file_io_E");
32481   E17 : Short_Integer; pragma Import (Ada, E17, "system__secondary_stack_E");
32482   E06 : Short_Integer; pragma Import (Ada, E06, "ada__text_io_E");
32483
32484   Local_Priority_Specific_Dispatching : constant String := "";
32485   Local_Interrupt_States : constant String := "";
32486
32487   Is_Elaborated : Boolean := False;
32488
32489   procedure finalize_library is
32490   begin
32491      E06 := E06 - 1;
32492      declare
32493         procedure F1;
32494         pragma Import (Ada, F1, "ada__text_io__finalize_spec");
32495      begin
32496         F1;
32497      end;
32498      E77 := E77 - 1;
32499      E91 := E91 - 1;
32500      declare
32501         procedure F2;
32502         pragma Import (Ada, F2, "system__file_io__finalize_body");
32503      begin
32504         E64 := E64 - 1;
32505         F2;
32506      end;
32507      declare
32508         procedure F3;
32509         pragma Import (Ada, F3, "system__file_control_block__finalize_spec");
32510      begin
32511         E75 := E75 - 1;
32512         F3;
32513      end;
32514      E87 := E87 - 1;
32515      declare
32516         procedure F4;
32517         pragma Import (Ada, F4, "system__pool_global__finalize_spec");
32518      begin
32519         F4;
32520      end;
32521      declare
32522         procedure F5;
32523         pragma Import (Ada, F5, "system__storage_pools__subpools__finalize_spec");
32524      begin
32525         F5;
32526      end;
32527      declare
32528         procedure F6;
32529         pragma Import (Ada, F6, "system__finalization_masters__finalize_spec");
32530      begin
32531         F6;
32532      end;
32533      declare
32534         procedure Reraise_Library_Exception_If_Any;
32535         pragma Import (Ada, Reraise_Library_Exception_If_Any, "__gnat_reraise_library_exception_if_any");
32536      begin
32537         Reraise_Library_Exception_If_Any;
32538      end;
32539   end finalize_library;
32540
32541   -------------
32542   -- adainit --
32543   -------------
32544
32545   procedure adainit is
32546
32547      Main_Priority : Integer;
32548      pragma Import (C, Main_Priority, "__gl_main_priority");
32549      Time_Slice_Value : Integer;
32550      pragma Import (C, Time_Slice_Value, "__gl_time_slice_val");
32551      WC_Encoding : Character;
32552      pragma Import (C, WC_Encoding, "__gl_wc_encoding");
32553      Locking_Policy : Character;
32554      pragma Import (C, Locking_Policy, "__gl_locking_policy");
32555      Queuing_Policy : Character;
32556      pragma Import (C, Queuing_Policy, "__gl_queuing_policy");
32557      Task_Dispatching_Policy : Character;
32558      pragma Import (C, Task_Dispatching_Policy, "__gl_task_dispatching_policy");
32559      Priority_Specific_Dispatching : System.Address;
32560      pragma Import (C, Priority_Specific_Dispatching, "__gl_priority_specific_dispatching");
32561      Num_Specific_Dispatching : Integer;
32562      pragma Import (C, Num_Specific_Dispatching, "__gl_num_specific_dispatching");
32563      Main_CPU : Integer;
32564      pragma Import (C, Main_CPU, "__gl_main_cpu");
32565      Interrupt_States : System.Address;
32566      pragma Import (C, Interrupt_States, "__gl_interrupt_states");
32567      Num_Interrupt_States : Integer;
32568      pragma Import (C, Num_Interrupt_States, "__gl_num_interrupt_states");
32569      Unreserve_All_Interrupts : Integer;
32570      pragma Import (C, Unreserve_All_Interrupts, "__gl_unreserve_all_interrupts");
32571      Detect_Blocking : Integer;
32572      pragma Import (C, Detect_Blocking, "__gl_detect_blocking");
32573      Default_Stack_Size : Integer;
32574      pragma Import (C, Default_Stack_Size, "__gl_default_stack_size");
32575      Leap_Seconds_Support : Integer;
32576      pragma Import (C, Leap_Seconds_Support, "__gl_leap_seconds_support");
32577
32578      procedure Runtime_Initialize;
32579      pragma Import (C, Runtime_Initialize, "__gnat_runtime_initialize");
32580
32581      Finalize_Library_Objects : No_Param_Proc;
32582      pragma Import (C, Finalize_Library_Objects, "__gnat_finalize_library_objects");
32583
32584   --  Start of processing for adainit
32585
32586   begin
32587
32588      --  Record various information for this partition.  The values
32589      --  are derived by the binder from information stored in the ali
32590      --  files by the compiler.
32591
32592      if Is_Elaborated then
32593         return;
32594      end if;
32595      Is_Elaborated := True;
32596      Main_Priority := -1;
32597      Time_Slice_Value := -1;
32598      WC_Encoding := 'b';
32599      Locking_Policy := ' ';
32600      Queuing_Policy := ' ';
32601      Task_Dispatching_Policy := ' ';
32602      Priority_Specific_Dispatching :=
32603        Local_Priority_Specific_Dispatching'Address;
32604      Num_Specific_Dispatching := 0;
32605      Main_CPU := -1;
32606      Interrupt_States := Local_Interrupt_States'Address;
32607      Num_Interrupt_States := 0;
32608      Unreserve_All_Interrupts := 0;
32609      Detect_Blocking := 0;
32610      Default_Stack_Size := -1;
32611      Leap_Seconds_Support := 0;
32612
32613      Runtime_Initialize;
32614
32615      Finalize_Library_Objects := finalize_library'access;
32616
32617      --  Now we have the elaboration calls for all units in the partition.
32618      --  The Elab_Spec and Elab_Body attributes generate references to the
32619      --  implicit elaboration procedures generated by the compiler for
32620      --  each unit that requires elaboration. Increment a counter of
32621      --  reference for each unit.
32622
32623      System.Soft_Links'Elab_Spec;
32624      System.Exception_Table'Elab_Body;
32625      E23 := E23 + 1;
32626      Ada.Io_Exceptions'Elab_Spec;
32627      E46 := E46 + 1;
32628      Ada.Tags'Elab_Spec;
32629      Ada.Streams'Elab_Spec;
32630      E45 := E45 + 1;
32631      Interfaces.C'Elab_Spec;
32632      System.Exceptions'Elab_Spec;
32633      E25 := E25 + 1;
32634      System.Finalization_Root'Elab_Spec;
32635      E68 := E68 + 1;
32636      Ada.Finalization'Elab_Spec;
32637      E66 := E66 + 1;
32638      System.Storage_Pools'Elab_Spec;
32639      E85 := E85 + 1;
32640      System.Finalization_Masters'Elab_Spec;
32641      System.Storage_Pools.Subpools'Elab_Spec;
32642      System.Pool_Global'Elab_Spec;
32643      E87 := E87 + 1;
32644      System.File_Control_Block'Elab_Spec;
32645      E75 := E75 + 1;
32646      System.File_Io'Elab_Body;
32647      E64 := E64 + 1;
32648      E91 := E91 + 1;
32649      System.Finalization_Masters'Elab_Body;
32650      E77 := E77 + 1;
32651      E70 := E70 + 1;
32652      Ada.Tags'Elab_Body;
32653      E48 := E48 + 1;
32654      System.Soft_Links'Elab_Body;
32655      E13 := E13 + 1;
32656      System.Os_Lib'Elab_Body;
32657      E72 := E72 + 1;
32658      System.Secondary_Stack'Elab_Body;
32659      E17 := E17 + 1;
32660      Ada.Text_Io'Elab_Spec;
32661      Ada.Text_Io'Elab_Body;
32662      E06 := E06 + 1;
32663   end adainit;
32664
32665   --------------
32666   -- adafinal --
32667   --------------
32668
32669   procedure adafinal is
32670      procedure s_stalib_adafinal;
32671      pragma Import (C, s_stalib_adafinal, "system__standard_library__adafinal");
32672
32673      procedure Runtime_Finalize;
32674      pragma Import (C, Runtime_Finalize, "__gnat_runtime_finalize");
32675
32676   begin
32677      if not Is_Elaborated then
32678         return;
32679      end if;
32680      Is_Elaborated := False;
32681      Runtime_Finalize;
32682      s_stalib_adafinal;
32683   end adafinal;
32684
32685   --  We get to the main program of the partition by using
32686   --  pragma Import because if we try to with the unit and
32687   --  call it Ada style, then not only do we waste time
32688   --  recompiling it, but also, we don't really know the right
32689   --  switches (e.g.@@: identifier character set) to be used
32690   --  to compile it.
32691
32692   procedure Ada_Main_Program;
32693   pragma Import (Ada, Ada_Main_Program, "_ada_hello");
32694
32695   ----------
32696   -- main --
32697   ----------
32698
32699   --  main is actually a function, as in the ANSI C standard,
32700   --  defined to return the exit status. The three parameters
32701   --  are the argument count, argument values and environment
32702   --  pointer.
32703
32704   function main
32705     (argc : Integer;
32706      argv : System.Address;
32707      envp : System.Address)
32708      return Integer
32709   is
32710      --  The initialize routine performs low level system
32711      --  initialization using a standard library routine which
32712      --  sets up signal handling and performs any other
32713      --  required setup. The routine can be found in file
32714      --  a-init.c.
32715
32716      procedure initialize;
32717      pragma Import (C, initialize, "__gnat_initialize");
32718
32719      --  The finalize routine performs low level system
32720      --  finalization using a standard library routine. The
32721      --  routine is found in file a-final.c and in the standard
32722      --  distribution is a dummy routine that does nothing, so
32723      --  really this is a hook for special user finalization.
32724
32725      procedure finalize;
32726      pragma Import (C, finalize, "__gnat_finalize");
32727
32728      --  The following is to initialize the SEH exceptions
32729
32730      SEH : aliased array (1 .. 2) of Integer;
32731
32732      Ensure_Reference : aliased System.Address := Ada_Main_Program_Name'Address;
32733      pragma Volatile (Ensure_Reference);
32734
32735   --  Start of processing for main
32736
32737   begin
32738      --  Save global variables
32739
32740      gnat_argc := argc;
32741      gnat_argv := argv;
32742      gnat_envp := envp;
32743
32744      --  Call low level system initialization
32745
32746      Initialize (SEH'Address);
32747
32748      --  Call our generated Ada initialization routine
32749
32750      adainit;
32751
32752      --  Now we call the main program of the partition
32753
32754      Ada_Main_Program;
32755
32756      --  Perform Ada finalization
32757
32758      adafinal;
32759
32760      --  Perform low level system finalization
32761
32762      Finalize;
32763
32764      --  Return the proper exit status
32765      return (gnat_exit_status);
32766   end;
32767
32768--  This section is entirely comments, so it has no effect on the
32769--  compilation of the Ada_Main package. It provides the list of
32770--  object files and linker options, as well as some standard
32771--  libraries needed for the link. The gnatlink utility parses
32772--  this b~hello.adb file to read these comment lines to generate
32773--  the appropriate command line arguments for the call to the
32774--  system linker. The BEGIN/END lines are used for sentinels for
32775--  this parsing operation.
32776
32777--  The exact file names will of course depend on the environment,
32778--  host/target and location of files on the host system.
32779
32780-- BEGIN Object file/option list
32781   --   ./hello.o
32782   --   -L./
32783   --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
32784   --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
32785-- END Object file/option list
32786
32787end ada_main;
32788@end example
32789
32790The Ada code in the above example is exactly what is generated by the
32791binder. We have added comments to more clearly indicate the function
32792of each part of the generated @cite{Ada_Main} package.
32793
32794The code is standard Ada in all respects, and can be processed by any
32795tools that handle Ada. In particular, it is possible to use the debugger
32796in Ada mode to debug the generated @cite{Ada_Main} package. For example,
32797suppose that for reasons that you do not understand, your program is crashing
32798during elaboration of the body of @cite{Ada.Text_IO}. To locate this bug,
32799you can place a breakpoint on the call:
32800
32801@quotation
32802
32803@example
32804Ada.Text_Io'Elab_Body;
32805@end example
32806@end quotation
32807
32808and trace the elaboration routine for this package to find out where
32809the problem might be (more usually of course you would be debugging
32810elaboration code in your own application).
32811
32812@c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
32813
32814@node Elaboration Order Handling in GNAT,Inline Assembler,Example of Binder Output File,Top
32815@anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-order-handling-in-gnat}@anchor{11}@anchor{gnat_ugn/elaboration_order_handling_in_gnat doc}@anchor{2ae}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id1}@anchor{2af}
32816@chapter Elaboration Order Handling in GNAT
32817
32818
32819@geindex Order of elaboration
32820
32821@geindex Elaboration control
32822
32823This appendix describes the handling of elaboration code in Ada and
32824in GNAT, and discusses how the order of elaboration of program units can
32825be controlled in GNAT, either automatically or with explicit programming
32826features.
32827
32828@menu
32829* Elaboration Code:: 
32830* Checking the Elaboration Order:: 
32831* Controlling the Elaboration Order:: 
32832* Controlling Elaboration in GNAT - Internal Calls:: 
32833* Controlling Elaboration in GNAT - External Calls:: 
32834* Default Behavior in GNAT - Ensuring Safety:: 
32835* Treatment of Pragma Elaborate:: 
32836* Elaboration Issues for Library Tasks:: 
32837* Mixing Elaboration Models:: 
32838* What to Do If the Default Elaboration Behavior Fails:: 
32839* Elaboration for Indirect Calls:: 
32840* Summary of Procedures for Elaboration Control:: 
32841* Other Elaboration Order Considerations:: 
32842* Determining the Chosen Elaboration Order:: 
32843
32844@end menu
32845
32846@node Elaboration Code,Checking the Elaboration Order,,Elaboration Order Handling in GNAT
32847@anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-code}@anchor{2b0}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id2}@anchor{2b1}
32848@section Elaboration Code
32849
32850
32851Ada provides rather general mechanisms for executing code at elaboration
32852time, that is to say before the main program starts executing. Such code arises
32853in three contexts:
32854
32855
32856@itemize *
32857
32858@item 
32859@emph{Initializers for variables}
32860
32861Variables declared at the library level, in package specs or bodies, can
32862require initialization that is performed at elaboration time, as in:
32863
32864@example
32865Sqrt_Half : Float := Sqrt (0.5);
32866@end example
32867
32868@item 
32869@emph{Package initialization code}
32870
32871Code in a @cite{BEGIN-END} section at the outer level of a package body is
32872executed as part of the package body elaboration code.
32873
32874@item 
32875@emph{Library level task allocators}
32876
32877Tasks that are declared using task allocators at the library level
32878start executing immediately and hence can execute at elaboration time.
32879@end itemize
32880
32881Subprogram calls are possible in any of these contexts, which means that
32882any arbitrary part of the program may be executed as part of the elaboration
32883code. It is even possible to write a program which does all its work at
32884elaboration time, with a null main program, although stylistically this
32885would usually be considered an inappropriate way to structure
32886a program.
32887
32888An important concern arises in the context of elaboration code:
32889we have to be sure that it is executed in an appropriate order. What we
32890have is a series of elaboration code sections, potentially one section
32891for each unit in the program. It is important that these execute
32892in the correct order. Correctness here means that, taking the above
32893example of the declaration of @cite{Sqrt_Half},
32894if some other piece of
32895elaboration code references @cite{Sqrt_Half},
32896then it must run after the
32897section of elaboration code that contains the declaration of
32898@cite{Sqrt_Half}.
32899
32900There would never be any order of elaboration problem if we made a rule
32901that whenever you @emph{with} a unit, you must elaborate both the spec and body
32902of that unit before elaborating the unit doing the @emph{with}ing:
32903
32904@example
32905with Unit_1;
32906package Unit_2 is ...
32907@end example
32908
32909would require that both the body and spec of @cite{Unit_1} be elaborated
32910before the spec of @cite{Unit_2}. However, a rule like that would be far too
32911restrictive. In particular, it would make it impossible to have routines
32912in separate packages that were mutually recursive.
32913
32914You might think that a clever enough compiler could look at the actual
32915elaboration code and determine an appropriate correct order of elaboration,
32916but in the general case, this is not possible. Consider the following
32917example.
32918
32919In the body of @cite{Unit_1}, we have a procedure @cite{Func_1}
32920that references
32921the variable @cite{Sqrt_1}, which is declared in the elaboration code
32922of the body of @cite{Unit_1}:
32923
32924@example
32925Sqrt_1 : Float := Sqrt (0.1);
32926@end example
32927
32928The elaboration code of the body of @cite{Unit_1} also contains:
32929
32930@example
32931if expression_1 = 1 then
32932   Q := Unit_2.Func_2;
32933end if;
32934@end example
32935
32936@cite{Unit_2} is exactly parallel,
32937it has a procedure @cite{Func_2} that references
32938the variable @cite{Sqrt_2}, which is declared in the elaboration code of
32939the body @cite{Unit_2}:
32940
32941@example
32942Sqrt_2 : Float := Sqrt (0.1);
32943@end example
32944
32945The elaboration code of the body of @cite{Unit_2} also contains:
32946
32947@example
32948if expression_2 = 2 then
32949   Q := Unit_1.Func_1;
32950end if;
32951@end example
32952
32953Now the question is, which of the following orders of elaboration is
32954acceptable:
32955
32956@example
32957Spec of Unit_1
32958Spec of Unit_2
32959Body of Unit_1
32960Body of Unit_2
32961@end example
32962
32963or
32964
32965@example
32966Spec of Unit_2
32967Spec of Unit_1
32968Body of Unit_2
32969Body of Unit_1
32970@end example
32971
32972If you carefully analyze the flow here, you will see that you cannot tell
32973at compile time the answer to this question.
32974If @cite{expression_1} is not equal to 1,
32975and @cite{expression_2} is not equal to 2,
32976then either order is acceptable, because neither of the function calls is
32977executed. If both tests evaluate to true, then neither order is acceptable
32978and in fact there is no correct order.
32979
32980If one of the two expressions is true, and the other is false, then one
32981of the above orders is correct, and the other is incorrect. For example,
32982if @cite{expression_1} /= 1 and @cite{expression_2} = 2,
32983then the call to @cite{Func_1}
32984will occur, but not the call to @cite{Func_2.}
32985This means that it is essential
32986to elaborate the body of @cite{Unit_1} before
32987the body of @cite{Unit_2}, so the first
32988order of elaboration is correct and the second is wrong.
32989
32990By making @cite{expression_1} and @cite{expression_2}
32991depend on input data, or perhaps
32992the time of day, we can make it impossible for the compiler or binder
32993to figure out which of these expressions will be true, and hence it
32994is impossible to guarantee a safe order of elaboration at run time.
32995
32996@node Checking the Elaboration Order,Controlling the Elaboration Order,Elaboration Code,Elaboration Order Handling in GNAT
32997@anchor{gnat_ugn/elaboration_order_handling_in_gnat checking-the-elaboration-order}@anchor{2b2}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id3}@anchor{2b3}
32998@section Checking the Elaboration Order
32999
33000
33001In some languages that involve the same kind of elaboration problems,
33002e.g., Java and C++, the programmer needs to take these
33003ordering problems into account, and it is common to
33004write a program in which an incorrect elaboration order  gives
33005surprising results, because it references variables before they
33006are initialized.
33007Ada is designed to be a safe language, and a programmer-beware approach is
33008clearly not sufficient. Consequently, the language provides three lines
33009of defense:
33010
33011
33012@itemize *
33013
33014@item 
33015@emph{Standard rules}
33016
33017Some standard rules restrict the possible choice of elaboration
33018order. In particular, if you @emph{with} a unit, then its spec is always
33019elaborated before the unit doing the @emph{with}. Similarly, a parent
33020spec is always elaborated before the child spec, and finally
33021a spec is always elaborated before its corresponding body.
33022@end itemize
33023
33024@geindex Elaboration checks
33025
33026@geindex Checks
33027@geindex elaboration
33028
33029
33030@itemize *
33031
33032@item 
33033@emph{Dynamic elaboration checks}
33034
33035Dynamic checks are made at run time, so that if some entity is accessed
33036before it is elaborated (typically  by means of a subprogram call)
33037then the exception (@cite{Program_Error}) is raised.
33038
33039@item 
33040@emph{Elaboration control}
33041
33042Facilities are provided for the programmer to specify the desired order
33043of elaboration.
33044@end itemize
33045
33046Let's look at these facilities in more detail. First, the rules for
33047dynamic checking. One possible rule would be simply to say that the
33048exception is raised if you access a variable which has not yet been
33049elaborated. The trouble with this approach is that it could require
33050expensive checks on every variable reference. Instead Ada has two
33051rules which are a little more restrictive, but easier to check, and
33052easier to state:
33053
33054
33055@itemize *
33056
33057@item 
33058@emph{Restrictions on calls}
33059
33060A subprogram can only be called at elaboration time if its body
33061has been elaborated. The rules for elaboration given above guarantee
33062that the spec of the subprogram has been elaborated before the
33063call, but not the body. If this rule is violated, then the
33064exception @cite{Program_Error} is raised.
33065
33066@item 
33067@emph{Restrictions on instantiations}
33068
33069A generic unit can only be instantiated if the body of the generic
33070unit has been elaborated. Again, the rules for elaboration given above
33071guarantee that the spec of the generic unit has been elaborated
33072before the instantiation, but not the body. If this rule is
33073violated, then the exception @cite{Program_Error} is raised.
33074@end itemize
33075
33076The idea is that if the body has been elaborated, then any variables
33077it references must have been elaborated; by checking for the body being
33078elaborated we guarantee that none of its references causes any
33079trouble. As we noted above, this is a little too restrictive, because a
33080subprogram that has no non-local references in its body may in fact be safe
33081to call. However, it really would be unsafe to rely on this, because
33082it would mean that the caller was aware of details of the implementation
33083in the body. This goes against the basic tenets of Ada.
33084
33085A plausible implementation can be described as follows.
33086A Boolean variable is associated with each subprogram
33087and each generic unit. This variable is initialized to False, and is set to
33088True at the point body is elaborated. Every call or instantiation checks the
33089variable, and raises @cite{Program_Error} if the variable is False.
33090
33091Note that one might think that it would be good enough to have one Boolean
33092variable for each package, but that would not deal with cases of trying
33093to call a body in the same package as the call
33094that has not been elaborated yet.
33095Of course a compiler may be able to do enough analysis to optimize away
33096some of the Boolean variables as unnecessary, and @cite{GNAT} indeed
33097does such optimizations, but still the easiest conceptual model is to
33098think of there being one variable per subprogram.
33099
33100@node Controlling the Elaboration Order,Controlling Elaboration in GNAT - Internal Calls,Checking the Elaboration Order,Elaboration Order Handling in GNAT
33101@anchor{gnat_ugn/elaboration_order_handling_in_gnat id4}@anchor{2b4}@anchor{gnat_ugn/elaboration_order_handling_in_gnat controlling-the-elaboration-order}@anchor{2b5}
33102@section Controlling the Elaboration Order
33103
33104
33105In the previous section we discussed the rules in Ada which ensure
33106that @cite{Program_Error} is raised if an incorrect elaboration order is
33107chosen. This prevents erroneous executions, but we need mechanisms to
33108specify a correct execution and avoid the exception altogether.
33109To achieve this, Ada provides a number of features for controlling
33110the order of elaboration. We discuss these features in this section.
33111
33112First, there are several ways of indicating to the compiler that a given
33113unit has no elaboration problems:
33114
33115
33116@itemize *
33117
33118@item 
33119@emph{packages that do not require a body}
33120
33121A library package that does not require a body does not permit
33122a body (this rule was introduced in Ada 95).
33123Thus if we have a such a package, as in:
33124
33125@example
33126package Definitions is
33127   generic
33128      type m is new integer;
33129   package Subp is
33130      type a is array (1 .. 10) of m;
33131      type b is array (1 .. 20) of m;
33132   end Subp;
33133end Definitions;
33134@end example
33135
33136A package that @emph{with}s @cite{Definitions} may safely instantiate
33137@cite{Definitions.Subp} because the compiler can determine that there
33138definitely is no package body to worry about in this case
33139@end itemize
33140
33141@geindex pragma Pure
33142
33143
33144@itemize *
33145
33146@item 
33147@emph{pragma Pure}
33148
33149This pragma places sufficient restrictions on a unit to guarantee that
33150no call to any subprogram in the unit can result in an
33151elaboration problem. This means that the compiler does not need
33152to worry about the point of elaboration of such units, and in
33153particular, does not need to check any calls to any subprograms
33154in this unit.
33155@end itemize
33156
33157@geindex pragma Preelaborate
33158
33159
33160@itemize *
33161
33162@item 
33163@emph{pragma Preelaborate}
33164
33165This pragma places slightly less stringent restrictions on a unit than
33166does pragma Pure,
33167but these restrictions are still sufficient to ensure that there
33168are no elaboration problems with any calls to the unit.
33169@end itemize
33170
33171@geindex pragma Elaborate_Body
33172
33173
33174@itemize *
33175
33176@item 
33177@emph{pragma Elaborate_Body}
33178
33179This pragma requires that the body of a unit be elaborated immediately
33180after its spec. Suppose a unit @cite{A} has such a pragma,
33181and unit @cite{B} does
33182a @emph{with} of unit @cite{A}. Recall that the standard rules require
33183the spec of unit @cite{A}
33184to be elaborated before the @emph{with}ing unit; given the pragma in
33185@cite{A}, we also know that the body of @cite{A}
33186will be elaborated before @cite{B}, so
33187that calls to @cite{A} are safe and do not need a check.
33188
33189Note that, unlike pragma @cite{Pure} and pragma @cite{Preelaborate},
33190the use of @cite{Elaborate_Body} does not guarantee that the program is
33191free of elaboration problems, because it may not be possible
33192to satisfy the requested elaboration order.
33193Let's go back to the example with @cite{Unit_1} and @cite{Unit_2}.
33194If a programmer marks @cite{Unit_1} as @cite{Elaborate_Body},
33195and not @cite{Unit_2@comma{}} then the order of
33196elaboration will be:
33197
33198@example
33199Spec of Unit_2
33200Spec of Unit_1
33201Body of Unit_1
33202Body of Unit_2
33203@end example
33204
33205Now that means that the call to @cite{Func_1} in @cite{Unit_2}
33206need not be checked,
33207it must be safe. But the call to @cite{Func_2} in
33208@cite{Unit_1} may still fail if
33209@cite{Expression_1} is equal to 1,
33210and the programmer must still take
33211responsibility for this not being the case.
33212
33213If all units carry a pragma @cite{Elaborate_Body}, then all problems are
33214eliminated, except for calls entirely within a body, which are
33215in any case fully under programmer control. However, using the pragma
33216everywhere is not always possible.
33217In particular, for our @cite{Unit_1}/@cite{Unit_2} example, if
33218we marked both of them as having pragma @cite{Elaborate_Body}, then
33219clearly there would be no possible elaboration order.
33220@end itemize
33221
33222The above pragmas allow a server to guarantee safe use by clients, and
33223clearly this is the preferable approach. Consequently a good rule
33224is to mark units as @cite{Pure} or @cite{Preelaborate} if possible,
33225and if this is not possible,
33226mark them as @cite{Elaborate_Body} if possible.
33227As we have seen, there are situations where neither of these
33228three pragmas can be used.
33229So we also provide methods for clients to control the
33230order of elaboration of the servers on which they depend:
33231
33232@geindex pragma Elaborate
33233
33234
33235@itemize *
33236
33237@item 
33238@emph{pragma Elaborate (unit)}
33239
33240This pragma is placed in the context clause, after a @emph{with} clause,
33241and it requires that the body of the named unit be elaborated before
33242the unit in which the pragma occurs. The idea is to use this pragma
33243if the current unit calls at elaboration time, directly or indirectly,
33244some subprogram in the named unit.
33245@end itemize
33246
33247@geindex pragma Elaborate_All
33248
33249
33250@itemize *
33251
33252@item 
33253@emph{pragma Elaborate_All (unit)}
33254
33255This is a stronger version of the Elaborate pragma. Consider the
33256following example:
33257
33258@example
33259Unit A |withs| unit B and calls B.Func in elab code
33260Unit B |withs| unit C, and B.Func calls C.Func
33261@end example
33262
33263Now if we put a pragma @cite{Elaborate (B)}
33264in unit @cite{A}, this ensures that the
33265body of @cite{B} is elaborated before the call, but not the
33266body of @cite{C}, so
33267the call to @cite{C.Func} could still cause @cite{Program_Error} to
33268be raised.
33269
33270The effect of a pragma @cite{Elaborate_All} is stronger, it requires
33271not only that the body of the named unit be elaborated before the
33272unit doing the @emph{with}, but also the bodies of all units that the
33273named unit uses, following @emph{with} links transitively. For example,
33274if we put a pragma @cite{Elaborate_All (B)} in unit @cite{A},
33275then it requires not only that the body of @cite{B} be elaborated before @cite{A},
33276but also the body of @cite{C}, because @cite{B} @emph{with}s @cite{C}.
33277@end itemize
33278
33279We are now in a position to give a usage rule in Ada for avoiding
33280elaboration problems, at least if dynamic dispatching and access to
33281subprogram values are not used. We will handle these cases separately
33282later.
33283
33284The rule is simple:
33285
33286@emph{If a unit has elaboration code that can directly or
33287indirectly make a call to a subprogram in a |withed| unit, or instantiate
33288a generic package in a |withed| unit,
33289then if the |withed| unit does not have
33290pragma `Pure` or `Preelaborate`, then the client should have
33291a pragma `Elaborate_All`for the |withed| unit.*}
33292
33293By following this rule a client is
33294assured that calls can be made without risk of an exception.
33295
33296For generic subprogram instantiations, the rule can be relaxed to
33297require only a pragma @cite{Elaborate} since elaborating the body
33298of a subprogram cannot cause any transitive elaboration (we are
33299not calling the subprogram in this case, just elaborating its
33300declaration).
33301
33302If this rule is not followed, then a program may be in one of four
33303states:
33304
33305
33306@itemize *
33307
33308@item 
33309@emph{No order exists}
33310
33311No order of elaboration exists which follows the rules, taking into
33312account any @cite{Elaborate}, @cite{Elaborate_All},
33313or @cite{Elaborate_Body} pragmas. In
33314this case, an Ada compiler must diagnose the situation at bind
33315time, and refuse to build an executable program.
33316
33317@item 
33318@emph{One or more orders exist, all incorrect}
33319
33320One or more acceptable elaboration orders exist, and all of them
33321generate an elaboration order problem. In this case, the binder
33322can build an executable program, but @cite{Program_Error} will be raised
33323when the program is run.
33324
33325@item 
33326@emph{Several orders exist, some right, some incorrect}
33327
33328One or more acceptable elaboration orders exists, and some of them
33329work, and some do not. The programmer has not controlled
33330the order of elaboration, so the binder may or may not pick one of
33331the correct orders, and the program may or may not raise an
33332exception when it is run. This is the worst case, because it means
33333that the program may fail when moved to another compiler, or even
33334another version of the same compiler.
33335
33336@item 
33337@emph{One or more orders exists, all correct}
33338
33339One ore more acceptable elaboration orders exist, and all of them
33340work. In this case the program runs successfully. This state of
33341affairs can be guaranteed by following the rule we gave above, but
33342may be true even if the rule is not followed.
33343@end itemize
33344
33345Note that one additional advantage of following our rules on the use
33346of @cite{Elaborate} and @cite{Elaborate_All}
33347is that the program continues to stay in the ideal (all orders OK) state
33348even if maintenance
33349changes some bodies of some units. Conversely, if a program that does
33350not follow this rule happens to be safe at some point, this state of affairs
33351may deteriorate silently as a result of maintenance changes.
33352
33353You may have noticed that the above discussion did not mention
33354the use of @cite{Elaborate_Body}. This was a deliberate omission. If you
33355@emph{with} an @cite{Elaborate_Body} unit, it still may be the case that
33356code in the body makes calls to some other unit, so it is still necessary
33357to use @cite{Elaborate_All} on such units.
33358
33359@node Controlling Elaboration in GNAT - Internal Calls,Controlling Elaboration in GNAT - External Calls,Controlling the Elaboration Order,Elaboration Order Handling in GNAT
33360@anchor{gnat_ugn/elaboration_order_handling_in_gnat id5}@anchor{2b6}@anchor{gnat_ugn/elaboration_order_handling_in_gnat controlling-elaboration-in-gnat-internal-calls}@anchor{2b7}
33361@section Controlling Elaboration in GNAT - Internal Calls
33362
33363
33364In the case of internal calls, i.e., calls within a single package, the
33365programmer has full control over the order of elaboration, and it is up
33366to the programmer to elaborate declarations in an appropriate order. For
33367example writing:
33368
33369@example
33370function One return Float;
33371
33372Q : Float := One;
33373
33374function One return Float is
33375begin
33376     return 1.0;
33377end One;
33378@end example
33379
33380will obviously raise @cite{Program_Error} at run time, because function
33381One will be called before its body is elaborated. In this case GNAT will
33382generate a warning that the call will raise @cite{Program_Error}:
33383
33384@example
33385 1. procedure y is
33386 2.    function One return Float;
33387 3.
33388 4.    Q : Float := One;
33389                    |
33390    >>> warning: cannot call "One" before body is elaborated
33391    >>> warning: Program_Error will be raised at run time
33392
33393 5.
33394 6.    function One return Float is
33395 7.    begin
33396 8.         return 1.0;
33397 9.    end One;
3339810.
3339911. begin
3340012.    null;
3340113. end;
33402@end example
33403
33404Note that in this particular case, it is likely that the call is safe, because
33405the function @cite{One} does not access any global variables.
33406Nevertheless in Ada, we do not want the validity of the check to depend on
33407the contents of the body (think about the separate compilation case), so this
33408is still wrong, as we discussed in the previous sections.
33409
33410The error is easily corrected by rearranging the declarations so that the
33411body of @cite{One} appears before the declaration containing the call
33412(note that in Ada 95 as well as later versions of the Ada standard,
33413declarations can appear in any order, so there is no restriction that
33414would prevent this reordering, and if we write:
33415
33416@example
33417function One return Float;
33418
33419function One return Float is
33420begin
33421     return 1.0;
33422end One;
33423
33424Q : Float := One;
33425@end example
33426
33427then all is well, no warning is generated, and no
33428@cite{Program_Error} exception
33429will be raised.
33430Things are more complicated when a chain of subprograms is executed:
33431
33432@example
33433function A return Integer;
33434function B return Integer;
33435function C return Integer;
33436
33437function B return Integer is begin return A; end;
33438function C return Integer is begin return B; end;
33439
33440X : Integer := C;
33441
33442function A return Integer is begin return 1; end;
33443@end example
33444
33445Now the call to @cite{C}
33446at elaboration time in the declaration of @cite{X} is correct, because
33447the body of @cite{C} is already elaborated,
33448and the call to @cite{B} within the body of
33449@cite{C} is correct, but the call
33450to @cite{A} within the body of @cite{B} is incorrect, because the body
33451of @cite{A} has not been elaborated, so @cite{Program_Error}
33452will be raised on the call to @cite{A}.
33453In this case GNAT will generate a
33454warning that @cite{Program_Error} may be
33455raised at the point of the call. Let's look at the warning:
33456
33457@example
33458 1. procedure x is
33459 2.    function A return Integer;
33460 3.    function B return Integer;
33461 4.    function C return Integer;
33462 5.
33463 6.    function B return Integer is begin return A; end;
33464                                                    |
33465    >>> warning: call to "A" before body is elaborated may
33466                 raise Program_Error
33467    >>> warning: "B" called at line 7
33468    >>> warning: "C" called at line 9
33469
33470 7.    function C return Integer is begin return B; end;
33471 8.
33472 9.    X : Integer := C;
3347310.
3347411.    function A return Integer is begin return 1; end;
3347512.
3347613. begin
3347714.    null;
3347815. end;
33479@end example
33480
33481Note that the message here says 'may raise', instead of the direct case,
33482where the message says 'will be raised'. That's because whether
33483@cite{A} is
33484actually called depends in general on run-time flow of control.
33485For example, if the body of @cite{B} said
33486
33487@example
33488function B return Integer is
33489begin
33490   if some-condition-depending-on-input-data then
33491      return A;
33492   else
33493      return 1;
33494   end if;
33495end B;
33496@end example
33497
33498then we could not know until run time whether the incorrect call to A would
33499actually occur, so @cite{Program_Error} might
33500or might not be raised. It is possible for a compiler to
33501do a better job of analyzing bodies, to
33502determine whether or not @cite{Program_Error}
33503might be raised, but it certainly
33504couldn't do a perfect job (that would require solving the halting problem
33505and is provably impossible), and because this is a warning anyway, it does
33506not seem worth the effort to do the analysis. Cases in which it
33507would be relevant are rare.
33508
33509In practice, warnings of either of the forms given
33510above will usually correspond to
33511real errors, and should be examined carefully and eliminated.
33512In the rare case where a warning is bogus, it can be suppressed by any of
33513the following methods:
33514
33515
33516@itemize *
33517
33518@item 
33519Compile with the @emph{-gnatws} switch set
33520
33521@item 
33522Suppress @cite{Elaboration_Check} for the called subprogram
33523
33524@item 
33525Use pragma @cite{Warnings_Off} to turn warnings off for the call
33526@end itemize
33527
33528For the internal elaboration check case,
33529GNAT by default generates the
33530necessary run-time checks to ensure
33531that @cite{Program_Error} is raised if any
33532call fails an elaboration check. Of course this can only happen if a
33533warning has been issued as described above. The use of pragma
33534@cite{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
33535some of these checks, meaning that it may be possible (but is not
33536guaranteed) for a program to be able to call a subprogram whose body
33537is not yet elaborated, without raising a @cite{Program_Error} exception.
33538
33539@node Controlling Elaboration in GNAT - External Calls,Default Behavior in GNAT - Ensuring Safety,Controlling Elaboration in GNAT - Internal Calls,Elaboration Order Handling in GNAT
33540@anchor{gnat_ugn/elaboration_order_handling_in_gnat id6}@anchor{2b8}@anchor{gnat_ugn/elaboration_order_handling_in_gnat controlling-elaboration-in-gnat-external-calls}@anchor{2b9}
33541@section Controlling Elaboration in GNAT - External Calls
33542
33543
33544The previous section discussed the case in which the execution of a
33545particular thread of elaboration code occurred entirely within a
33546single unit. This is the easy case to handle, because a programmer
33547has direct and total control over the order of elaboration, and
33548furthermore, checks need only be generated in cases which are rare
33549and which the compiler can easily detect.
33550The situation is more complex when separate compilation is taken into account.
33551Consider the following:
33552
33553@example
33554package Math is
33555   function Sqrt (Arg : Float) return Float;
33556end Math;
33557
33558package body Math is
33559   function Sqrt (Arg : Float) return Float is
33560   begin
33561         ...
33562   end Sqrt;
33563end Math;
33564
33565with Math;
33566package Stuff is
33567   X : Float := Math.Sqrt (0.5);
33568end Stuff;
33569
33570with Stuff;
33571procedure Main is
33572begin
33573   ...
33574end Main;
33575@end example
33576
33577where @cite{Main} is the main program. When this program is executed, the
33578elaboration code must first be executed, and one of the jobs of the
33579binder is to determine the order in which the units of a program are
33580to be elaborated. In this case we have four units: the spec and body
33581of @cite{Math},
33582the spec of @cite{Stuff} and the body of @cite{Main}).
33583In what order should the four separate sections of elaboration code
33584be executed?
33585
33586There are some restrictions in the order of elaboration that the binder
33587can choose. In particular, if unit U has a @emph{with}
33588for a package @cite{X}, then you
33589are assured that the spec of @cite{X}
33590is elaborated before U , but you are
33591not assured that the body of @cite{X}
33592is elaborated before U.
33593This means that in the above case, the binder is allowed to choose the
33594order:
33595
33596@example
33597spec of Math
33598spec of Stuff
33599body of Math
33600body of Main
33601@end example
33602
33603but that's not good, because now the call to @cite{Math.Sqrt}
33604that happens during
33605the elaboration of the @cite{Stuff}
33606spec happens before the body of @cite{Math.Sqrt} is
33607elaborated, and hence causes @cite{Program_Error} exception to be raised.
33608At first glance, one might say that the binder is misbehaving, because
33609obviously you want to elaborate the body of something you @emph{with} first, but
33610that is not a general rule that can be followed in all cases. Consider
33611
33612@example
33613package X is ...
33614
33615package Y is ...
33616
33617with X;
33618package body Y is ...
33619
33620with Y;
33621package body X is ...
33622@end example
33623
33624This is a common arrangement, and, apart from the order of elaboration
33625problems that might arise in connection with elaboration code, this works fine.
33626A rule that says that you must first elaborate the body of anything you
33627@emph{with} cannot work in this case:
33628the body of @cite{X} @emph{with}s @cite{Y},
33629which means you would have to
33630elaborate the body of @cite{Y} first, but that @emph{with}s @cite{X},
33631which means
33632you have to elaborate the body of @cite{X} first, but ... and we have a
33633loop that cannot be broken.
33634
33635It is true that the binder can in many cases guess an order of elaboration
33636that is unlikely to cause a @cite{Program_Error}
33637exception to be raised, and it tries to do so (in the
33638above example of @cite{Math/Stuff/Spec}, the GNAT binder will
33639by default
33640elaborate the body of @cite{Math} right after its spec, so all will be well).
33641
33642However, a program that blindly relies on the binder to be helpful can
33643get into trouble, as we discussed in the previous sections, so GNAT
33644provides a number of facilities for assisting the programmer in
33645developing programs that are robust with respect to elaboration order.
33646
33647@node Default Behavior in GNAT - Ensuring Safety,Treatment of Pragma Elaborate,Controlling Elaboration in GNAT - External Calls,Elaboration Order Handling in GNAT
33648@anchor{gnat_ugn/elaboration_order_handling_in_gnat id7}@anchor{2ba}@anchor{gnat_ugn/elaboration_order_handling_in_gnat default-behavior-in-gnat-ensuring-safety}@anchor{2bb}
33649@section Default Behavior in GNAT - Ensuring Safety
33650
33651
33652The default behavior in GNAT ensures elaboration safety. In its
33653default mode GNAT implements the
33654rule we previously described as the right approach. Let's restate it:
33655
33656@emph{If a unit has elaboration code that can directly or indirectly make a
33657call to a subprogram in a |withed| unit, or instantiate a generic
33658package in a |withed| unit, then if the |withed| unit
33659does not have pragma `Pure` or `Preelaborate`, then the client should have an
33660`Elaborate_All` pragma for the |withed| unit.}
33661
33662@emph{In the case of instantiating a generic subprogram, it is always
33663sufficient to have only an `Elaborate` pragma for the
33664|withed| unit.}
33665
33666By following this rule a client is assured that calls and instantiations
33667can be made without risk of an exception.
33668
33669In this mode GNAT traces all calls that are potentially made from
33670elaboration code, and puts in any missing implicit @cite{Elaborate}
33671and @cite{Elaborate_All} pragmas.
33672The advantage of this approach is that no elaboration problems
33673are possible if the binder can find an elaboration order that is
33674consistent with these implicit @cite{Elaborate} and
33675@cite{Elaborate_All} pragmas. The
33676disadvantage of this approach is that no such order may exist.
33677
33678If the binder does not generate any diagnostics, then it means that it has
33679found an elaboration order that is guaranteed to be safe. However, the binder
33680may still be relying on implicitly generated @cite{Elaborate} and
33681@cite{Elaborate_All} pragmas so portability to other compilers than GNAT is not
33682guaranteed.
33683
33684If it is important to guarantee portability, then the compilations should
33685use the @emph{-gnatel}
33686(info messages for elaboration pragmas) switch. This will cause info messages
33687to be generated indicating the missing @cite{Elaborate} and
33688@cite{Elaborate_All} pragmas.
33689Consider the following source program:
33690
33691@example
33692with k;
33693package j is
33694  m : integer := k.r;
33695end;
33696@end example
33697
33698where it is clear that there
33699should be a pragma @cite{Elaborate_All}
33700for unit @cite{k}. An implicit pragma will be generated, and it is
33701likely that the binder will be able to honor it. However, if you want
33702to port this program to some other Ada compiler than GNAT.
33703it is safer to include the pragma explicitly in the source. If this
33704unit is compiled with the @emph{-gnatel}
33705switch, then the compiler outputs an information message:
33706
33707@example
337081. with k;
337092. package j is
337103.   m : integer := k.r;
33711                     |
33712   >>> info: call to "r" may raise Program_Error
33713   >>> info: missing pragma Elaborate_All for "k"
33714
337154. end;
33716@end example
33717
33718and these messages can be used as a guide for supplying manually
33719the missing pragmas. It is usually a bad idea to use this
33720option during development. That's because it will tell you when
33721you need to put in a pragma, but cannot tell you when it is time
33722to take it out. So the use of pragma @cite{Elaborate_All} may lead to
33723unnecessary dependencies and even false circularities.
33724
33725This default mode is more restrictive than the Ada Reference
33726Manual, and it is possible to construct programs which will compile
33727using the dynamic model described there, but will run into a
33728circularity using the safer static model we have described.
33729
33730Of course any Ada compiler must be able to operate in a mode
33731consistent with the requirements of the Ada Reference Manual,
33732and in particular must have the capability of implementing the
33733standard dynamic model of elaboration with run-time checks.
33734
33735In GNAT, this standard mode can be achieved either by the use of
33736the @emph{-gnatE} switch on the compiler (@emph{gcc} or
33737@emph{gnatmake}) command, or by the use of the configuration pragma:
33738
33739@example
33740pragma Elaboration_Checks (DYNAMIC);
33741@end example
33742
33743Either approach will cause the unit affected to be compiled using the
33744standard dynamic run-time elaboration checks described in the Ada
33745Reference Manual. The static model is generally preferable, since it
33746is clearly safer to rely on compile and link time checks rather than
33747run-time checks. However, in the case of legacy code, it may be
33748difficult to meet the requirements of the static model. This
33749issue is further discussed in
33750@ref{2bc,,What to Do If the Default Elaboration Behavior Fails}.
33751
33752Note that the static model provides a strict subset of the allowed
33753behavior and programs of the Ada Reference Manual, so if you do
33754adhere to the static model and no circularities exist,
33755then you are assured that your program will
33756work using the dynamic model, providing that you remove any
33757pragma Elaborate statements from the source.
33758
33759@node Treatment of Pragma Elaborate,Elaboration Issues for Library Tasks,Default Behavior in GNAT - Ensuring Safety,Elaboration Order Handling in GNAT
33760@anchor{gnat_ugn/elaboration_order_handling_in_gnat treatment-of-pragma-elaborate}@anchor{2bd}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id8}@anchor{2be}
33761@section Treatment of Pragma Elaborate
33762
33763
33764@geindex Pragma Elaborate
33765
33766The use of @cite{pragma Elaborate}
33767should generally be avoided in Ada 95 and Ada 2005 programs,
33768since there is no guarantee that transitive calls
33769will be properly handled. Indeed at one point, this pragma was placed
33770in Annex J (Obsolescent Features), on the grounds that it is never useful.
33771
33772Now that's a bit restrictive. In practice, the case in which
33773@cite{pragma Elaborate} is useful is when the caller knows that there
33774are no transitive calls, or that the called unit contains all necessary
33775transitive @cite{pragma Elaborate} statements, and legacy code often
33776contains such uses.
33777
33778Strictly speaking the static mode in GNAT should ignore such pragmas,
33779since there is no assurance at compile time that the necessary safety
33780conditions are met. In practice, this would cause GNAT to be incompatible
33781with correctly written Ada 83 code that had all necessary
33782@cite{pragma Elaborate} statements in place. Consequently, we made the
33783decision that GNAT in its default mode will believe that if it encounters
33784a @cite{pragma Elaborate} then the programmer knows what they are doing,
33785and it will trust that no elaboration errors can occur.
33786
33787The result of this decision is two-fold. First to be safe using the
33788static mode, you should remove all @cite{pragma Elaborate} statements.
33789Second, when fixing circularities in existing code, you can selectively
33790use @cite{pragma Elaborate} statements to convince the static mode of
33791GNAT that it need not generate an implicit @cite{pragma Elaborate_All}
33792statement.
33793
33794When using the static mode with @emph{-gnatwl}, any use of
33795@cite{pragma Elaborate} will generate a warning about possible
33796problems.
33797
33798@node Elaboration Issues for Library Tasks,Mixing Elaboration Models,Treatment of Pragma Elaborate,Elaboration Order Handling in GNAT
33799@anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-issues-for-library-tasks}@anchor{2bf}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id9}@anchor{2c0}
33800@section Elaboration Issues for Library Tasks
33801
33802
33803@geindex Library tasks
33804@geindex elaboration issues
33805
33806@geindex Elaboration of library tasks
33807
33808In this section we examine special elaboration issues that arise for
33809programs that declare library level tasks.
33810
33811Generally the model of execution of an Ada program is that all units are
33812elaborated, and then execution of the program starts. However, the
33813declaration of library tasks definitely does not fit this model. The
33814reason for this is that library tasks start as soon as they are declared
33815(more precisely, as soon as the statement part of the enclosing package
33816body is reached), that is to say before elaboration
33817of the program is complete. This means that if such a task calls a
33818subprogram, or an entry in another task, the callee may or may not be
33819elaborated yet, and in the standard
33820Reference Manual model of dynamic elaboration checks, you can even
33821get timing dependent Program_Error exceptions, since there can be
33822a race between the elaboration code and the task code.
33823
33824The static model of elaboration in GNAT seeks to avoid all such
33825dynamic behavior, by being conservative, and the conservative
33826approach in this particular case is to assume that all the code
33827in a task body is potentially executed at elaboration time if
33828a task is declared at the library level.
33829
33830This can definitely result in unexpected circularities. Consider
33831the following example
33832
33833@example
33834package Decls is
33835  task Lib_Task is
33836     entry Start;
33837  end Lib_Task;
33838
33839  type My_Int is new Integer;
33840
33841  function Ident (M : My_Int) return My_Int;
33842end Decls;
33843
33844with Utils;
33845package body Decls is
33846  task body Lib_Task is
33847  begin
33848     accept Start;
33849     Utils.Put_Val (2);
33850  end Lib_Task;
33851
33852  function Ident (M : My_Int) return My_Int is
33853  begin
33854     return M;
33855  end Ident;
33856end Decls;
33857
33858with Decls;
33859package Utils is
33860  procedure Put_Val (Arg : Decls.My_Int);
33861end Utils;
33862
33863with Text_IO;
33864package body Utils is
33865  procedure Put_Val (Arg : Decls.My_Int) is
33866  begin
33867     Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
33868  end Put_Val;
33869end Utils;
33870
33871with Decls;
33872procedure Main is
33873begin
33874   Decls.Lib_Task.Start;
33875end;
33876@end example
33877
33878If the above example is compiled in the default static elaboration
33879mode, then a circularity occurs. The circularity comes from the call
33880@cite{Utils.Put_Val} in the task body of @cite{Decls.Lib_Task}. Since
33881this call occurs in elaboration code, we need an implicit pragma
33882@cite{Elaborate_All} for @cite{Utils}. This means that not only must
33883the spec and body of @cite{Utils} be elaborated before the body
33884of @cite{Decls}, but also the spec and body of any unit that is
33885@emph{with}ed by the body of @cite{Utils} must also be elaborated before
33886the body of @cite{Decls}. This is the transitive implication of
33887pragma @cite{Elaborate_All} and it makes sense, because in general
33888the body of @cite{Put_Val} might have a call to something in a
33889@emph{with}ed unit.
33890
33891In this case, the body of Utils (actually its spec) @emph{with}s
33892@cite{Decls}. Unfortunately this means that the body of @cite{Decls}
33893must be elaborated before itself, in case there is a call from the
33894body of @cite{Utils}.
33895
33896Here is the exact chain of events we are worrying about:
33897
33898
33899@itemize *
33900
33901@item 
33902In the body of @cite{Decls} a call is made from within the body of a library
33903task to a subprogram in the package @cite{Utils}. Since this call may
33904occur at elaboration time (given that the task is activated at elaboration
33905time), we have to assume the worst, i.e., that the
33906call does happen at elaboration time.
33907
33908@item 
33909This means that the body and spec of @cite{Util} must be elaborated before
33910the body of @cite{Decls} so that this call does not cause an access before
33911elaboration.
33912
33913@item 
33914Within the body of @cite{Util}, specifically within the body of
33915@cite{Util.Put_Val} there may be calls to any unit @emph{with}ed
33916by this package.
33917
33918@item 
33919One such @emph{with}ed package is package @cite{Decls}, so there
33920might be a call to a subprogram in @cite{Decls} in @cite{Put_Val}.
33921In fact there is such a call in this example, but we would have to
33922assume that there was such a call even if it were not there, since
33923we are not supposed to write the body of @cite{Decls} knowing what
33924is in the body of @cite{Utils}; certainly in the case of the
33925static elaboration model, the compiler does not know what is in
33926other bodies and must assume the worst.
33927
33928@item 
33929This means that the spec and body of @cite{Decls} must also be
33930elaborated before we elaborate the unit containing the call, but
33931that unit is @cite{Decls}! This means that the body of @cite{Decls}
33932must be elaborated before itself, and that's a circularity.
33933@end itemize
33934
33935Indeed, if you add an explicit pragma @cite{Elaborate_All} for @cite{Utils} in
33936the body of @cite{Decls} you will get a true Ada Reference Manual
33937circularity that makes the program illegal.
33938
33939In practice, we have found that problems with the static model of
33940elaboration in existing code often arise from library tasks, so
33941we must address this particular situation.
33942
33943Note that if we compile and run the program above, using the dynamic model of
33944elaboration (that is to say use the @emph{-gnatE} switch),
33945then it compiles, binds,
33946links, and runs, printing the expected result of 2. Therefore in some sense
33947the circularity here is only apparent, and we need to capture
33948the properties of this program that  distinguish it from other library-level
33949tasks that have real elaboration problems.
33950
33951We have four possible answers to this question:
33952
33953
33954@itemize *
33955
33956@item 
33957Use the dynamic model of elaboration.
33958
33959If we use the @emph{-gnatE} switch, then as noted above, the program works.
33960Why is this? If we examine the task body, it is apparent that the task cannot
33961proceed past the
33962@cite{accept} statement until after elaboration has been completed, because
33963the corresponding entry call comes from the main program, not earlier.
33964This is why the dynamic model works here. But that's really giving
33965up on a precise analysis, and we prefer to take this approach only if we cannot
33966solve the
33967problem in any other manner. So let us examine two ways to reorganize
33968the program to avoid the potential elaboration problem.
33969
33970@item 
33971Split library tasks into separate packages.
33972
33973Write separate packages, so that library tasks are isolated from
33974other declarations as much as possible. Let us look at a variation on
33975the above program.
33976
33977@example
33978package Decls1 is
33979  task Lib_Task is
33980     entry Start;
33981  end Lib_Task;
33982end Decls1;
33983
33984with Utils;
33985package body Decls1 is
33986  task body Lib_Task is
33987  begin
33988     accept Start;
33989     Utils.Put_Val (2);
33990  end Lib_Task;
33991end Decls1;
33992
33993package Decls2 is
33994  type My_Int is new Integer;
33995  function Ident (M : My_Int) return My_Int;
33996end Decls2;
33997
33998with Utils;
33999package body Decls2 is
34000  function Ident (M : My_Int) return My_Int is
34001  begin
34002     return M;
34003  end Ident;
34004end Decls2;
34005
34006with Decls2;
34007package Utils is
34008  procedure Put_Val (Arg : Decls2.My_Int);
34009end Utils;
34010
34011with Text_IO;
34012package body Utils is
34013  procedure Put_Val (Arg : Decls2.My_Int) is
34014  begin
34015     Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
34016  end Put_Val;
34017end Utils;
34018
34019with Decls1;
34020procedure Main is
34021begin
34022   Decls1.Lib_Task.Start;
34023end;
34024@end example
34025
34026All we have done is to split @cite{Decls} into two packages, one
34027containing the library task, and one containing everything else. Now
34028there is no cycle, and the program compiles, binds, links and executes
34029using the default static model of elaboration.
34030
34031@item 
34032Declare separate task types.
34033
34034A significant part of the problem arises because of the use of the
34035single task declaration form. This means that the elaboration of
34036the task type, and the elaboration of the task itself (i.e., the
34037creation of the task) happen at the same time. A good rule
34038of style in Ada is to always create explicit task types. By
34039following the additional step of placing task objects in separate
34040packages from the task type declaration, many elaboration problems
34041are avoided. Here is another modified example of the example program:
34042
34043@example
34044package Decls is
34045  task type Lib_Task_Type is
34046     entry Start;
34047  end Lib_Task_Type;
34048
34049  type My_Int is new Integer;
34050
34051  function Ident (M : My_Int) return My_Int;
34052end Decls;
34053
34054with Utils;
34055package body Decls is
34056  task body Lib_Task_Type is
34057  begin
34058     accept Start;
34059     Utils.Put_Val (2);
34060  end Lib_Task_Type;
34061
34062  function Ident (M : My_Int) return My_Int is
34063  begin
34064     return M;
34065  end Ident;
34066end Decls;
34067
34068with Decls;
34069package Utils is
34070  procedure Put_Val (Arg : Decls.My_Int);
34071end Utils;
34072
34073with Text_IO;
34074package body Utils is
34075  procedure Put_Val (Arg : Decls.My_Int) is
34076  begin
34077     Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
34078  end Put_Val;
34079end Utils;
34080
34081with Decls;
34082package Declst is
34083   Lib_Task : Decls.Lib_Task_Type;
34084end Declst;
34085
34086with Declst;
34087procedure Main is
34088begin
34089   Declst.Lib_Task.Start;
34090end;
34091@end example
34092
34093What we have done here is to replace the @cite{task} declaration in
34094package @cite{Decls} with a @cite{task type} declaration. Then we
34095introduce a separate package @cite{Declst} to contain the actual
34096task object. This separates the elaboration issues for
34097the @cite{task type}
34098declaration, which causes no trouble, from the elaboration issues
34099of the task object, which is also unproblematic, since it is now independent
34100of the elaboration of  @cite{Utils}.
34101This separation of concerns also corresponds to
34102a generally sound engineering principle of separating declarations
34103from instances. This version of the program also compiles, binds, links,
34104and executes, generating the expected output.
34105@end itemize
34106
34107@geindex No_Entry_Calls_In_Elaboration_Code restriction
34108
34109
34110@itemize *
34111
34112@item 
34113Use No_Entry_Calls_In_Elaboration_Code restriction.
34114
34115The previous two approaches described how a program can be restructured
34116to avoid the special problems caused by library task bodies. in practice,
34117however, such restructuring may be difficult to apply to existing legacy code,
34118so we must consider solutions that do not require massive rewriting.
34119
34120Let us consider more carefully why our original sample program works
34121under the dynamic model of elaboration. The reason is that the code
34122in the task body blocks immediately on the @cite{accept}
34123statement. Now of course there is nothing to prohibit elaboration
34124code from making entry calls (for example from another library level task),
34125so we cannot tell in isolation that
34126the task will not execute the accept statement  during elaboration.
34127
34128However, in practice it is very unusual to see elaboration code
34129make any entry calls, and the pattern of tasks starting
34130at elaboration time and then immediately blocking on @cite{accept} or
34131@cite{select} statements is very common. What this means is that
34132the compiler is being too pessimistic when it analyzes the
34133whole package body as though it might be executed at elaboration
34134time.
34135
34136If we know that the elaboration code contains no entry calls, (a very safe
34137assumption most of the time, that could almost be made the default
34138behavior), then we can compile all units of the program under control
34139of the following configuration pragma:
34140
34141@example
34142pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
34143@end example
34144
34145This pragma can be placed in the @code{gnat.adc} file in the usual
34146manner. If we take our original unmodified program and compile it
34147in the presence of a @code{gnat.adc} containing the above pragma,
34148then once again, we can compile, bind, link, and execute, obtaining
34149the expected result. In the presence of this pragma, the compiler does
34150not trace calls in a task body, that appear after the first @cite{accept}
34151or @cite{select} statement, and therefore does not report a potential
34152circularity in the original program.
34153
34154The compiler will check to the extent it can that the above
34155restriction is not violated, but it is not always possible to do a
34156complete check at compile time, so it is important to use this
34157pragma only if the stated restriction is in fact met, that is to say
34158no task receives an entry call before elaboration of all units is completed.
34159@end itemize
34160
34161@node Mixing Elaboration Models,What to Do If the Default Elaboration Behavior Fails,Elaboration Issues for Library Tasks,Elaboration Order Handling in GNAT
34162@anchor{gnat_ugn/elaboration_order_handling_in_gnat id10}@anchor{2c1}@anchor{gnat_ugn/elaboration_order_handling_in_gnat mixing-elaboration-models}@anchor{2c2}
34163@section Mixing Elaboration Models
34164
34165
34166So far, we have assumed that the entire program is either compiled
34167using the dynamic model or static model, ensuring consistency. It
34168is possible to mix the two models, but rules have to be followed
34169if this mixing is done to ensure that elaboration checks are not
34170omitted.
34171
34172The basic rule is that
34173@strong{a unit compiled with the static model cannot
34174be |withed| by a unit compiled with the dynamic model}.
34175The reason for this is that in the static model, a unit assumes that
34176its clients guarantee to use (the equivalent of) pragma
34177@cite{Elaborate_All} so that no elaboration checks are required
34178in inner subprograms, and this assumption is violated if the
34179client is compiled with dynamic checks.
34180
34181The precise rule is as follows. A unit that is compiled with dynamic
34182checks can only @emph{with} a unit that meets at least one of the
34183following criteria:
34184
34185
34186@itemize *
34187
34188@item 
34189The @emph{with}ed unit is itself compiled with dynamic elaboration
34190checks (that is with the @emph{-gnatE} switch.
34191
34192@item 
34193The @emph{with}ed unit is an internal GNAT implementation unit from
34194the System, Interfaces, Ada, or GNAT hierarchies.
34195
34196@item 
34197The @emph{with}ed unit has pragma Preelaborate or pragma Pure.
34198
34199@item 
34200The @emph{with}ing unit (that is the client) has an explicit pragma
34201@cite{Elaborate_All} for the @emph{with}ed unit.
34202@end itemize
34203
34204If this rule is violated, that is if a unit with dynamic elaboration
34205checks @emph{with}s a unit that does not meet one of the above four
34206criteria, then the binder (@cite{gnatbind}) will issue a warning
34207similar to that in the following example:
34208
34209@example
34210warning: "x.ads" has dynamic elaboration checks and with's
34211warning:   "y.ads" which has static elaboration checks
34212@end example
34213
34214These warnings indicate that the rule has been violated, and that as a result
34215elaboration checks may be missed in the resulting executable file.
34216This warning may be suppressed using the @emph{-ws} binder switch
34217in the usual manner.
34218
34219One useful application of this mixing rule is in the case of a subsystem
34220which does not itself @emph{with} units from the remainder of the
34221application. In this case, the entire subsystem can be compiled with
34222dynamic checks to resolve a circularity in the subsystem, while
34223allowing the main application that uses this subsystem to be compiled
34224using the more reliable default static model.
34225
34226@node What to Do If the Default Elaboration Behavior Fails,Elaboration for Indirect Calls,Mixing Elaboration Models,Elaboration Order Handling in GNAT
34227@anchor{gnat_ugn/elaboration_order_handling_in_gnat id11}@anchor{2c3}@anchor{gnat_ugn/elaboration_order_handling_in_gnat what-to-do-if-the-default-elaboration-behavior-fails}@anchor{2bc}
34228@section What to Do If the Default Elaboration Behavior Fails
34229
34230
34231If the binder cannot find an acceptable order, it outputs detailed
34232diagnostics. For example:
34233
34234@example
34235error: elaboration circularity detected
34236info:   "proc (body)" must be elaborated before "pack (body)"
34237info:     reason: Elaborate_All probably needed in unit "pack (body)"
34238info:     recompile "pack (body)" with -gnatel
34239info:                             for full details
34240info:       "proc (body)"
34241info:         is needed by its spec:
34242info:       "proc (spec)"
34243info:         which is withed by:
34244info:       "pack (body)"
34245info:  "pack (body)" must be elaborated before "proc (body)"
34246info:     reason: pragma Elaborate in unit "proc (body)"
34247@end example
34248
34249In this case we have a cycle that the binder cannot break. On the one
34250hand, there is an explicit pragma Elaborate in @cite{proc} for
34251@cite{pack}. This means that the body of @cite{pack} must be elaborated
34252before the body of @cite{proc}. On the other hand, there is elaboration
34253code in @cite{pack} that calls a subprogram in @cite{proc}. This means
34254that for maximum safety, there should really be a pragma
34255Elaborate_All in @cite{pack} for @cite{proc} which would require that
34256the body of @cite{proc} be elaborated before the body of
34257@cite{pack}. Clearly both requirements cannot be satisfied.
34258Faced with a circularity of this kind, you have three different options.
34259
34260
34261@itemize *
34262
34263@item 
34264@emph{Fix the program}
34265
34266The most desirable option from the point of view of long-term maintenance
34267is to rearrange the program so that the elaboration problems are avoided.
34268One useful technique is to place the elaboration code into separate
34269child packages. Another is to move some of the initialization code to
34270explicitly called subprograms, where the program controls the order
34271of initialization explicitly. Although this is the most desirable option,
34272it may be impractical and involve too much modification, especially in
34273the case of complex legacy code.
34274
34275@item 
34276@emph{Perform dynamic checks}
34277
34278If the compilations are done using the @emph{-gnatE}
34279(dynamic elaboration check) switch, then GNAT behaves in a quite different
34280manner. Dynamic checks are generated for all calls that could possibly result
34281in raising an exception. With this switch, the compiler does not generate
34282implicit @cite{Elaborate} or @cite{Elaborate_All} pragmas. The behavior then is
34283exactly as specified in the @cite{Ada Reference Manual}.
34284The binder will generate
34285an executable program that may or may not raise @cite{Program_Error}, and then
34286it is the programmer's job to ensure that it does not raise an exception. Note
34287that it is important to compile all units with the switch, it cannot be used
34288selectively.
34289
34290@item 
34291@emph{Suppress checks}
34292
34293The drawback of dynamic checks is that they generate a
34294significant overhead at run time, both in space and time. If you
34295are absolutely sure that your program cannot raise any elaboration
34296exceptions, and you still want to use the dynamic elaboration model,
34297then you can use the configuration pragma
34298@cite{Suppress (Elaboration_Check)} to suppress all such checks. For
34299example this pragma could be placed in the @code{gnat.adc} file.
34300
34301@item 
34302@emph{Suppress checks selectively}
34303
34304When you know that certain calls or instantiations in elaboration code cannot
34305possibly lead to an elaboration error, and the binder nevertheless complains
34306about implicit @cite{Elaborate} and @cite{Elaborate_All} pragmas that lead to
34307elaboration circularities, it is possible to remove those warnings locally and
34308obtain a program that will bind. Clearly this can be unsafe, and it is the
34309responsibility of the programmer to make sure that the resulting program has no
34310elaboration anomalies. The pragma @cite{Suppress (Elaboration_Check)} can be
34311used with different granularity to suppress warnings and break elaboration
34312circularities:
34313
34314
34315@itemize *
34316
34317@item 
34318Place the pragma that names the called subprogram in the declarative part
34319that contains the call.
34320
34321@item 
34322Place the pragma in the declarative part, without naming an entity. This
34323disables warnings on all calls in the corresponding  declarative region.
34324
34325@item 
34326Place the pragma in the package spec that declares the called subprogram,
34327and name the subprogram. This disables warnings on all elaboration calls to
34328that subprogram.
34329
34330@item 
34331Place the pragma in the package spec that declares the called subprogram,
34332without naming any entity. This disables warnings on all elaboration calls to
34333all subprograms declared in this spec.
34334
34335@item 
34336Use Pragma Elaborate.
34337
34338As previously described in section @ref{2bd,,Treatment of Pragma Elaborate},
34339GNAT in static mode assumes that a @cite{pragma} Elaborate indicates correctly
34340that no elaboration checks are required on calls to the designated unit.
34341There may be cases in which the caller knows that no transitive calls
34342can occur, so that a @cite{pragma Elaborate} will be sufficient in a
34343case where @cite{pragma Elaborate_All} would cause a circularity.
34344@end itemize
34345
34346These five cases are listed in order of decreasing safety, and therefore
34347require increasing programmer care in their application. Consider the
34348following program:
34349
34350@example
34351package Pack1 is
34352  function F1 return Integer;
34353  X1 : Integer;
34354end Pack1;
34355
34356package Pack2 is
34357  function F2 return Integer;
34358  function Pure (x : integer) return integer;
34359  --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
34360  --  pragma Suppress (Elaboration_Check);              -- (4)
34361end Pack2;
34362
34363with Pack2;
34364package body Pack1 is
34365  function F1 return Integer is
34366  begin
34367    return 100;
34368  end F1;
34369  Val : integer := Pack2.Pure (11);    --  Elab. call (1)
34370begin
34371  declare
34372    --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
34373    --  pragma Suppress(Elaboration_Check);             -- (2)
34374  begin
34375    X1 := Pack2.F2 + 1;                --  Elab. call (2)
34376  end;
34377end Pack1;
34378
34379with Pack1;
34380package body Pack2 is
34381  function F2 return Integer is
34382  begin
34383     return Pack1.F1;
34384  end F2;
34385  function Pure (x : integer) return integer is
34386  begin
34387     return x ** 3 - 3 * x;
34388  end;
34389end Pack2;
34390
34391with Pack1, Ada.Text_IO;
34392procedure Proc3 is
34393begin
34394  Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
34395end Proc3;
34396@end example
34397
34398In the absence of any pragmas, an attempt to bind this program produces
34399the following diagnostics:
34400
34401@example
34402error: elaboration circularity detected
34403info:    "pack1 (body)" must be elaborated before "pack1 (body)"
34404info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
34405info:       recompile "pack1 (body)" with -gnatel for full details
34406info:          "pack1 (body)"
34407info:             must be elaborated along with its spec:
34408info:          "pack1 (spec)"
34409info:             which is withed by:
34410info:          "pack2 (body)"
34411info:             which must be elaborated along with its spec:
34412info:          "pack2 (spec)"
34413info:             which is withed by:
34414info:          "pack1 (body)"
34415@end example
34416
34417The sources of the circularity are the two calls to @cite{Pack2.Pure} and
34418@cite{Pack2.F2} in the body of @cite{Pack1}. We can see that the call to
34419F2 is safe, even though F2 calls F1, because the call appears after the
34420elaboration of the body of F1. Therefore the pragma (1) is safe, and will
34421remove the warning on the call. It is also possible to use pragma (2)
34422because there are no other potentially unsafe calls in the block.
34423
34424The call to @cite{Pure} is safe because this function does not depend on the
34425state of @cite{Pack2}. Therefore any call to this function is safe, and it
34426is correct to place pragma (3) in the corresponding package spec.
34427
34428Finally, we could place pragma (4) in the spec of @cite{Pack2} to disable
34429warnings on all calls to functions declared therein. Note that this is not
34430necessarily safe, and requires more detailed examination of the subprogram
34431bodies involved. In particular, a call to @cite{F2} requires that @cite{F1}
34432be already elaborated.
34433@end itemize
34434
34435It is hard to generalize on which of these four approaches should be
34436taken. Obviously if it is possible to fix the program so that the default
34437treatment works, this is preferable, but this may not always be practical.
34438It is certainly simple enough to use @emph{-gnatE}
34439but the danger in this case is that, even if the GNAT binder
34440finds a correct elaboration order, it may not always do so,
34441and certainly a binder from another Ada compiler might not. A
34442combination of testing and analysis (for which the
34443information messages generated with the @emph{-gnatel}
34444switch can be useful) must be used to ensure that the program is free
34445of errors. One switch that is useful in this testing is the
34446@emph{-p (pessimistic elaboration order)} switch for @cite{gnatbind}.
34447Normally the binder tries to find an order that has the best chance
34448of avoiding elaboration problems. However, if this switch is used, the binder
34449plays a devil's advocate role, and tries to choose the order that
34450has the best chance of failing. If your program works even with this
34451switch, then it has a better chance of being error free, but this is still
34452not a guarantee.
34453
34454For an example of this approach in action, consider the C-tests (executable
34455tests) from the ACATS suite. If these are compiled and run with the default
34456treatment, then all but one of them succeed without generating any error
34457diagnostics from the binder. However, there is one test that fails, and
34458this is not surprising, because the whole point of this test is to ensure
34459that the compiler can handle cases where it is impossible to determine
34460a correct order statically, and it checks that an exception is indeed
34461raised at run time.
34462
34463This one test must be compiled and run using the @emph{-gnatE}
34464switch, and then it passes. Alternatively, the entire suite can
34465be run using this switch. It is never wrong to run with the dynamic
34466elaboration switch if your code is correct, and we assume that the
34467C-tests are indeed correct (it is less efficient, but efficiency is
34468not a factor in running the ACATS tests.)
34469
34470@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
34471@anchor{gnat_ugn/elaboration_order_handling_in_gnat id12}@anchor{2c4}@anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-for-indirect-calls}@anchor{2c5}
34472@section Elaboration for Indirect Calls
34473
34474
34475@geindex Dispatching calls
34476
34477@geindex Indirect calls
34478
34479In rare cases, the static elaboration model fails to prevent
34480dispatching calls to not-yet-elaborated subprograms. In such cases, we
34481fall back to run-time checks; premature calls to any primitive
34482operation of a tagged type before the body of the operation has been
34483elaborated will raise @cite{Program_Error}.
34484
34485Access-to-subprogram types, however, are handled conservatively, and
34486do not require run-time checks. This was not true in earlier versions
34487of the compiler; you can use the @emph{-gnatd.U} debug switch to
34488revert to the old behavior if the new conservative behavior causes
34489elaboration cycles. Here, 'conservative' means that if you do
34490@cite{P'Access} during elaboration, the compiler will assume that you
34491might call @cite{P} indirectly during elaboration, so it adds an
34492implicit @cite{pragma Elaborate_All} on the library unit containing
34493@cite{P}. The @emph{-gnatd.U} switch is safe if you know there are
34494no such calls. If the program worked before, it will continue to work
34495with @emph{-gnatd.U}. But beware that code modifications such as
34496adding an indirect call can cause erroneous behavior in the presence
34497of @emph{-gnatd.U}.
34498
34499@node Summary of Procedures for Elaboration Control,Other Elaboration Order Considerations,Elaboration for Indirect Calls,Elaboration Order Handling in GNAT
34500@anchor{gnat_ugn/elaboration_order_handling_in_gnat id13}@anchor{2c6}@anchor{gnat_ugn/elaboration_order_handling_in_gnat summary-of-procedures-for-elaboration-control}@anchor{2c7}
34501@section Summary of Procedures for Elaboration Control
34502
34503
34504@geindex Elaboration control
34505
34506First, compile your program with the default options, using none of
34507the special elaboration control switches. If the binder successfully
34508binds your program, then you can be confident that, apart from issues
34509raised by the use of access-to-subprogram types and dynamic dispatching,
34510the program is free of elaboration errors. If it is important that the
34511program be portable to other compilers than GNAT, then use the
34512@emph{-gnatel}
34513switch to generate messages about missing @cite{Elaborate} or
34514@cite{Elaborate_All} pragmas, and supply the missing pragmas.
34515
34516If the program fails to bind using the default static elaboration
34517handling, then you can fix the program to eliminate the binder
34518message, or recompile the entire program with the
34519@emph{-gnatE} switch to generate dynamic elaboration checks,
34520and, if you are sure there really are no elaboration problems,
34521use a global pragma @cite{Suppress (Elaboration_Check)}.
34522
34523@node Other Elaboration Order Considerations,Determining the Chosen Elaboration Order,Summary of Procedures for Elaboration Control,Elaboration Order Handling in GNAT
34524@anchor{gnat_ugn/elaboration_order_handling_in_gnat id14}@anchor{2c8}@anchor{gnat_ugn/elaboration_order_handling_in_gnat other-elaboration-order-considerations}@anchor{2c9}
34525@section Other Elaboration Order Considerations
34526
34527
34528This section has been entirely concerned with the issue of finding a valid
34529elaboration order, as defined by the Ada Reference Manual. In a case
34530where several elaboration orders are valid, the task is to find one
34531of the possible valid elaboration orders (and the static model in GNAT
34532will ensure that this is achieved).
34533
34534The purpose of the elaboration rules in the Ada Reference Manual is to
34535make sure that no entity is accessed before it has been elaborated. For
34536a subprogram, this means that the spec and body must have been elaborated
34537before the subprogram is called. For an object, this means that the object
34538must have been elaborated before its value is read or written. A violation
34539of either of these two requirements is an access before elaboration order,
34540and this section has been all about avoiding such errors.
34541
34542In the case where more than one order of elaboration is possible, in the
34543sense that access before elaboration errors are avoided, then any one of
34544the orders is 'correct' in the sense that it meets the requirements of
34545the Ada Reference Manual, and no such error occurs.
34546
34547However, it may be the case for a given program, that there are
34548constraints on the order of elaboration that come not from consideration
34549of avoiding elaboration errors, but rather from extra-lingual logic
34550requirements. Consider this example:
34551
34552@example
34553with Init_Constants;
34554package Constants is
34555   X : Integer := 0;
34556   Y : Integer := 0;
34557end Constants;
34558
34559package Init_Constants is
34560   procedure P; --* require a body*
34561end Init_Constants;
34562
34563with Constants;
34564package body Init_Constants is
34565   procedure P is begin null; end;
34566begin
34567   Constants.X := 3;
34568   Constants.Y := 4;
34569end Init_Constants;
34570
34571with Constants;
34572package Calc is
34573   Z : Integer := Constants.X + Constants.Y;
34574end Calc;
34575
34576with Calc;
34577with Text_IO; use Text_IO;
34578procedure Main is
34579begin
34580   Put_Line (Calc.Z'Img);
34581end Main;
34582@end example
34583
34584In this example, there is more than one valid order of elaboration. For
34585example both the following are correct orders:
34586
34587@example
34588Init_Constants spec
34589Constants spec
34590Calc spec
34591Init_Constants body
34592Main body
34593@end example
34594
34595and
34596
34597@example
34598Init_Constants spec
34599Init_Constants body
34600Constants spec
34601Calc spec
34602Main body
34603@end example
34604
34605There is no language rule to prefer one or the other, both are correct
34606from an order of elaboration point of view. But the programmatic effects
34607of the two orders are very different. In the first, the elaboration routine
34608of @cite{Calc} initializes @cite{Z} to zero, and then the main program
34609runs with this value of zero. But in the second order, the elaboration
34610routine of @cite{Calc} runs after the body of Init_Constants has set
34611@cite{X} and @cite{Y} and thus @cite{Z} is set to 7 before @cite{Main} runs.
34612
34613One could perhaps by applying pretty clever non-artificial intelligence
34614to the situation guess that it is more likely that the second order of
34615elaboration is the one desired, but there is no formal linguistic reason
34616to prefer one over the other. In fact in this particular case, GNAT will
34617prefer the second order, because of the rule that bodies are elaborated
34618as soon as possible, but it's just luck that this is what was wanted
34619(if indeed the second order was preferred).
34620
34621If the program cares about the order of elaboration routines in a case like
34622this, it is important to specify the order required. In this particular
34623case, that could have been achieved by adding to the spec of Calc:
34624
34625@example
34626pragma Elaborate_All (Constants);
34627@end example
34628
34629which requires that the body (if any) and spec of @cite{Constants},
34630as well as the body and spec of any unit @emph{with}ed by
34631@cite{Constants} be elaborated before @cite{Calc} is elaborated.
34632
34633Clearly no automatic method can always guess which alternative you require,
34634and if you are working with legacy code that had constraints of this kind
34635which were not properly specified by adding @cite{Elaborate} or
34636@cite{Elaborate_All} pragmas, then indeed it is possible that two different
34637compilers can choose different orders.
34638
34639However, GNAT does attempt to diagnose the common situation where there
34640are uninitialized variables in the visible part of a package spec, and the
34641corresponding package body has an elaboration block that directly or
34642indirectly initialized one or more of these variables. This is the situation
34643in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
34644a warning that suggests this addition if it detects this situation.
34645
34646The @cite{gnatbind} @emph{-p} switch may be useful in smoking
34647out problems. This switch causes bodies to be elaborated as late as possible
34648instead of as early as possible. In the example above, it would have forced
34649the choice of the first elaboration order. If you get different results
34650when using this switch, and particularly if one set of results is right,
34651and one is wrong as far as you are concerned, it shows that you have some
34652missing @cite{Elaborate} pragmas. For the example above, we have the
34653following output:
34654
34655@example
34656$ gnatmake -f -q main
34657$ main
34658 7
34659$ gnatmake -f -q main -bargs -p
34660$ main
34661 0
34662@end example
34663
34664It is of course quite unlikely that both these results are correct, so
34665it is up to you in a case like this to investigate the source of the
34666difference, by looking at the two elaboration orders that are chosen,
34667and figuring out which is correct, and then adding the necessary
34668@cite{Elaborate} or @cite{Elaborate_All} pragmas to ensure the desired order.
34669
34670@node Determining the Chosen Elaboration Order,,Other Elaboration Order Considerations,Elaboration Order Handling in GNAT
34671@anchor{gnat_ugn/elaboration_order_handling_in_gnat determining-the-chosen-elaboration-order}@anchor{2ca}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id15}@anchor{2cb}
34672@section Determining the Chosen Elaboration Order
34673
34674
34675To see the elaboration order that the binder chooses, you can look at
34676the last part of the file:@cite{b~xxx.adb} binder output file. Here is an example:
34677
34678@example
34679System.Soft_Links'Elab_Body;
34680E14 := True;
34681System.Secondary_Stack'Elab_Body;
34682E18 := True;
34683System.Exception_Table'Elab_Body;
34684E24 := True;
34685Ada.Io_Exceptions'Elab_Spec;
34686E67 := True;
34687Ada.Tags'Elab_Spec;
34688Ada.Streams'Elab_Spec;
34689E43 := True;
34690Interfaces.C'Elab_Spec;
34691E69 := True;
34692System.Finalization_Root'Elab_Spec;
34693E60 := True;
34694System.Os_Lib'Elab_Body;
34695E71 := True;
34696System.Finalization_Implementation'Elab_Spec;
34697System.Finalization_Implementation'Elab_Body;
34698E62 := True;
34699Ada.Finalization'Elab_Spec;
34700E58 := True;
34701Ada.Finalization.List_Controller'Elab_Spec;
34702E76 := True;
34703System.File_Control_Block'Elab_Spec;
34704E74 := True;
34705System.File_Io'Elab_Body;
34706E56 := True;
34707Ada.Tags'Elab_Body;
34708E45 := True;
34709Ada.Text_Io'Elab_Spec;
34710Ada.Text_Io'Elab_Body;
34711E07 := True;
34712@end example
34713
34714Here Elab_Spec elaborates the spec
34715and Elab_Body elaborates the body. The assignments to the @code{E@emph{xx}} flags
34716flag that the corresponding body is now elaborated.
34717
34718You can also ask the binder to generate a more
34719readable list of the elaboration order using the
34720@cite{-l} switch when invoking the binder. Here is
34721an example of the output generated by this switch:
34722
34723@example
34724ada (spec)
34725interfaces (spec)
34726system (spec)
34727system.case_util (spec)
34728system.case_util (body)
34729system.concat_2 (spec)
34730system.concat_2 (body)
34731system.concat_3 (spec)
34732system.concat_3 (body)
34733system.htable (spec)
34734system.parameters (spec)
34735system.parameters (body)
34736system.crtl (spec)
34737interfaces.c_streams (spec)
34738interfaces.c_streams (body)
34739system.restrictions (spec)
34740system.restrictions (body)
34741system.standard_library (spec)
34742system.exceptions (spec)
34743system.exceptions (body)
34744system.storage_elements (spec)
34745system.storage_elements (body)
34746system.secondary_stack (spec)
34747system.stack_checking (spec)
34748system.stack_checking (body)
34749system.string_hash (spec)
34750system.string_hash (body)
34751system.htable (body)
34752system.strings (spec)
34753system.strings (body)
34754system.traceback (spec)
34755system.traceback (body)
34756system.traceback_entries (spec)
34757system.traceback_entries (body)
34758ada.exceptions (spec)
34759ada.exceptions.last_chance_handler (spec)
34760system.soft_links (spec)
34761system.soft_links (body)
34762ada.exceptions.last_chance_handler (body)
34763system.secondary_stack (body)
34764system.exception_table (spec)
34765system.exception_table (body)
34766ada.io_exceptions (spec)
34767ada.tags (spec)
34768ada.streams (spec)
34769interfaces.c (spec)
34770interfaces.c (body)
34771system.finalization_root (spec)
34772system.finalization_root (body)
34773system.memory (spec)
34774system.memory (body)
34775system.standard_library (body)
34776system.os_lib (spec)
34777system.os_lib (body)
34778system.unsigned_types (spec)
34779system.stream_attributes (spec)
34780system.stream_attributes (body)
34781system.finalization_implementation (spec)
34782system.finalization_implementation (body)
34783ada.finalization (spec)
34784ada.finalization (body)
34785ada.finalization.list_controller (spec)
34786ada.finalization.list_controller (body)
34787system.file_control_block (spec)
34788system.file_io (spec)
34789system.file_io (body)
34790system.val_uns (spec)
34791system.val_util (spec)
34792system.val_util (body)
34793system.val_uns (body)
34794system.wch_con (spec)
34795system.wch_con (body)
34796system.wch_cnv (spec)
34797system.wch_jis (spec)
34798system.wch_jis (body)
34799system.wch_cnv (body)
34800system.wch_stw (spec)
34801system.wch_stw (body)
34802ada.tags (body)
34803ada.exceptions (body)
34804ada.text_io (spec)
34805ada.text_io (body)
34806text_io (spec)
34807gdbstr (body)
34808@end example
34809
34810@node Inline Assembler,GNU Free Documentation License,Elaboration Order Handling in GNAT,Top
34811@anchor{gnat_ugn/inline_assembler inline-assembler}@anchor{12}@anchor{gnat_ugn/inline_assembler doc}@anchor{2cc}@anchor{gnat_ugn/inline_assembler id1}@anchor{2cd}
34812@chapter Inline Assembler
34813
34814
34815@geindex Inline Assembler
34816
34817If you need to write low-level software that interacts directly
34818with the hardware, Ada provides two ways to incorporate assembly
34819language code into your program.  First, you can import and invoke
34820external routines written in assembly language, an Ada feature fully
34821supported by GNAT.  However, for small sections of code it may be simpler
34822or more efficient to include assembly language statements directly
34823in your Ada source program, using the facilities of the implementation-defined
34824package @cite{System.Machine_Code}, which incorporates the gcc
34825Inline Assembler.  The Inline Assembler approach offers a number of advantages,
34826including the following:
34827
34828
34829@itemize *
34830
34831@item 
34832No need to use non-Ada tools
34833
34834@item 
34835Consistent interface over different targets
34836
34837@item 
34838Automatic usage of the proper calling conventions
34839
34840@item 
34841Access to Ada constants and variables
34842
34843@item 
34844Definition of intrinsic routines
34845
34846@item 
34847Possibility of inlining a subprogram comprising assembler code
34848
34849@item 
34850Code optimizer can take Inline Assembler code into account
34851@end itemize
34852
34853This appendix presents a series of examples to show you how to use
34854the Inline Assembler.  Although it focuses on the Intel x86,
34855the general approach applies also to other processors.
34856It is assumed that you are familiar with Ada
34857and with assembly language programming.
34858
34859@menu
34860* Basic Assembler Syntax:: 
34861* A Simple Example of Inline Assembler:: 
34862* Output Variables in Inline Assembler:: 
34863* Input Variables in Inline Assembler:: 
34864* Inlining Inline Assembler Code:: 
34865* Other Asm Functionality:: 
34866
34867@end menu
34868
34869@node Basic Assembler Syntax,A Simple Example of Inline Assembler,,Inline Assembler
34870@anchor{gnat_ugn/inline_assembler id2}@anchor{2ce}@anchor{gnat_ugn/inline_assembler basic-assembler-syntax}@anchor{2cf}
34871@section Basic Assembler Syntax
34872
34873
34874The assembler used by GNAT and gcc is based not on the Intel assembly
34875language, but rather on a language that descends from the AT&T Unix
34876assembler @emph{as} (and which is often referred to as 'AT&T syntax').
34877The following table summarizes the main features of @emph{as} syntax
34878and points out the differences from the Intel conventions.
34879See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
34880pre-processor) documentation for further information.
34881
34882
34883@display
34884@emph{Register names}@w{ }
34885@display
34886gcc / @emph{as}: Prefix with '%'; for example @cite{%eax}@w{ }
34887Intel: No extra punctuation; for example @cite{eax}@w{ }
34888@end display
34889@end display
34890
34891
34892
34893
34894@display
34895@emph{Immediate operand}@w{ }
34896@display
34897gcc / @emph{as}: Prefix with '$'; for example @cite{$4}@w{ }
34898Intel: No extra punctuation; for example @cite{4}@w{ }
34899@end display
34900@end display
34901
34902
34903
34904
34905@display
34906@emph{Address}@w{ }
34907@display
34908gcc / @emph{as}: Prefix with '$'; for example @cite{$loc}@w{ }
34909Intel: No extra punctuation; for example @cite{loc}@w{ }
34910@end display
34911@end display
34912
34913
34914
34915
34916@display
34917@emph{Memory contents}@w{ }
34918@display
34919gcc / @emph{as}: No extra punctuation; for example @cite{loc}@w{ }
34920Intel: Square brackets; for example @cite{[loc]}@w{ }
34921@end display
34922@end display
34923
34924
34925
34926
34927@display
34928@emph{Register contents}@w{ }
34929@display
34930gcc / @emph{as}: Parentheses; for example @cite{(%eax)}@w{ }
34931Intel: Square brackets; for example @cite{[eax]}@w{ }
34932@end display
34933@end display
34934
34935
34936
34937
34938@display
34939@emph{Hexadecimal numbers}@w{ }
34940@display
34941gcc / @emph{as}: Leading '0x' (C language syntax); for example @cite{0xA0}@w{ }
34942Intel: Trailing 'h'; for example @cite{A0h}@w{ }
34943@end display
34944@end display
34945
34946
34947
34948
34949@display
34950@emph{Operand size}@w{ }
34951@display
34952gcc / @emph{as}: Explicit in op code; for example @cite{movw} to move a 16-bit word@w{ }
34953Intel: Implicit, deduced by assembler; for example @cite{mov}@w{ }
34954@end display
34955@end display
34956
34957
34958
34959
34960@display
34961@emph{Instruction repetition}@w{ }
34962@display
34963gcc / @emph{as}: Split into two lines; for example@w{ }
34964@display
34965@cite{rep}@w{ }
34966@cite{stosl}@w{ }
34967@end display
34968Intel: Keep on one line; for example @cite{rep stosl}@w{ }
34969@end display
34970@end display
34971
34972
34973
34974
34975@display
34976@emph{Order of operands}@w{ }
34977@display
34978gcc / @emph{as}: Source first; for example @cite{movw $4@comma{} %eax}@w{ }
34979Intel: Destination first; for example @cite{mov eax@comma{} 4}@w{ }
34980@end display
34981@end display
34982
34983
34984
34985@node A Simple Example of Inline Assembler,Output Variables in Inline Assembler,Basic Assembler Syntax,Inline Assembler
34986@anchor{gnat_ugn/inline_assembler a-simple-example-of-inline-assembler}@anchor{2d0}@anchor{gnat_ugn/inline_assembler id3}@anchor{2d1}
34987@section A Simple Example of Inline Assembler
34988
34989
34990The following example will generate a single assembly language statement,
34991@cite{nop}, which does nothing.  Despite its lack of run-time effect,
34992the example will be useful in illustrating the basics of
34993the Inline Assembler facility.
34994
34995@quotation
34996
34997@example
34998with System.Machine_Code; use System.Machine_Code;
34999procedure Nothing is
35000begin
35001   Asm ("nop");
35002end Nothing;
35003@end example
35004@end quotation
35005
35006@cite{Asm} is a procedure declared in package @cite{System.Machine_Code};
35007here it takes one parameter, a @emph{template string} that must be a static
35008expression and that will form the generated instruction.
35009@cite{Asm} may be regarded as a compile-time procedure that parses
35010the template string and additional parameters (none here),
35011from which it generates a sequence of assembly language instructions.
35012
35013The examples in this chapter will illustrate several of the forms
35014for invoking @cite{Asm}; a complete specification of the syntax
35015is found in the @cite{Machine_Code_Insertions} section of the
35016@cite{GNAT Reference Manual}.
35017
35018Under the standard GNAT conventions, the @cite{Nothing} procedure
35019should be in a file named @code{nothing.adb}.
35020You can build the executable in the usual way:
35021
35022@quotation
35023
35024@example
35025$ gnatmake nothing
35026@end example
35027@end quotation
35028
35029However, the interesting aspect of this example is not its run-time behavior
35030but rather the generated assembly code.
35031To see this output, invoke the compiler as follows:
35032
35033@quotation
35034
35035@example
35036$  gcc -c -S -fomit-frame-pointer -gnatp nothing.adb
35037@end example
35038@end quotation
35039
35040where the options are:
35041
35042
35043@itemize *
35044
35045@item 
35046
35047@table @asis
35048
35049@item @code{-c}
35050
35051compile only (no bind or link)
35052@end table
35053
35054@item 
35055
35056@table @asis
35057
35058@item @code{-S}
35059
35060generate assembler listing
35061@end table
35062
35063@item 
35064
35065@table @asis
35066
35067@item @code{-fomit-frame-pointer}
35068
35069do not set up separate stack frames
35070@end table
35071
35072@item 
35073
35074@table @asis
35075
35076@item @code{-gnatp}
35077
35078do not add runtime checks
35079@end table
35080@end itemize
35081
35082This gives a human-readable assembler version of the code. The resulting
35083file will have the same name as the Ada source file, but with a @cite{.s}
35084extension. In our example, the file @code{nothing.s} has the following
35085contents:
35086
35087@quotation
35088
35089@example
35090.file "nothing.adb"
35091gcc2_compiled.:
35092___gnu_compiled_ada:
35093.text
35094   .align 4
35095.globl __ada_nothing
35096__ada_nothing:
35097#APP
35098   nop
35099#NO_APP
35100   jmp L1
35101   .align 2,0x90
35102L1:
35103   ret
35104@end example
35105@end quotation
35106
35107The assembly code you included is clearly indicated by
35108the compiler, between the @cite{#APP} and @cite{#NO_APP}
35109delimiters. The character before the 'APP' and 'NOAPP'
35110can differ on different targets. For example, GNU/Linux uses '#APP' while
35111on NT you will see '/APP'.
35112
35113If you make a mistake in your assembler code (such as using the
35114wrong size modifier, or using a wrong operand for the instruction) GNAT
35115will report this error in a temporary file, which will be deleted when
35116the compilation is finished.  Generating an assembler file will help
35117in such cases, since you can assemble this file separately using the
35118@emph{as} assembler that comes with gcc.
35119
35120Assembling the file using the command
35121
35122@quotation
35123
35124@example
35125$ as nothing.s
35126@end example
35127@end quotation
35128
35129will give you error messages whose lines correspond to the assembler
35130input file, so you can easily find and correct any mistakes you made.
35131If there are no errors, @emph{as} will generate an object file
35132@code{nothing.out}.
35133
35134@node Output Variables in Inline Assembler,Input Variables in Inline Assembler,A Simple Example of Inline Assembler,Inline Assembler
35135@anchor{gnat_ugn/inline_assembler id4}@anchor{2d2}@anchor{gnat_ugn/inline_assembler output-variables-in-inline-assembler}@anchor{2d3}
35136@section Output Variables in Inline Assembler
35137
35138
35139The examples in this section, showing how to access the processor flags,
35140illustrate how to specify the destination operands for assembly language
35141statements.
35142
35143@quotation
35144
35145@example
35146with Interfaces; use Interfaces;
35147with Ada.Text_IO; use Ada.Text_IO;
35148with System.Machine_Code; use System.Machine_Code;
35149procedure Get_Flags is
35150   Flags : Unsigned_32;
35151   use ASCII;
35152begin
35153   Asm ("pushfl"          & LF & HT & -- push flags on stack
35154        "popl %%eax"      & LF & HT & -- load eax with flags
35155        "movl %%eax, %0",             -- store flags in variable
35156        Outputs => Unsigned_32'Asm_Output ("=g", Flags));
35157   Put_Line ("Flags register:" & Flags'Img);
35158end Get_Flags;
35159@end example
35160@end quotation
35161
35162In order to have a nicely aligned assembly listing, we have separated
35163multiple assembler statements in the Asm template string with linefeed
35164(ASCII.LF) and horizontal tab (ASCII.HT) characters.
35165The resulting section of the assembly output file is:
35166
35167@quotation
35168
35169@example
35170#APP
35171   pushfl
35172   popl %eax
35173   movl %eax, -40(%ebp)
35174#NO_APP
35175@end example
35176@end quotation
35177
35178It would have been legal to write the Asm invocation as:
35179
35180@quotation
35181
35182@example
35183Asm ("pushfl popl %%eax movl %%eax, %0")
35184@end example
35185@end quotation
35186
35187but in the generated assembler file, this would come out as:
35188
35189@quotation
35190
35191@example
35192#APP
35193   pushfl popl %eax movl %eax, -40(%ebp)
35194#NO_APP
35195@end example
35196@end quotation
35197
35198which is not so convenient for the human reader.
35199
35200We use Ada comments
35201at the end of each line to explain what the assembler instructions
35202actually do.  This is a useful convention.
35203
35204When writing Inline Assembler instructions, you need to precede each register
35205and variable name with a percent sign.  Since the assembler already requires
35206a percent sign at the beginning of a register name, you need two consecutive
35207percent signs for such names in the Asm template string, thus @cite{%%eax}.
35208In the generated assembly code, one of the percent signs will be stripped off.
35209
35210Names such as @cite{%0}, @cite{%1}, @cite{%2}, etc., denote input or output
35211variables: operands you later define using @cite{Input} or @cite{Output}
35212parameters to @cite{Asm}.
35213An output variable is illustrated in
35214the third statement in the Asm template string:
35215
35216@quotation
35217
35218@example
35219movl %%eax, %0
35220@end example
35221@end quotation
35222
35223The intent is to store the contents of the eax register in a variable that can
35224be accessed in Ada.  Simply writing @cite{movl %%eax@comma{} Flags} would not
35225necessarily work, since the compiler might optimize by using a register
35226to hold Flags, and the expansion of the @cite{movl} instruction would not be
35227aware of this optimization.  The solution is not to store the result directly
35228but rather to advise the compiler to choose the correct operand form;
35229that is the purpose of the @cite{%0} output variable.
35230
35231Information about the output variable is supplied in the @cite{Outputs}
35232parameter to @cite{Asm}:
35233
35234@quotation
35235
35236@example
35237Outputs => Unsigned_32'Asm_Output ("=g", Flags));
35238@end example
35239@end quotation
35240
35241The output is defined by the @cite{Asm_Output} attribute of the target type;
35242the general format is
35243
35244@quotation
35245
35246@example
35247Type'Asm_Output (constraint_string, variable_name)
35248@end example
35249@end quotation
35250
35251The constraint string directs the compiler how
35252to store/access the associated variable.  In the example
35253
35254@quotation
35255
35256@example
35257Unsigned_32'Asm_Output ("=m", Flags);
35258@end example
35259@end quotation
35260
35261the @cite{"m"} (memory) constraint tells the compiler that the variable
35262@cite{Flags} should be stored in a memory variable, thus preventing
35263the optimizer from keeping it in a register.  In contrast,
35264
35265@quotation
35266
35267@example
35268Unsigned_32'Asm_Output ("=r", Flags);
35269@end example
35270@end quotation
35271
35272uses the @cite{"r"} (register) constraint, telling the compiler to
35273store the variable in a register.
35274
35275If the constraint is preceded by the equal character '=', it tells
35276the compiler that the variable will be used to store data into it.
35277
35278In the @cite{Get_Flags} example, we used the @cite{"g"} (global) constraint,
35279allowing the optimizer to choose whatever it deems best.
35280
35281There are a fairly large number of constraints, but the ones that are
35282most useful (for the Intel x86 processor) are the following:
35283
35284@quotation
35285
35286
35287@multitable {xxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
35288@item
35289
35290@emph{=}
35291
35292@tab
35293
35294output constraint
35295
35296@item
35297
35298@emph{g}
35299
35300@tab
35301
35302global (i.e., can be stored anywhere)
35303
35304@item
35305
35306@emph{m}
35307
35308@tab
35309
35310in memory
35311
35312@item
35313
35314@emph{I}
35315
35316@tab
35317
35318a constant
35319
35320@item
35321
35322@emph{a}
35323
35324@tab
35325
35326use eax
35327
35328@item
35329
35330@emph{b}
35331
35332@tab
35333
35334use ebx
35335
35336@item
35337
35338@emph{c}
35339
35340@tab
35341
35342use ecx
35343
35344@item
35345
35346@emph{d}
35347
35348@tab
35349
35350use edx
35351
35352@item
35353
35354@emph{S}
35355
35356@tab
35357
35358use esi
35359
35360@item
35361
35362@emph{D}
35363
35364@tab
35365
35366use edi
35367
35368@item
35369
35370@emph{r}
35371
35372@tab
35373
35374use one of eax, ebx, ecx or edx
35375
35376@item
35377
35378@emph{q}
35379
35380@tab
35381
35382use one of eax, ebx, ecx, edx, esi or edi
35383
35384@end multitable
35385
35386@end quotation
35387
35388The full set of constraints is described in the gcc and @emph{as}
35389documentation; note that it is possible to combine certain constraints
35390in one constraint string.
35391
35392You specify the association of an output variable with an assembler operand
35393through the @code{%@emph{n}} notation, where @emph{n} is a non-negative
35394integer.  Thus in
35395
35396@quotation
35397
35398@example
35399Asm ("pushfl"          & LF & HT & -- push flags on stack
35400     "popl %%eax"      & LF & HT & -- load eax with flags
35401     "movl %%eax, %0",             -- store flags in variable
35402     Outputs => Unsigned_32'Asm_Output ("=g", Flags));
35403@end example
35404@end quotation
35405
35406@cite{%0} will be replaced in the expanded code by the appropriate operand,
35407whatever
35408the compiler decided for the @cite{Flags} variable.
35409
35410In general, you may have any number of output variables:
35411
35412
35413@itemize *
35414
35415@item 
35416Count the operands starting at 0; thus @cite{%0}, @cite{%1}, etc.
35417
35418@item 
35419Specify the @cite{Outputs} parameter as a parenthesized comma-separated list
35420of @cite{Asm_Output} attributes
35421@end itemize
35422
35423For example:
35424
35425@quotation
35426
35427@example
35428Asm ("movl %%eax, %0" & LF & HT &
35429     "movl %%ebx, %1" & LF & HT &
35430     "movl %%ecx, %2",
35431     Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
35432                 Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
35433                 Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
35434@end example
35435@end quotation
35436
35437where @cite{Var_A}, @cite{Var_B}, and @cite{Var_C} are variables
35438in the Ada program.
35439
35440As a variation on the @cite{Get_Flags} example, we can use the constraints
35441string to direct the compiler to store the eax register into the @cite{Flags}
35442variable, instead of including the store instruction explicitly in the
35443@cite{Asm} template string:
35444
35445@quotation
35446
35447@example
35448with Interfaces; use Interfaces;
35449with Ada.Text_IO; use Ada.Text_IO;
35450with System.Machine_Code; use System.Machine_Code;
35451procedure Get_Flags_2 is
35452   Flags : Unsigned_32;
35453   use ASCII;
35454begin
35455   Asm ("pushfl"      & LF & HT & -- push flags on stack
35456        "popl %%eax",             -- save flags in eax
35457        Outputs => Unsigned_32'Asm_Output ("=a", Flags));
35458   Put_Line ("Flags register:" & Flags'Img);
35459end Get_Flags_2;
35460@end example
35461@end quotation
35462
35463The @cite{"a"} constraint tells the compiler that the @cite{Flags}
35464variable will come from the eax register. Here is the resulting code:
35465
35466@quotation
35467
35468@example
35469#APP
35470   pushfl
35471   popl %eax
35472#NO_APP
35473   movl %eax,-40(%ebp)
35474@end example
35475@end quotation
35476
35477The compiler generated the store of eax into Flags after
35478expanding the assembler code.
35479
35480Actually, there was no need to pop the flags into the eax register;
35481more simply, we could just pop the flags directly into the program variable:
35482
35483@quotation
35484
35485@example
35486with Interfaces; use Interfaces;
35487with Ada.Text_IO; use Ada.Text_IO;
35488with System.Machine_Code; use System.Machine_Code;
35489procedure Get_Flags_3 is
35490   Flags : Unsigned_32;
35491   use ASCII;
35492begin
35493   Asm ("pushfl"  & LF & HT & -- push flags on stack
35494        "pop %0",             -- save flags in Flags
35495        Outputs => Unsigned_32'Asm_Output ("=g", Flags));
35496   Put_Line ("Flags register:" & Flags'Img);
35497end Get_Flags_3;
35498@end example
35499@end quotation
35500
35501@node Input Variables in Inline Assembler,Inlining Inline Assembler Code,Output Variables in Inline Assembler,Inline Assembler
35502@anchor{gnat_ugn/inline_assembler id5}@anchor{2d4}@anchor{gnat_ugn/inline_assembler input-variables-in-inline-assembler}@anchor{2d5}
35503@section Input Variables in Inline Assembler
35504
35505
35506The example in this section illustrates how to specify the source operands
35507for assembly language statements.
35508The program simply increments its input value by 1:
35509
35510@quotation
35511
35512@example
35513with Interfaces; use Interfaces;
35514with Ada.Text_IO; use Ada.Text_IO;
35515with System.Machine_Code; use System.Machine_Code;
35516procedure Increment is
35517
35518   function Incr (Value : Unsigned_32) return Unsigned_32 is
35519      Result : Unsigned_32;
35520   begin
35521      Asm ("incl %0",
35522           Outputs => Unsigned_32'Asm_Output ("=a", Result),
35523           Inputs  => Unsigned_32'Asm_Input ("a", Value));
35524      return Result;
35525   end Incr;
35526
35527   Value : Unsigned_32;
35528
35529begin
35530   Value := 5;
35531   Put_Line ("Value before is" & Value'Img);
35532   Value := Incr (Value);
35533  Put_Line ("Value after is" & Value'Img);
35534end Increment;
35535@end example
35536@end quotation
35537
35538The @cite{Outputs} parameter to @cite{Asm} specifies
35539that the result will be in the eax register and that it is to be stored
35540in the @cite{Result} variable.
35541
35542The @cite{Inputs} parameter looks much like the @cite{Outputs} parameter,
35543but with an @cite{Asm_Input} attribute.
35544The @cite{"="} constraint, indicating an output value, is not present.
35545
35546You can have multiple input variables, in the same way that you can have more
35547than one output variable.
35548
35549The parameter count (%0, %1) etc, still starts at the first output statement,
35550and continues with the input statements.
35551
35552Just as the @cite{Outputs} parameter causes the register to be stored into the
35553target variable after execution of the assembler statements, so does the
35554@cite{Inputs} parameter cause its variable to be loaded into the register
35555before execution of the assembler statements.
35556
35557Thus the effect of the @cite{Asm} invocation is:
35558
35559
35560@itemize *
35561
35562@item 
35563load the 32-bit value of @cite{Value} into eax
35564
35565@item 
35566execute the @cite{incl %eax} instruction
35567
35568@item 
35569store the contents of eax into the @cite{Result} variable
35570@end itemize
35571
35572The resulting assembler file (with @emph{-O2} optimization) contains:
35573
35574@quotation
35575
35576@example
35577_increment__incr.1:
35578   subl $4,%esp
35579   movl 8(%esp),%eax
35580#APP
35581   incl %eax
35582#NO_APP
35583   movl %eax,%edx
35584   movl %ecx,(%esp)
35585   addl $4,%esp
35586   ret
35587@end example
35588@end quotation
35589
35590@node Inlining Inline Assembler Code,Other Asm Functionality,Input Variables in Inline Assembler,Inline Assembler
35591@anchor{gnat_ugn/inline_assembler id6}@anchor{2d6}@anchor{gnat_ugn/inline_assembler inlining-inline-assembler-code}@anchor{2d7}
35592@section Inlining Inline Assembler Code
35593
35594
35595For a short subprogram such as the @cite{Incr} function in the previous
35596section, the overhead of the call and return (creating / deleting the stack
35597frame) can be significant, compared to the amount of code in the subprogram
35598body.  A solution is to apply Ada's @cite{Inline} pragma to the subprogram,
35599which directs the compiler to expand invocations of the subprogram at the
35600point(s) of call, instead of setting up a stack frame for out-of-line calls.
35601Here is the resulting program:
35602
35603@quotation
35604
35605@example
35606with Interfaces; use Interfaces;
35607with Ada.Text_IO; use Ada.Text_IO;
35608with System.Machine_Code; use System.Machine_Code;
35609procedure Increment_2 is
35610
35611   function Incr (Value : Unsigned_32) return Unsigned_32 is
35612      Result : Unsigned_32;
35613   begin
35614      Asm ("incl %0",
35615           Outputs => Unsigned_32'Asm_Output ("=a", Result),
35616           Inputs  => Unsigned_32'Asm_Input ("a", Value));
35617      return Result;
35618   end Incr;
35619   pragma Inline (Increment);
35620
35621   Value : Unsigned_32;
35622
35623begin
35624   Value := 5;
35625   Put_Line ("Value before is" & Value'Img);
35626   Value := Increment (Value);
35627   Put_Line ("Value after is" & Value'Img);
35628end Increment_2;
35629@end example
35630@end quotation
35631
35632Compile the program with both optimization (@emph{-O2}) and inlining
35633(@emph{-gnatn}) enabled.
35634
35635The @cite{Incr} function is still compiled as usual, but at the
35636point in @cite{Increment} where our function used to be called:
35637
35638@quotation
35639
35640@example
35641pushl %edi
35642call _increment__incr.1
35643@end example
35644@end quotation
35645
35646the code for the function body directly appears:
35647
35648@quotation
35649
35650@example
35651movl %esi,%eax
35652#APP
35653   incl %eax
35654#NO_APP
35655   movl %eax,%edx
35656@end example
35657@end quotation
35658
35659thus saving the overhead of stack frame setup and an out-of-line call.
35660
35661@node Other Asm Functionality,,Inlining Inline Assembler Code,Inline Assembler
35662@anchor{gnat_ugn/inline_assembler other-asm-functionality}@anchor{2d8}@anchor{gnat_ugn/inline_assembler id7}@anchor{2d9}
35663@section Other @cite{Asm} Functionality
35664
35665
35666This section describes two important parameters to the @cite{Asm}
35667procedure: @cite{Clobber}, which identifies register usage;
35668and @cite{Volatile}, which inhibits unwanted optimizations.
35669
35670@menu
35671* The Clobber Parameter:: 
35672* The Volatile Parameter:: 
35673
35674@end menu
35675
35676@node The Clobber Parameter,The Volatile Parameter,,Other Asm Functionality
35677@anchor{gnat_ugn/inline_assembler the-clobber-parameter}@anchor{2da}@anchor{gnat_ugn/inline_assembler id8}@anchor{2db}
35678@subsection The @cite{Clobber} Parameter
35679
35680
35681One of the dangers of intermixing assembly language and a compiled language
35682such as Ada is that the compiler needs to be aware of which registers are
35683being used by the assembly code.  In some cases, such as the earlier examples,
35684the constraint string is sufficient to indicate register usage (e.g.,
35685@cite{"a"} for
35686the eax register).  But more generally, the compiler needs an explicit
35687identification of the registers that are used by the Inline Assembly
35688statements.
35689
35690Using a register that the compiler doesn't know about
35691could be a side effect of an instruction (like @cite{mull}
35692storing its result in both eax and edx).
35693It can also arise from explicit register usage in your
35694assembly code; for example:
35695
35696@quotation
35697
35698@example
35699Asm ("movl %0, %%ebx" & LF & HT &
35700     "movl %%ebx, %1",
35701     Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
35702     Inputs  => Unsigned_32'Asm_Input  ("g", Var_In));
35703@end example
35704@end quotation
35705
35706where the compiler (since it does not analyze the @cite{Asm} template string)
35707does not know you are using the ebx register.
35708
35709In such cases you need to supply the @cite{Clobber} parameter to @cite{Asm},
35710to identify the registers that will be used by your assembly code:
35711
35712@quotation
35713
35714@example
35715Asm ("movl %0, %%ebx" & LF & HT &
35716     "movl %%ebx, %1",
35717     Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
35718     Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
35719     Clobber => "ebx");
35720@end example
35721@end quotation
35722
35723The Clobber parameter is a static string expression specifying the
35724register(s) you are using.  Note that register names are @emph{not} prefixed
35725by a percent sign. Also, if more than one register is used then their names
35726are separated by commas; e.g., @cite{"eax@comma{} ebx"}
35727
35728The @cite{Clobber} parameter has several additional uses:
35729
35730
35731@itemize *
35732
35733@item 
35734Use 'register' name @cite{cc} to indicate that flags might have changed
35735
35736@item 
35737Use 'register' name @cite{memory} if you changed a memory location
35738@end itemize
35739
35740@node The Volatile Parameter,,The Clobber Parameter,Other Asm Functionality
35741@anchor{gnat_ugn/inline_assembler the-volatile-parameter}@anchor{2dc}@anchor{gnat_ugn/inline_assembler id9}@anchor{2dd}
35742@subsection The @cite{Volatile} Parameter
35743
35744
35745@geindex Volatile parameter
35746
35747Compiler optimizations in the presence of Inline Assembler may sometimes have
35748unwanted effects.  For example, when an @cite{Asm} invocation with an input
35749variable is inside a loop, the compiler might move the loading of the input
35750variable outside the loop, regarding it as a one-time initialization.
35751
35752If this effect is not desired, you can disable such optimizations by setting
35753the @cite{Volatile} parameter to @cite{True}; for example:
35754
35755@quotation
35756
35757@example
35758Asm ("movl %0, %%ebx" & LF & HT &
35759     "movl %%ebx, %1",
35760     Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
35761     Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
35762     Clobber  => "ebx",
35763     Volatile => True);
35764@end example
35765@end quotation
35766
35767By default, @cite{Volatile} is set to @cite{False} unless there is no
35768@cite{Outputs} parameter.
35769
35770Although setting @cite{Volatile} to @cite{True} prevents unwanted
35771optimizations, it will also disable other optimizations that might be
35772important for efficiency. In general, you should set @cite{Volatile}
35773to @cite{True} only if the compiler's optimizations have created
35774problems.
35775
35776@node GNU Free Documentation License,Index,Inline Assembler,Top
35777@anchor{share/gnu_free_documentation_license gnu-fdl}@anchor{1}@anchor{share/gnu_free_documentation_license doc}@anchor{2de}@anchor{share/gnu_free_documentation_license gnu-free-documentation-license}@anchor{2df}
35778@chapter GNU Free Documentation License
35779
35780
35781Version 1.3, 3 November 2008
35782
35783Copyright  2000, 2001, 2002, 2007, 2008  Free Software Foundation, Inc
35784@indicateurl{http://fsf.org/}
35785
35786Everyone is permitted to copy and distribute verbatim copies of this
35787license document, but changing it is not allowed.
35788
35789@strong{Preamble}
35790
35791The purpose of this License is to make a manual, textbook, or other
35792functional and useful document "free" in the sense of freedom: to
35793assure everyone the effective freedom to copy and redistribute it,
35794with or without modifying it, either commercially or noncommercially.
35795Secondarily, this License preserves for the author and publisher a way
35796to get credit for their work, while not being considered responsible
35797for modifications made by others.
35798
35799This License is a kind of "copyleft", which means that derivative
35800works of the document must themselves be free in the same sense.  It
35801complements the GNU General Public License, which is a copyleft
35802license designed for free software.
35803
35804We have designed this License in order to use it for manuals for free
35805software, because free software needs free documentation: a free
35806program should come with manuals providing the same freedoms that the
35807software does.  But this License is not limited to software manuals;
35808it can be used for any textual work, regardless of subject matter or
35809whether it is published as a printed book.  We recommend this License
35810principally for works whose purpose is instruction or reference.
35811
35812@strong{1. APPLICABILITY AND DEFINITIONS}
35813
35814This License applies to any manual or other work, in any medium, that
35815contains a notice placed by the copyright holder saying it can be
35816distributed under the terms of this License.  Such a notice grants a
35817world-wide, royalty-free license, unlimited in duration, to use that
35818work under the conditions stated herein.  The @strong{Document}, below,
35819refers to any such manual or work.  Any member of the public is a
35820licensee, and is addressed as "@strong{you}".  You accept the license if you
35821copy, modify or distribute the work in a way requiring permission
35822under copyright law.
35823
35824A "@strong{Modified Version}" of the Document means any work containing the
35825Document or a portion of it, either copied verbatim, or with
35826modifications and/or translated into another language.
35827
35828A "@strong{Secondary Section}" is a named appendix or a front-matter section of
35829the Document that deals exclusively with the relationship of the
35830publishers or authors of the Document to the Document's overall subject
35831(or to related matters) and contains nothing that could fall directly
35832within that overall subject.  (Thus, if the Document is in part a
35833textbook of mathematics, a Secondary Section may not explain any
35834mathematics.)  The relationship could be a matter of historical
35835connection with the subject or with related matters, or of legal,
35836commercial, philosophical, ethical or political position regarding
35837them.
35838
35839The "@strong{Invariant Sections}" are certain Secondary Sections whose titles
35840are designated, as being those of Invariant Sections, in the notice
35841that says that the Document is released under this License.  If a
35842section does not fit the above definition of Secondary then it is not
35843allowed to be designated as Invariant.  The Document may contain zero
35844Invariant Sections.  If the Document does not identify any Invariant
35845Sections then there are none.
35846
35847The "@strong{Cover Texts}" are certain short passages of text that are listed,
35848as Front-Cover Texts or Back-Cover Texts, in the notice that says that
35849the Document is released under this License.  A Front-Cover Text may
35850be at most 5 words, and a Back-Cover Text may be at most 25 words.
35851
35852A "@strong{Transparent}" copy of the Document means a machine-readable copy,
35853represented in a format whose specification is available to the
35854general public, that is suitable for revising the document
35855straightforwardly with generic text editors or (for images composed of
35856pixels) generic paint programs or (for drawings) some widely available
35857drawing editor, and that is suitable for input to text formatters or
35858for automatic translation to a variety of formats suitable for input
35859to text formatters.  A copy made in an otherwise Transparent file
35860format whose markup, or absence of markup, has been arranged to thwart
35861or discourage subsequent modification by readers is not Transparent.
35862An image format is not Transparent if used for any substantial amount
35863of text.  A copy that is not "Transparent" is called @strong{Opaque}.
35864
35865Examples of suitable formats for Transparent copies include plain
35866ASCII without markup, Texinfo input format, LaTeX input format, SGML
35867or XML using a publicly available DTD, and standard-conforming simple
35868HTML, PostScript or PDF designed for human modification.  Examples of
35869transparent image formats include PNG, XCF and JPG.  Opaque formats
35870include proprietary formats that can be read and edited only by
35871proprietary word processors, SGML or XML for which the DTD and/or
35872processing tools are not generally available, and the
35873machine-generated HTML, PostScript or PDF produced by some word
35874processors for output purposes only.
35875
35876The "@strong{Title Page}" means, for a printed book, the title page itself,
35877plus such following pages as are needed to hold, legibly, the material
35878this License requires to appear in the title page.  For works in
35879formats which do not have any title page as such, "Title Page" means
35880the text near the most prominent appearance of the work's title,
35881preceding the beginning of the body of the text.
35882
35883The "@strong{publisher}" means any person or entity that distributes
35884copies of the Document to the public.
35885
35886A section "@strong{Entitled XYZ}" means a named subunit of the Document whose
35887title either is precisely XYZ or contains XYZ in parentheses following
35888text that translates XYZ in another language.  (Here XYZ stands for a
35889specific section name mentioned below, such as "@strong{Acknowledgements}",
35890"@strong{Dedications}", "@strong{Endorsements}", or "@strong{History}".)
35891To "@strong{Preserve the Title}"
35892of such a section when you modify the Document means that it remains a
35893section "Entitled XYZ" according to this definition.
35894
35895The Document may include Warranty Disclaimers next to the notice which
35896states that this License applies to the Document.  These Warranty
35897Disclaimers are considered to be included by reference in this
35898License, but only as regards disclaiming warranties: any other
35899implication that these Warranty Disclaimers may have is void and has
35900no effect on the meaning of this License.
35901
35902@strong{2. VERBATIM COPYING}
35903
35904You may copy and distribute the Document in any medium, either
35905commercially or noncommercially, provided that this License, the
35906copyright notices, and the license notice saying this License applies
35907to the Document are reproduced in all copies, and that you add no other
35908conditions whatsoever to those of this License.  You may not use
35909technical measures to obstruct or control the reading or further
35910copying of the copies you make or distribute.  However, you may accept
35911compensation in exchange for copies.  If you distribute a large enough
35912number of copies you must also follow the conditions in section 3.
35913
35914You may also lend copies, under the same conditions stated above, and
35915you may publicly display copies.
35916
35917@strong{3. COPYING IN QUANTITY}
35918
35919If you publish printed copies (or copies in media that commonly have
35920printed covers) of the Document, numbering more than 100, and the
35921Document's license notice requires Cover Texts, you must enclose the
35922copies in covers that carry, clearly and legibly, all these Cover
35923Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on
35924the back cover.  Both covers must also clearly and legibly identify
35925you as the publisher of these copies.  The front cover must present
35926the full title with all words of the title equally prominent and
35927visible.  You may add other material on the covers in addition.
35928Copying with changes limited to the covers, as long as they preserve
35929the title of the Document and satisfy these conditions, can be treated
35930as verbatim copying in other respects.
35931
35932If the required texts for either cover are too voluminous to fit
35933legibly, you should put the first ones listed (as many as fit
35934reasonably) on the actual cover, and continue the rest onto adjacent
35935pages.
35936
35937If you publish or distribute Opaque copies of the Document numbering
35938more than 100, you must either include a machine-readable Transparent
35939copy along with each Opaque copy, or state in or with each Opaque copy
35940a computer-network location from which the general network-using
35941public has access to download using public-standard network protocols
35942a complete Transparent copy of the Document, free of added material.
35943If you use the latter option, you must take reasonably prudent steps,
35944when you begin distribution of Opaque copies in quantity, to ensure
35945that this Transparent copy will remain thus accessible at the stated
35946location until at least one year after the last time you distribute an
35947Opaque copy (directly or through your agents or retailers) of that
35948edition to the public.
35949
35950It is requested, but not required, that you contact the authors of the
35951Document well before redistributing any large number of copies, to give
35952them a chance to provide you with an updated version of the Document.
35953
35954@strong{4. MODIFICATIONS}
35955
35956You may copy and distribute a Modified Version of the Document under
35957the conditions of sections 2 and 3 above, provided that you release
35958the Modified Version under precisely this License, with the Modified
35959Version filling the role of the Document, thus licensing distribution
35960and modification of the Modified Version to whoever possesses a copy
35961of it.  In addition, you must do these things in the Modified Version:
35962
35963
35964@enumerate A
35965
35966@item 
35967Use in the Title Page (and on the covers, if any) a title distinct
35968from that of the Document, and from those of previous versions
35969(which should, if there were any, be listed in the History section
35970of the Document).  You may use the same title as a previous version
35971if the original publisher of that version gives permission.
35972
35973@item 
35974List on the Title Page, as authors, one or more persons or entities
35975responsible for authorship of the modifications in the Modified
35976Version, together with at least five of the principal authors of the
35977Document (all of its principal authors, if it has fewer than five),
35978unless they release you from this requirement.
35979
35980@item 
35981State on the Title page the name of the publisher of the
35982Modified Version, as the publisher.
35983
35984@item 
35985Preserve all the copyright notices of the Document.
35986
35987@item 
35988Add an appropriate copyright notice for your modifications
35989adjacent to the other copyright notices.
35990
35991@item 
35992Include, immediately after the copyright notices, a license notice
35993giving the public permission to use the Modified Version under the
35994terms of this License, in the form shown in the Addendum below.
35995
35996@item 
35997Preserve in that license notice the full lists of Invariant Sections
35998and required Cover Texts given in the Document's license notice.
35999
36000@item 
36001Include an unaltered copy of this License.
36002
36003@item 
36004Preserve the section Entitled "History", Preserve its Title, and add
36005to it an item stating at least the title, year, new authors, and
36006publisher of the Modified Version as given on the Title Page.  If
36007there is no section Entitled "History" in the Document, create one
36008stating the title, year, authors, and publisher of the Document as
36009given on its Title Page, then add an item describing the Modified
36010Version as stated in the previous sentence.
36011
36012@item 
36013Preserve the network location, if any, given in the Document for
36014public access to a Transparent copy of the Document, and likewise
36015the network locations given in the Document for previous versions
36016it was based on.  These may be placed in the "History" section.
36017You may omit a network location for a work that was published at
36018least four years before the Document itself, or if the original
36019publisher of the version it refers to gives permission.
36020
36021@item 
36022For any section Entitled "Acknowledgements" or "Dedications",
36023Preserve the Title of the section, and preserve in the section all
36024the substance and tone of each of the contributor acknowledgements
36025and/or dedications given therein.
36026
36027@item 
36028Preserve all the Invariant Sections of the Document,
36029unaltered in their text and in their titles.  Section numbers
36030or the equivalent are not considered part of the section titles.
36031
36032@item 
36033Delete any section Entitled "Endorsements".  Such a section
36034may not be included in the Modified Version.
36035
36036@item 
36037Do not retitle any existing section to be Entitled "Endorsements"
36038or to conflict in title with any Invariant Section.
36039
36040@item 
36041Preserve any Warranty Disclaimers.
36042@end enumerate
36043
36044If the Modified Version includes new front-matter sections or
36045appendices that qualify as Secondary Sections and contain no material
36046copied from the Document, you may at your option designate some or all
36047of these sections as invariant.  To do this, add their titles to the
36048list of Invariant Sections in the Modified Version's license notice.
36049These titles must be distinct from any other section titles.
36050
36051You may add a section Entitled "Endorsements", provided it contains
36052nothing but endorsements of your Modified Version by various
36053parties---for example, statements of peer review or that the text has
36054been approved by an organization as the authoritative definition of a
36055standard.
36056
36057You may add a passage of up to five words as a Front-Cover Text, and a
36058passage of up to 25 words as a Back-Cover Text, to the end of the list
36059of Cover Texts in the Modified Version.  Only one passage of
36060Front-Cover Text and one of Back-Cover Text may be added by (or
36061through arrangements made by) any one entity.  If the Document already
36062includes a cover text for the same cover, previously added by you or
36063by arrangement made by the same entity you are acting on behalf of,
36064you may not add another; but you may replace the old one, on explicit
36065permission from the previous publisher that added the old one.
36066
36067The author(s) and publisher(s) of the Document do not by this License
36068give permission to use their names for publicity for or to assert or
36069imply endorsement of any Modified Version.
36070
36071@strong{5. COMBINING DOCUMENTS}
36072
36073You may combine the Document with other documents released under this
36074License, under the terms defined in section 4 above for modified
36075versions, provided that you include in the combination all of the
36076Invariant Sections of all of the original documents, unmodified, and
36077list them all as Invariant Sections of your combined work in its
36078license notice, and that you preserve all their Warranty Disclaimers.
36079
36080The combined work need only contain one copy of this License, and
36081multiple identical Invariant Sections may be replaced with a single
36082copy.  If there are multiple Invariant Sections with the same name but
36083different contents, make the title of each such section unique by
36084adding at the end of it, in parentheses, the name of the original
36085author or publisher of that section if known, or else a unique number.
36086Make the same adjustment to the section titles in the list of
36087Invariant Sections in the license notice of the combined work.
36088
36089In the combination, you must combine any sections Entitled "History"
36090in the various original documents, forming one section Entitled
36091"History"; likewise combine any sections Entitled "Acknowledgements",
36092and any sections Entitled "Dedications".  You must delete all sections
36093Entitled "Endorsements".
36094
36095@strong{6. COLLECTIONS OF DOCUMENTS}
36096
36097You may make a collection consisting of the Document and other documents
36098released under this License, and replace the individual copies of this
36099License in the various documents with a single copy that is included in
36100the collection, provided that you follow the rules of this License for
36101verbatim copying of each of the documents in all other respects.
36102
36103You may extract a single document from such a collection, and distribute
36104it individually under this License, provided you insert a copy of this
36105License into the extracted document, and follow this License in all
36106other respects regarding verbatim copying of that document.
36107
36108@strong{7. AGGREGATION WITH INDEPENDENT WORKS}
36109
36110A compilation of the Document or its derivatives with other separate
36111and independent documents or works, in or on a volume of a storage or
36112distribution medium, is called an "aggregate" if the copyright
36113resulting from the compilation is not used to limit the legal rights
36114of the compilation's users beyond what the individual works permit.
36115When the Document is included in an aggregate, this License does not
36116apply to the other works in the aggregate which are not themselves
36117derivative works of the Document.
36118
36119If the Cover Text requirement of section 3 is applicable to these
36120copies of the Document, then if the Document is less than one half of
36121the entire aggregate, the Document's Cover Texts may be placed on
36122covers that bracket the Document within the aggregate, or the
36123electronic equivalent of covers if the Document is in electronic form.
36124Otherwise they must appear on printed covers that bracket the whole
36125aggregate.
36126
36127@strong{8. TRANSLATION}
36128
36129Translation is considered a kind of modification, so you may
36130distribute translations of the Document under the terms of section 4.
36131Replacing Invariant Sections with translations requires special
36132permission from their copyright holders, but you may include
36133translations of some or all Invariant Sections in addition to the
36134original versions of these Invariant Sections.  You may include a
36135translation of this License, and all the license notices in the
36136Document, and any Warranty Disclaimers, provided that you also include
36137the original English version of this License and the original versions
36138of those notices and disclaimers.  In case of a disagreement between
36139the translation and the original version of this License or a notice
36140or disclaimer, the original version will prevail.
36141
36142If a section in the Document is Entitled "Acknowledgements",
36143"Dedications", or "History", the requirement (section 4) to Preserve
36144its Title (section 1) will typically require changing the actual
36145title.
36146
36147@strong{9. TERMINATION}
36148
36149You may not copy, modify, sublicense, or distribute the Document
36150except as expressly provided under this License.  Any attempt
36151otherwise to copy, modify, sublicense, or distribute it is void, and
36152will automatically terminate your rights under this License.
36153
36154However, if you cease all violation of this License, then your license
36155from a particular copyright holder is reinstated (a) provisionally,
36156unless and until the copyright holder explicitly and finally
36157terminates your license, and (b) permanently, if the copyright holder
36158fails to notify you of the violation by some reasonable means prior to
3615960 days after the cessation.
36160
36161Moreover, your license from a particular copyright holder is
36162reinstated permanently if the copyright holder notifies you of the
36163violation by some reasonable means, this is the first time you have
36164received notice of violation of this License (for any work) from that
36165copyright holder, and you cure the violation prior to 30 days after
36166your receipt of the notice.
36167
36168Termination of your rights under this section does not terminate the
36169licenses of parties who have received copies or rights from you under
36170this License.  If your rights have been terminated and not permanently
36171reinstated, receipt of a copy of some or all of the same material does
36172not give you any rights to use it.
36173
36174@strong{10. FUTURE REVISIONS OF THIS LICENSE}
36175
36176The Free Software Foundation may publish new, revised versions
36177of the GNU Free Documentation License from time to time.  Such new
36178versions will be similar in spirit to the present version, but may
36179differ in detail to address new problems or concerns.  See
36180@indicateurl{http://www.gnu.org/copyleft/}.
36181
36182Each version of the License is given a distinguishing version number.
36183If the Document specifies that a particular numbered version of this
36184License "or any later version" applies to it, you have the option of
36185following the terms and conditions either of that specified version or
36186of any later version that has been published (not as a draft) by the
36187Free Software Foundation.  If the Document does not specify a version
36188number of this License, you may choose any version ever published (not
36189as a draft) by the Free Software Foundation.  If the Document
36190specifies that a proxy can decide which future versions of this
36191License can be used, that proxy's public statement of acceptance of a
36192version permanently authorizes you to choose that version for the
36193Document.
36194
36195@strong{11. RELICENSING}
36196
36197"Massive Multiauthor Collaboration Site" (or "MMC Site") means any
36198World Wide Web server that publishes copyrightable works and also
36199provides prominent facilities for anybody to edit those works.  A
36200public wiki that anybody can edit is an example of such a server.  A
36201"Massive Multiauthor Collaboration" (or "MMC") contained in the
36202site means any set of copyrightable works thus published on the MMC
36203site.
36204
36205"CC-BY-SA" means the Creative Commons Attribution-Share Alike 3.0
36206license published by Creative Commons Corporation, a not-for-profit
36207corporation with a principal place of business in San Francisco,
36208California, as well as future copyleft versions of that license
36209published by that same organization.
36210
36211"Incorporate" means to publish or republish a Document, in whole or
36212in part, as part of another Document.
36213
36214An MMC is "eligible for relicensing" if it is licensed under this
36215License, and if all works that were first published under this License
36216somewhere other than this MMC, and subsequently incorporated in whole
36217or in part into the MMC, (1) had no cover texts or invariant sections,
36218and (2) were thus incorporated prior to November 1, 2008.
36219
36220The operator of an MMC Site may republish an MMC contained in the site
36221under CC-BY-SA on the same site at any time before August 1, 2009,
36222provided the MMC is eligible for relicensing.
36223
36224@strong{ADDENDUM: How to use this License for your documents}
36225
36226To use this License in a document you have written, include a copy of
36227the License in the document and put the following copyright and
36228license notices just after the title page:
36229
36230@quotation
36231
36232Copyright �� YEAR  YOUR NAME.
36233Permission is granted to copy, distribute and/or modify this document
36234under the terms of the GNU Free Documentation License, Version 1.3
36235or any later version published by the Free Software Foundation;
36236with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
36237A copy of the license is included in the section entitled "GNU
36238Free Documentation License".
36239@end quotation
36240
36241If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts,
36242replace the "with ... Texts." line with this:
36243
36244@quotation
36245
36246with the Invariant Sections being LIST THEIR TITLES, with the
36247Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST.
36248@end quotation
36249
36250If you have Invariant Sections without Cover Texts, or some other
36251combination of the three, merge those two alternatives to suit the
36252situation.
36253
36254If your document contains nontrivial examples of program code, we
36255recommend releasing these examples in parallel under your choice of
36256free software license, such as the GNU General Public License,
36257to permit their use in free software.
36258
36259@node Index,,GNU Free Documentation License,Top
36260@unnumbered Index
36261
36262
36263@printindex ge
36264
36265
36266@c %**end of body
36267@bye
36268