1.. role:: switch(samp)
2
3.. |with| replace:: *with*
4.. |withs| replace:: *with*\ s
5.. |withed| replace:: *with*\ ed
6.. |withing| replace:: *with*\ ing
7
8.. -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
9
10
11.. _The_GNAT_Compilation_Model:
12
13**************************
14The GNAT Compilation Model
15**************************
16
17.. index:: ! GNAT compilation model
18
19.. index:: Compilation model
20
21This chapter describes the compilation model used by GNAT. Although
22similar to that used by other languages such as C and C++, this model
23is substantially different from the traditional Ada compilation models,
24which are based on a centralized program library. The chapter covers
25the following material:
26
27* Topics related to source file makeup and naming
28
29  * :ref:`Source_Representation`
30  * :ref:`Foreign_Language_Representation`
31  * :ref:`File_Naming_Topics_and_Utilities`
32
33* :ref:`Configuration_Pragmas`
34* :ref:`Generating_Object_Files`
35* :ref:`Source_Dependencies`
36* :ref:`The_Ada_Library_Information_Files`
37* :ref:`Binding_an_Ada_Program`
38* :ref:`GNAT_and_Libraries`
39* :ref:`Conditional_Compilation`
40* :ref:`Mixed_Language_Programming`
41* :ref:`GNAT_and_Other_Compilation_Models`
42* :ref:`Using_GNAT_Files_with_External_Tools`
43
44
45.. _Source_Representation:
46
47Source Representation
48=====================
49
50.. index:: Latin-1
51
52.. index:: VT, HT, CR, LF, FF
53
54Ada source programs are represented in standard text files, using
55Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
567-bit ASCII set, plus additional characters used for
57representing foreign languages (see :ref:`Foreign_Language_Representation`
58for support of non-USA character sets). The format effector characters
59are represented using their standard ASCII encodings, as follows:
60
61    =========== ======================= ===========
62     Character          Effect           Code
63    ----------- ----------------------- -----------
64    :kbd:`VT`    Vertical tab            ``16#0B#``
65    :kbd:`HT`    Horizontal tab          ``16#09#``
66    :kbd:`CR`    Carriage return         ``16#0D#``
67    :kbd:`LF`    Line feed               ``16#0A#``
68    :kbd:`FF`    Form feed               ``16#0C#``
69    =========== ======================= ===========
70
71Source files are in standard text file format. In addition, GNAT will
72recognize a wide variety of stream formats, in which the end of
73physical lines is marked by any of the following sequences:
74``LF``, ``CR``, ``CR-LF``, or ``LF-CR``. This is useful
75in accommodating files that are imported from other operating systems.
76
77.. index:: pair: End of source file; Source file, end
78
79.. index:: SUB (control character)
80
81The end of a source file is normally represented by the physical end of
82file. However, the control character ``16#1A#`` (:kbd:`SUB`) is also
83recognized as signalling the end of the source file. Again, this is
84provided for compatibility with other operating systems where this
85code is used to represent the end of file.
86
87.. index:: spec (definition), compilation (definition)
88
89Each file contains a single Ada compilation unit, including any pragmas
90associated with the unit. For example, this means you must place a
91package declaration (a package *spec*) and the corresponding body in
92separate files. An Ada *compilation* (which is a sequence of
93compilation units) is represented using a sequence of files. Similarly,
94you will place each subunit or child unit in a separate file.
95
96.. _Foreign_Language_Representation:
97
98Foreign Language Representation
99===============================
100
101GNAT supports the standard character sets defined in Ada as well as
102several other non-standard character sets for use in localized versions
103of the compiler (:ref:`Character_Set_Control`).
104
105.. _Latin-1:
106
107Latin-1
108-------
109
110.. index:: Latin-1
111
112The basic character set is Latin-1. This character set is defined by ISO
113standard 8859, part 1. The lower half (character codes ``16#00#``
114... ``16#7F#)`` is identical to standard ASCII coding, but the upper
115half is used to represent additional characters. These include extended letters
116used by European languages, such as French accents, the vowels with umlauts
117used in German, and the extra letter A-ring used in Swedish.
118
119.. index:: Ada.Characters.Latin_1
120
121For a complete list of Latin-1 codes and their encodings, see the source
122file of library unit ``Ada.Characters.Latin_1`` in file
123:file:`a-chlat1.ads`.
124You may use any of these extended characters freely in character or
125string literals. In addition, the extended characters that represent
126letters can be used in identifiers.
127
128.. _Other_8-Bit_Codes:
129
130Other 8-Bit Codes
131-----------------
132
133GNAT also supports several other 8-bit coding schemes:
134
135
136.. index:: Latin-2
137.. index:: ISO 8859-2
138
139*ISO 8859-2 (Latin-2)*
140  Latin-2 letters allowed in identifiers, with uppercase and lowercase
141  equivalence.
142
143.. index:: Latin-3
144.. index:: ISO 8859-3
145
146*ISO 8859-3 (Latin-3)*
147  Latin-3 letters allowed in identifiers, with uppercase and lowercase
148  equivalence.
149
150
151.. index:: Latin-4
152.. index:: ISO 8859-4
153
154*ISO 8859-4 (Latin-4)*
155  Latin-4 letters allowed in identifiers, with uppercase and lowercase
156  equivalence.
157
158
159.. index:: ISO 8859-5
160.. index:: Cyrillic
161
162*ISO 8859-5 (Cyrillic)*
163  ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
164  lowercase equivalence.
165
166.. index:: ISO 8859-15
167.. index:: Latin-9
168
169*ISO 8859-15 (Latin-9)*
170  ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
171  lowercase equivalence
172
173.. index:: code page 437 (IBM PC)
174
175*IBM PC (code page 437)*
176  This code page is the normal default for PCs in the U.S. It corresponds
177  to the original IBM PC character set. This set has some, but not all, of
178  the extended Latin-1 letters, but these letters do not have the same
179  encoding as Latin-1. In this mode, these letters are allowed in
180  identifiers with uppercase and lowercase equivalence.
181
182.. index:: code page 850 (IBM PC)
183
184*IBM PC (code page 850)*
185  This code page is a modification of 437 extended to include all the
186  Latin-1 letters, but still not with the usual Latin-1 encoding. In this
187  mode, all these letters are allowed in identifiers with uppercase and
188  lowercase equivalence.
189
190
191*Full Upper 8-bit*
192  Any character in the range 80-FF allowed in identifiers, and all are
193  considered distinct. In other words, there are no uppercase and lowercase
194  equivalences in this range. This is useful in conjunction with
195  certain encoding schemes used for some foreign character sets (e.g.,
196  the typical method of representing Chinese characters on the PC).
197
198
199*No Upper-Half*
200  No upper-half characters in the range 80-FF are allowed in identifiers.
201  This gives Ada 83 compatibility for identifier names.
202
203For precise data on the encodings permitted, and the uppercase and lowercase
204equivalences that are recognized, see the file :file:`csets.adb` in
205the GNAT compiler sources. You will need to obtain a full source release
206of GNAT to obtain this file.
207
208.. _Wide_Character_Encodings:
209
210Wide_Character Encodings
211------------------------
212
213GNAT allows wide character codes to appear in character and string
214literals, and also optionally in identifiers, by means of the following
215possible encoding schemes:
216
217*Hex Coding*
218  In this encoding, a wide character is represented by the following five
219  character sequence::
220
221    ESC a b c d
222
223  where ``a``, ``b``, ``c``, ``d`` are the four hexadecimal
224  characters (using uppercase letters) of the wide character code. For
225  example, ESC A345 is used to represent the wide character with code
226  ``16#A345#``.
227  This scheme is compatible with use of the full Wide_Character set.
228
229*Upper-Half Coding*
230  .. index:: Upper-Half Coding
231
232  The wide character with encoding ``16#abcd#`` where the upper bit is on
233  (in other words, 'a' is in the range 8-F) is represented as two bytes,
234  ``16#ab#`` and ``16#cd#``. The second byte cannot be a format control
235  character, but is not required to be in the upper half. This method can
236  be also used for shift-JIS or EUC, where the internal coding matches the
237  external coding.
238
239*Shift JIS Coding*
240  .. index:: Shift JIS Coding
241
242  A wide character is represented by a two-character sequence,
243  ``16#ab#`` and
244  ``16#cd#``, with the restrictions described for upper-half encoding as
245  described above. The internal character code is the corresponding JIS
246  character according to the standard algorithm for Shift-JIS
247  conversion. Only characters defined in the JIS code set table can be
248  used with this encoding method.
249
250
251*EUC Coding*
252  .. index:: EUC Coding
253
254  A wide character is represented by a two-character sequence
255  ``16#ab#`` and
256  ``16#cd#``, with both characters being in the upper half. The internal
257  character code is the corresponding JIS character according to the EUC
258  encoding algorithm. Only characters defined in the JIS code set table
259  can be used with this encoding method.
260
261
262*UTF-8 Coding*
263  A wide character is represented using
264  UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
265  10646-1/Am.2. Depending on the character value, the representation
266  is a one, two, or three byte sequence::
267
268    16#0000#-16#007f#: 2#0xxxxxxx#
269    16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx#
270    16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx#
271
272  where the ``xxx`` bits correspond to the left-padded bits of the
273  16-bit character value. Note that all lower half ASCII characters
274  are represented as ASCII bytes and all upper half characters and
275  other wide characters are represented as sequences of upper-half
276  (The full UTF-8 scheme allows for encoding 31-bit characters as
277  6-byte sequences, and in the following section on wide wide
278  characters, the use of these sequences is documented).
279
280
281*Brackets Coding*
282  In this encoding, a wide character is represented by the following eight
283  character sequence::
284
285    [ " a b c d " ]
286
287  where ``a``, ``b``, ``c``, ``d`` are the four hexadecimal
288  characters (using uppercase letters) of the wide character code. For
289  example, ['A345'] is used to represent the wide character with code
290  ``16#A345#``. It is also possible (though not required) to use the
291  Brackets coding for upper half characters. For example, the code
292  ``16#A3#`` can be represented as ``['A3']``.
293
294  This scheme is compatible with use of the full Wide_Character set,
295  and is also the method used for wide character encoding in some standard
296  ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
297
298.. note::
299
300  Some of these coding schemes do not permit the full use of the
301  Ada character set. For example, neither Shift JIS nor EUC allow the
302  use of the upper half of the Latin-1 set.
303
304.. _Wide_Wide_Character_Encodings:
305
306Wide_Wide_Character Encodings
307-----------------------------
308
309GNAT allows wide wide character codes to appear in character and string
310literals, and also optionally in identifiers, by means of the following
311possible encoding schemes:
312
313*UTF-8 Coding*
314  A wide character is represented using
315  UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
316  10646-1/Am.2. Depending on the character value, the representation
317  of character codes with values greater than 16#FFFF# is a
318  is a four, five, or six byte sequence::
319
320    16#01_0000#-16#10_FFFF#:     11110xxx 10xxxxxx 10xxxxxx
321                                 10xxxxxx
322    16#0020_0000#-16#03FF_FFFF#: 111110xx 10xxxxxx 10xxxxxx
323                                 10xxxxxx 10xxxxxx
324    16#0400_0000#-16#7FFF_FFFF#: 1111110x 10xxxxxx 10xxxxxx
325                                 10xxxxxx 10xxxxxx 10xxxxxx
326
327
328  where the ``xxx`` bits correspond to the left-padded bits of the
329  32-bit character value.
330
331*Brackets Coding*
332  In this encoding, a wide wide character is represented by the following ten or
333  twelve byte character sequence::
334
335    [ " a b c d e f " ]
336    [ " a b c d e f g h " ]
337
338  where ``a-h`` are the six or eight hexadecimal
339  characters (using uppercase letters) of the wide wide character code. For
340  example, ["1F4567"] is used to represent the wide wide character with code
341  ``16#001F_4567#``.
342
343  This scheme is compatible with use of the full Wide_Wide_Character set,
344  and is also the method used for wide wide character encoding in some standard
345  ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
346
347
348.. _File_Naming_Topics_and_Utilities:
349
350File Naming Topics and Utilities
351================================
352
353GNAT has a default file naming scheme and also provides the user with
354a high degree of control over how the names and extensions of the
355source files correspond to the Ada compilation units that they contain.
356
357
358.. _File_Naming_Rules:
359
360File Naming Rules
361-----------------
362
363The default file name is determined by the name of the unit that the
364file contains. The name is formed by taking the full expanded name of
365the unit and replacing the separating dots with hyphens and using
366lowercase for all letters.
367
368An exception arises if the file name generated by the above rules starts
369with one of the characters
370``a``, ``g``, ``i``, or ``s``, and the second character is a
371minus. In this case, the character tilde is used in place
372of the minus. The reason for this special rule is to avoid clashes with
373the standard names for child units of the packages System, Ada,
374Interfaces, and GNAT, which use the prefixes
375``s-``, ``a-``, ``i-``, and ``g-``,
376respectively.
377
378The file extension is :file:`.ads` for a spec and
379:file:`.adb` for a body. The following table shows some
380examples of these rules.
381
382   ============================ ===============================
383   Source File                   Ada Compilation Unit
384   ---------------------------- -------------------------------
385   :file:`main.ads`              Main (spec)
386   :file:`main.adb`              Main (body)
387   :file:`arith_functions.ads`   Arith_Functions (package spec)
388   :file:`arith_functions.adb`   Arith_Functions (package body)
389   :file:`func-spec.ads`         Func.Spec (child package spec)
390   :file:`func-spec.adb`         Func.Spec (child package body)
391   :file:`main-sub.adb`          Sub (subunit of Main)
392   :file:`a~bad.adb`             A.Bad (child package body)
393   ============================ ===============================
394
395Following these rules can result in excessively long
396file names if corresponding
397unit names are long (for example, if child units or subunits are
398heavily nested). An option is available to shorten such long file names
399(called file name 'krunching'). This may be particularly useful when
400programs being developed with GNAT are to be used on operating systems
401with limited file name lengths. :ref:`Using_gnatkr`.
402
403Of course, no file shortening algorithm can guarantee uniqueness over
404all possible unit names; if file name krunching is used, it is your
405responsibility to ensure no name clashes occur. Alternatively you
406can specify the exact file names that you want used, as described
407in the next section. Finally, if your Ada programs are migrating from a
408compiler with a different naming convention, you can use the gnatchop
409utility to produce source files that follow the GNAT naming conventions.
410(For details see :ref:`Renaming_Files_with_gnatchop`.)
411
412Note: in the case of Windows or Mac OS operating systems, case is not
413significant. So for example on Windows if the canonical name is
414:file:`main-sub.adb`, you can use the file name :file:`Main-Sub.adb` instead.
415However, case is significant for other operating systems, so for example,
416if you want to use other than canonically cased file names on a Unix system,
417you need to follow the procedures described in the next section.
418
419.. _Using_Other_File_Names:
420
421Using Other File Names
422----------------------
423
424.. index:: File names
425
426In the previous section, we have described the default rules used by
427GNAT to determine the file name in which a given unit resides. It is
428often convenient to follow these default rules, and if you follow them,
429the compiler knows without being explicitly told where to find all
430the files it needs.
431
432.. index:: Source_File_Name pragma
433
434However, in some cases, particularly when a program is imported from
435another Ada compiler environment, it may be more convenient for the
436programmer to specify which file names contain which units. GNAT allows
437arbitrary file names to be used by means of the Source_File_Name pragma.
438The form of this pragma is as shown in the following examples:
439
440.. code-block:: ada
441
442      pragma Source_File_Name (My_Utilities.Stacks,
443        Spec_File_Name => "myutilst_a.ada");
444      pragma Source_File_name (My_Utilities.Stacks,
445        Body_File_Name => "myutilst.ada");
446
447As shown in this example, the first argument for the pragma is the unit
448name (in this example a child unit). The second argument has the form
449of a named association. The identifier
450indicates whether the file name is for a spec or a body;
451the file name itself is given by a string literal.
452
453The source file name pragma is a configuration pragma, which means that
454normally it will be placed in the :file:`gnat.adc`
455file used to hold configuration
456pragmas that apply to a complete compilation environment.
457For more details on how the :file:`gnat.adc` file is created and used
458see :ref:`Handling_of_Configuration_Pragmas`.
459
460.. index:: gnat.adc
461
462GNAT allows completely arbitrary file names to be specified using the
463source file name pragma. However, if the file name specified has an
464extension other than :file:`.ads` or :file:`.adb` it is necessary to use
465a special syntax when compiling the file. The name in this case must be
466preceded by the special sequence ``-x`` followed by a space and the name
467of the language, here ``ada``, as in:
468
469.. code-block:: sh
470
471     $ gcc -c -x ada peculiar_file_name.sim
472
473``gnatmake`` handles non-standard file names in the usual manner (the
474non-standard file name for the main program is simply used as the
475argument to gnatmake). Note that if the extension is also non-standard,
476then it must be included in the ``gnatmake`` command, it may not
477be omitted.
478
479.. _Alternative_File_Naming_Schemes:
480
481Alternative File Naming Schemes
482-------------------------------
483
484.. index:: File naming schemes, alternative
485
486.. index:: File names
487
488The previous section described the use of the ``Source_File_Name``
489pragma to allow arbitrary names to be assigned to individual source files.
490However, this approach requires one pragma for each file, and especially in
491large systems can result in very long :file:`gnat.adc` files, and also create
492a maintenance problem.
493
494.. index:: Source_File_Name pragma
495
496GNAT also provides a facility for specifying systematic file naming schemes
497other than the standard default naming scheme previously described. An
498alternative scheme for naming is specified by the use of
499``Source_File_Name`` pragmas having the following format:
500
501.. code-block:: ada
502
503     pragma Source_File_Name (
504        Spec_File_Name  => FILE_NAME_PATTERN
505      [ , Casing          => CASING_SPEC]
506      [ , Dot_Replacement => STRING_LITERAL ] );
507
508     pragma Source_File_Name (
509        Body_File_Name  => FILE_NAME_PATTERN
510      [ , Casing          => CASING_SPEC ]
511      [ , Dot_Replacement => STRING_LITERAL ] ) ;
512
513     pragma Source_File_Name (
514        Subunit_File_Name  => FILE_NAME_PATTERN
515      [ , Casing          => CASING_SPEC ]
516      [ , Dot_Replacement => STRING_LITERAL ] ) ;
517
518     FILE_NAME_PATTERN ::= STRING_LITERAL
519     CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
520
521The ``FILE_NAME_PATTERN`` string shows how the file name is constructed.
522It contains a single asterisk character, and the unit name is substituted
523systematically for this asterisk. The optional parameter
524``Casing`` indicates
525whether the unit name is to be all upper-case letters, all lower-case letters,
526or mixed-case. If no
527``Casing`` parameter is used, then the default is all
528lower-case.
529
530The optional ``Dot_Replacement`` string is used to replace any periods
531that occur in subunit or child unit names. If no ``Dot_Replacement``
532argument is used then separating dots appear unchanged in the resulting
533file name.
534Although the above syntax indicates that the
535``Casing`` argument must appear
536before the ``Dot_Replacement`` argument, but it
537is also permissible to write these arguments in the opposite order.
538
539As indicated, it is possible to specify different naming schemes for
540bodies, specs, and subunits. Quite often the rule for subunits is the
541same as the rule for bodies, in which case, there is no need to give
542a separate ``Subunit_File_Name`` rule, and in this case the
543``Body_File_name`` rule is used for subunits as well.
544
545The separate rule for subunits can also be used to implement the rather
546unusual case of a compilation environment (e.g., a single directory) which
547contains a subunit and a child unit with the same unit name. Although
548both units cannot appear in the same partition, the Ada Reference Manual
549allows (but does not require) the possibility of the two units coexisting
550in the same environment.
551
552The file name translation works in the following steps:
553
554* If there is a specific ``Source_File_Name`` pragma for the given unit,
555  then this is always used, and any general pattern rules are ignored.
556
557* If there is a pattern type ``Source_File_Name`` pragma that applies to
558  the unit, then the resulting file name will be used if the file exists. If
559  more than one pattern matches, the latest one will be tried first, and the
560  first attempt resulting in a reference to a file that exists will be used.
561
562* If no pattern type ``Source_File_Name`` pragma that applies to the unit
563  for which the corresponding file exists, then the standard GNAT default
564  naming rules are used.
565
566As an example of the use of this mechanism, consider a commonly used scheme
567in which file names are all lower case, with separating periods copied
568unchanged to the resulting file name, and specs end with :file:`.1.ada`, and
569bodies end with :file:`.2.ada`. GNAT will follow this scheme if the following
570two pragmas appear:
571
572.. code-block:: ada
573
574     pragma Source_File_Name
575       (Spec_File_Name => ".1.ada");
576     pragma Source_File_Name
577       (Body_File_Name => ".2.ada");
578
579The default GNAT scheme is actually implemented by providing the following
580default pragmas internally:
581
582.. code-block:: ada
583
584     pragma Source_File_Name
585       (Spec_File_Name => ".ads", Dot_Replacement => "-");
586     pragma Source_File_Name
587       (Body_File_Name => ".adb", Dot_Replacement => "-");
588
589Our final example implements a scheme typically used with one of the
590Ada 83 compilers, where the separator character for subunits was '__'
591(two underscores), specs were identified by adding :file:`_.ADA`, bodies
592by adding :file:`.ADA`, and subunits by
593adding :file:`.SEP`. All file names were
594upper case. Child units were not present of course since this was an
595Ada 83 compiler, but it seems reasonable to extend this scheme to use
596the same double underscore separator for child units.
597
598.. code-block:: ada
599
600     pragma Source_File_Name
601       (Spec_File_Name => "_.ADA",
602        Dot_Replacement => "__",
603        Casing = Uppercase);
604     pragma Source_File_Name
605       (Body_File_Name => ".ADA",
606        Dot_Replacement => "__",
607        Casing = Uppercase);
608     pragma Source_File_Name
609       (Subunit_File_Name => ".SEP",
610        Dot_Replacement => "__",
611        Casing = Uppercase);
612
613
614.. index:: ! gnatname
615
616.. _Handling_Arbitrary_File_Naming_Conventions_with_gnatname:
617
618Handling Arbitrary File Naming Conventions with ``gnatname``
619------------------------------------------------------------
620
621.. index:: File Naming Conventions
622
623.. _Arbitrary_File_Naming_Conventions:
624
625Arbitrary File Naming Conventions
626^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
627
628The GNAT compiler must be able to know the source file name of a compilation
629unit.  When using the standard GNAT default file naming conventions
630(``.ads`` for specs, ``.adb`` for bodies), the GNAT compiler
631does not need additional information.
632
633When the source file names do not follow the standard GNAT default file naming
634conventions, the GNAT compiler must be given additional information through
635a configuration pragmas file (:ref:`Configuration_Pragmas`)
636or a project file.
637When the non-standard file naming conventions are well-defined,
638a small number of pragmas ``Source_File_Name`` specifying a naming pattern
639(:ref:`Alternative_File_Naming_Schemes`) may be sufficient. However,
640if the file naming conventions are irregular or arbitrary, a number
641of pragma ``Source_File_Name`` for individual compilation units
642must be defined.
643To help maintain the correspondence between compilation unit names and
644source file names within the compiler,
645GNAT provides a tool ``gnatname`` to generate the required pragmas for a
646set of files.
647
648.. _Running_gnatname:
649
650Running ``gnatname``
651^^^^^^^^^^^^^^^^^^^^
652
653The usual form of the ``gnatname`` command is:
654
655.. code-block:: sh
656
657      $ gnatname [ switches ]  naming_pattern  [ naming_patterns ]
658          [--and [ switches ]  naming_pattern  [ naming_patterns ]]
659
660
661All of the arguments are optional. If invoked without any argument,
662``gnatname`` will display its usage.
663
664When used with at least one naming pattern, ``gnatname`` will attempt to
665find all the compilation units in files that follow at least one of the
666naming patterns. To find these compilation units,
667``gnatname`` will use the GNAT compiler in syntax-check-only mode on all
668regular files.
669
670One or several Naming Patterns may be given as arguments to ``gnatname``.
671Each Naming Pattern is enclosed between double quotes (or single
672quotes on Windows).
673A Naming Pattern is a regular expression similar to the wildcard patterns
674used in file names by the Unix shells or the DOS prompt.
675
676``gnatname`` may be called with several sections of directories/patterns.
677Sections are separated by the switch :switch:`--and`. In each section, there must be
678at least one pattern. If no directory is specified in a section, the current
679directory (or the project directory if :switch:`-P` is used) is implied.
680The options other that the directory switches and the patterns apply globally
681even if they are in different sections.
682
683Examples of Naming Patterns are::
684
685     "*.[12].ada"
686     "*.ad[sb]*"
687     "body_*"    "spec_*"
688
689For a more complete description of the syntax of Naming Patterns,
690see the second kind of regular expressions described in :file:`g-regexp.ads`
691(the 'Glob' regular expressions).
692
693When invoked without the switch :switch:`-P`, ``gnatname`` will create a
694configuration pragmas file :file:`gnat.adc` in the current working directory,
695with pragmas ``Source_File_Name`` for each file that contains a valid Ada
696unit.
697
698.. _Switches_for_gnatname:
699
700Switches for ``gnatname``
701^^^^^^^^^^^^^^^^^^^^^^^^^
702
703Switches for ``gnatname`` must precede any specified Naming Pattern.
704
705You may specify any of the following switches to ``gnatname``:
706
707.. index:: --version (gnatname)
708
709:switch:`--version`
710  Display Copyright and version, then exit disregarding all other options.
711
712.. index:: --help (gnatname)
713
714:switch:`--help`
715  If :switch:`--version` was not used, display usage, then exit disregarding
716  all other options.
717
718:switch:`--subdirs={dir}`
719  Real object, library or exec directories are subdirectories <dir> of the
720  specified ones.
721
722:switch:`--no-backup`
723  Do not create a backup copy of an existing project file.
724
725:switch:`--and`
726  Start another section of directories/patterns.
727
728.. index:: -c (gnatname)
729
730:switch:`-c{filename}`
731  Create a configuration pragmas file :file:`filename` (instead of the default
732  :file:`gnat.adc`).
733  There may be zero, one or more space between :switch:`-c` and
734  :file:`filename`.
735  :file:`filename` may include directory information. :file:`filename` must be
736  writable. There may be only one switch :switch:`-c`.
737  When a switch :switch:`-c` is
738  specified, no switch :switch:`-P` may be specified (see below).
739
740.. index:: -d (gnatname)
741
742:switch:`-d{dir}`
743  Look for source files in directory :file:`dir`. There may be zero, one or more
744  spaces between :switch:`-d` and :file:`dir`.
745  :file:`dir` may end with ``/**``, that is it may be of the form
746  ``root_dir/**``. In this case, the directory ``root_dir`` and all of its
747  subdirectories, recursively, have to be searched for sources.
748  When a switch :switch:`-d`
749  is specified, the current working directory will not be searched for source
750  files, unless it is explicitly specified with a :switch:`-d`
751  or :switch:`-D` switch.
752  Several switches :switch:`-d` may be specified.
753  If :file:`dir` is a relative path, it is relative to the directory of
754  the configuration pragmas file specified with switch
755  :switch:`-c`,
756  or to the directory of the project file specified with switch
757  :switch:`-P` or,
758  if neither switch :switch:`-c`
759  nor switch :switch:`-P` are specified, it is relative to the
760  current working directory. The directory
761  specified with switch :switch:`-d` must exist and be readable.
762
763.. index:: -D (gnatname)
764
765:switch:`-D{filename}`
766  Look for source files in all directories listed in text file :file:`filename`.
767  There may be zero, one or more spaces between :switch:`-D`
768  and :file:`filename`.
769  :file:`filename` must be an existing, readable text file.
770  Each nonempty line in :file:`filename` must be a directory.
771  Specifying switch :switch:`-D` is equivalent to specifying as many
772  switches :switch:`-d` as there are nonempty lines in
773  :file:`file`.
774
775:switch:`-eL`
776  Follow symbolic links when processing project files.
777
778  .. index:: -f (gnatname)
779
780:switch:`-f{pattern}`
781  Foreign patterns. Using this switch, it is possible to add sources of languages
782  other than Ada to the list of sources of a project file.
783  It is only useful if a -P switch is used.
784  For example,
785
786  .. code-block:: sh
787
788     gnatname -Pprj -f"*.c" "*.ada"
789
790  will look for Ada units in all files with the :file:`.ada` extension,
791  and will add to the list of file for project :file:`prj.gpr` the C files
792  with extension :file:`.c`.
793
794  .. index:: -h (gnatname)
795
796:switch:`-h`
797  Output usage (help) information. The output is written to :file:`stdout`.
798
799  .. index:: -P (gnatname)
800
801:switch:`-P{proj}`
802  Create or update project file :file:`proj`. There may be zero, one or more space
803  between :switch:`-P` and :file:`proj`. :file:`proj` may include directory
804  information. :file:`proj` must be writable.
805  There may be only one switch :switch:`-P`.
806  When a switch :switch:`-P` is specified,
807  no switch :switch:`-c` may be specified.
808  On all platforms, except on VMS, when ``gnatname`` is invoked for an
809  existing project file <proj>.gpr, a backup copy of the project file is created
810  in the project directory with file name <proj>.gpr.saved_x. 'x' is the first
811  non negative number that makes this backup copy a new file.
812
813  .. index:: -v (gnatname)
814
815:switch:`-v`
816  Verbose mode. Output detailed explanation of behavior to :file:`stdout`.
817  This includes name of the file written, the name of the directories to search
818  and, for each file in those directories whose name matches at least one of
819  the Naming Patterns, an indication of whether the file contains a unit,
820  and if so the name of the unit.
821
822.. index:: -v -v (gnatname)
823
824:switch:`-v -v`
825  Very Verbose mode. In addition to the output produced in verbose mode,
826  for each file in the searched directories whose name matches none of
827  the Naming Patterns, an indication is given that there is no match.
828
829  .. index:: -x (gnatname)
830
831:switch:`-x{pattern}`
832  Excluded patterns. Using this switch, it is possible to exclude some files
833  that would match the name patterns. For example,
834
835  .. code-block:: sh
836
837      gnatname -x "*_nt.ada" "*.ada"
838
839  will look for Ada units in all files with the :file:`.ada` extension,
840  except those whose names end with :file:`_nt.ada`.
841
842
843.. _Examples_of_gnatname_Usage:
844
845Examples of ``gnatname`` Usage
846^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
847
848.. code-block:: sh
849
850     $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
851
852In this example, the directory :file:`/home/me` must already exist
853and be writable. In addition, the directory
854:file:`/home/me/sources` (specified by
855:switch:`-d sources`) must exist and be readable.
856
857Note the optional spaces after :switch:`-c` and :switch:`-d`.
858
859.. code-block:: sh
860
861     $ gnatname -P/home/me/proj -x "*_nt_body.ada"
862     -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
863
864Note that several switches :switch:`-d` may be used,
865even in conjunction with one or several switches
866:switch:`-D`. Several Naming Patterns and one excluded pattern
867are used in this example.
868
869
870.. _File_Name_Krunching_with_gnatkr:
871
872File Name Krunching with ``gnatkr``
873-----------------------------------
874
875.. index:: ! gnatkr
876
877This section discusses the method used by the compiler to shorten
878the default file names chosen for Ada units so that they do not
879exceed the maximum length permitted. It also describes the
880``gnatkr`` utility that can be used to determine the result of
881applying this shortening.
882
883.. _About_gnatkr:
884
885About ``gnatkr``
886^^^^^^^^^^^^^^^^
887
888The default file naming rule in GNAT
889is that the file name must be derived from
890the unit name. The exact default rule is as follows:
891
892* Take the unit name and replace all dots by hyphens.
893
894* If such a replacement occurs in the
895  second character position of a name, and the first character is
896  :samp:`a`, :samp:`g`, :samp:`s`, or :samp:`i`,
897  then replace the dot by the character
898  :samp:`~` (tilde)
899  instead of a minus.
900
901  The reason for this exception is to avoid clashes
902  with the standard names for children of System, Ada, Interfaces,
903  and GNAT, which use the prefixes
904  :samp:`s-`, :samp:`a-`, :samp:`i-`, and :samp:`g-`,
905  respectively.
906
907The :switch:`-gnatk{nn}`
908switch of the compiler activates a 'krunching'
909circuit that limits file names to nn characters (where nn is a decimal
910integer).
911
912The ``gnatkr`` utility can be used to determine the krunched name for
913a given file, when krunched to a specified maximum length.
914
915.. _Using_gnatkr:
916
917Using ``gnatkr``
918^^^^^^^^^^^^^^^^
919
920The ``gnatkr`` command has the form:
921
922.. code-block:: sh
923
924      $ gnatkr name [ length ]
925
926``name`` is the uncrunched file name, derived from the name of the unit
927in the standard manner described in the previous section (i.e., in particular
928all dots are replaced by hyphens). The file name may or may not have an
929extension (defined as a suffix of the form period followed by arbitrary
930characters other than period). If an extension is present then it will
931be preserved in the output. For example, when krunching :file:`hellofile.ads`
932to eight characters, the result will be hellofil.ads.
933
934Note: for compatibility with previous versions of ``gnatkr`` dots may
935appear in the name instead of hyphens, but the last dot will always be
936taken as the start of an extension. So if ``gnatkr`` is given an argument
937such as :file:`Hello.World.adb` it will be treated exactly as if the first
938period had been a hyphen, and for example krunching to eight characters
939gives the result :file:`hellworl.adb`.
940
941Note that the result is always all lower case.
942Characters of the other case are folded as required.
943
944``length`` represents the length of the krunched name. The default
945when no argument is given is 8 characters. A length of zero stands for
946unlimited, in other words do not chop except for system files where the
947implied crunching length is always eight characters.
948
949The output is the krunched name. The output has an extension only if the
950original argument was a file name with an extension.
951
952.. _Krunching_Method:
953
954Krunching Method
955^^^^^^^^^^^^^^^^
956
957The initial file name is determined by the name of the unit that the file
958contains. The name is formed by taking the full expanded name of the
959unit and replacing the separating dots with hyphens and
960using lowercase
961for all letters, except that a hyphen in the second character position is
962replaced by a tilde if the first character is
963:samp:`a`, :samp:`i`, :samp:`g`, or :samp:`s`.
964The extension is ``.ads`` for a
965spec and ``.adb`` for a body.
966Krunching does not affect the extension, but the file name is shortened to
967the specified length by following these rules:
968
969* The name is divided into segments separated by hyphens, tildes or
970  underscores and all hyphens, tildes, and underscores are
971  eliminated. If this leaves the name short enough, we are done.
972
973* If the name is too long, the longest segment is located (left-most
974  if there are two of equal length), and shortened by dropping
975  its last character. This is repeated until the name is short enough.
976
977  As an example, consider the krunching of :file:`our-strings-wide_fixed.adb`
978  to fit the name into 8 characters as required by some operating systems::
979
980      our-strings-wide_fixed 22
981      our strings wide fixed 19
982      our string  wide fixed 18
983      our strin   wide fixed 17
984      our stri    wide fixed 16
985      our stri    wide fixe  15
986      our str     wide fixe  14
987      our str     wid  fixe  13
988      our str     wid  fix   12
989      ou  str     wid  fix   11
990      ou  st      wid  fix   10
991      ou  st      wi   fix   9
992      ou  st      wi   fi    8
993      Final file name: oustwifi.adb
994
995* The file names for all predefined units are always krunched to eight
996  characters. The krunching of these predefined units uses the following
997  special prefix replacements:
998
999  ===================== ==============
1000  Prefix                 Replacement
1001  --------------------- --------------
1002  :file:`ada-`           :file:`a-`
1003  :file:`gnat-`          :file:`g-`
1004  :file:`interfac es-`   :file:`i-`
1005  :file:`system-`        :file:`s-`
1006  ===================== ==============
1007
1008  These system files have a hyphen in the second character position. That
1009  is why normal user files replace such a character with a
1010  tilde, to avoid confusion with system file names.
1011
1012  As an example of this special rule, consider
1013  :file:`ada-strings-wide_fixed.adb`, which gets krunched as follows::
1014
1015      ada-strings-wide_fixed 22
1016      a-  strings wide fixed 18
1017      a-  string  wide fixed 17
1018      a-  strin   wide fixed 16
1019      a-  stri    wide fixed 15
1020      a-  stri    wide fixe  14
1021      a-  str     wide fixe  13
1022      a-  str     wid  fixe  12
1023      a-  str     wid  fix   11
1024      a-  st      wid  fix   10
1025      a-  st      wi   fix   9
1026      a-  st      wi   fi    8
1027      Final file name: a-stwifi.adb
1028
1029Of course no file shortening algorithm can guarantee uniqueness over all
1030possible unit names, and if file name krunching is used then it is your
1031responsibility to ensure that no name clashes occur. The utility
1032program ``gnatkr`` is supplied for conveniently determining the
1033krunched name of a file.
1034
1035.. _Examples_of_gnatkr_Usage:
1036
1037Examples of ``gnatkr`` Usage
1038^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1039
1040::
1041
1042    $ gnatkr very_long_unit_name.ads      --> velounna.ads
1043    $ gnatkr grandparent-parent-child.ads --> grparchi.ads
1044    $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
1045    $ gnatkr grandparent-parent-child     --> grparchi
1046    $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
1047    $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
1048
1049
1050.. _Renaming_Files_with_gnatchop:
1051
1052Renaming Files with ``gnatchop``
1053--------------------------------
1054
1055.. index:: ! gnatchop
1056
1057This section discusses how to handle files with multiple units by using
1058the ``gnatchop`` utility. This utility is also useful in renaming
1059files to meet the standard GNAT default file naming conventions.
1060
1061.. _Handling_Files_with_Multiple_Units:
1062
1063Handling Files with Multiple Units
1064^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1065
1066The basic compilation model of GNAT requires that a file submitted to the
1067compiler have only one unit and there be a strict correspondence
1068between the file name and the unit name.
1069
1070If you want to keep your files with multiple units,
1071perhaps to maintain compatibility with some other Ada compilation system,
1072you can use ``gnatname`` to generate or update your project files.
1073Generated or modified project files can be processed by GNAT.
1074
1075See :ref:`Handling_Arbitrary_File_Naming_Conventions_with_gnatname`
1076for more details on how to use `gnatname`.
1077
1078Alternatively, if you want to permanently restructure a set of 'foreign'
1079files so that they match the GNAT rules, and do the remaining development
1080using the GNAT structure, you can simply use ``gnatchop`` once, generate the
1081new set of files and work with them from that point on.
1082
1083Note that if your file containing multiple units starts with a byte order
1084mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
1085will each start with a copy of this BOM, meaning that they can be compiled
1086automatically in UTF-8 mode without needing to specify an explicit encoding.
1087
1088.. _Operating_gnatchop_in_Compilation_Mode:
1089
1090Operating gnatchop in Compilation Mode
1091^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1092
1093The basic function of ``gnatchop`` is to take a file with multiple units
1094and split it into separate files. The boundary between files is reasonably
1095clear, except for the issue of comments and pragmas. In default mode, the
1096rule is that any pragmas between units belong to the previous unit, except
1097that configuration pragmas always belong to the following unit. Any comments
1098belong to the following unit. These rules
1099almost always result in the right choice of
1100the split point without needing to mark it explicitly and most users will
1101find this default to be what they want. In this default mode it is incorrect to
1102submit a file containing only configuration pragmas, or one that ends in
1103configuration pragmas, to ``gnatchop``.
1104
1105However, using a special option to activate 'compilation mode',
1106``gnatchop``
1107can perform another function, which is to provide exactly the semantics
1108required by the RM for handling of configuration pragmas in a compilation.
1109In the absence of configuration pragmas (at the main file level), this
1110option has no effect, but it causes such configuration pragmas to be handled
1111in a quite different manner.
1112
1113First, in compilation mode, if ``gnatchop`` is given a file that consists of
1114only configuration pragmas, then this file is appended to the
1115:file:`gnat.adc` file in the current directory. This behavior provides
1116the required behavior described in the RM for the actions to be taken
1117on submitting such a file to the compiler, namely that these pragmas
1118should apply to all subsequent compilations in the same compilation
1119environment. Using GNAT, the current directory, possibly containing a
1120:file:`gnat.adc` file is the representation
1121of a compilation environment. For more information on the
1122:file:`gnat.adc` file, see :ref:`Handling_of_Configuration_Pragmas`.
1123
1124Second, in compilation mode, if ``gnatchop``
1125is given a file that starts with
1126configuration pragmas, and contains one or more units, then these
1127configuration pragmas are prepended to each of the chopped files. This
1128behavior provides the required behavior described in the RM for the
1129actions to be taken on compiling such a file, namely that the pragmas
1130apply to all units in the compilation, but not to subsequently compiled
1131units.
1132
1133Finally, if configuration pragmas appear between units, they are appended
1134to the previous unit. This results in the previous unit being illegal,
1135since the compiler does not accept configuration pragmas that follow
1136a unit. This provides the required RM behavior that forbids configuration
1137pragmas other than those preceding the first compilation unit of a
1138compilation.
1139
1140For most purposes, ``gnatchop`` will be used in default mode. The
1141compilation mode described above is used only if you need exactly
1142accurate behavior with respect to compilations, and you have files
1143that contain multiple units and configuration pragmas. In this
1144circumstance the use of ``gnatchop`` with the compilation mode
1145switch provides the required behavior, and is for example the mode
1146in which GNAT processes the ACVC tests.
1147
1148
1149.. _Command_Line_for_gnatchop:
1150
1151Command Line for ``gnatchop``
1152^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1153
1154The ``gnatchop`` command has the form:
1155
1156.. code-block:: sh
1157
1158     $ gnatchop switches file_name [file_name ...]
1159           [directory]
1160
1161The only required argument is the file name of the file to be chopped.
1162There are no restrictions on the form of this file name. The file itself
1163contains one or more Ada units, in normal GNAT format, concatenated
1164together. As shown, more than one file may be presented to be chopped.
1165
1166When run in default mode, ``gnatchop`` generates one output file in
1167the current directory for each unit in each of the files.
1168
1169``directory``, if specified, gives the name of the directory to which
1170the output files will be written. If it is not specified, all files are
1171written to the current directory.
1172
1173For example, given a
1174file called :file:`hellofiles` containing
1175
1176.. code-block:: ada
1177
1178     procedure Hello;
1179
1180     with Ada.Text_IO; use Ada.Text_IO;
1181     procedure Hello is
1182     begin
1183        Put_Line ("Hello");
1184     end Hello;
1185
1186the command
1187
1188.. code-block:: sh
1189
1190     $ gnatchop hellofiles
1191
1192generates two files in the current directory, one called
1193:file:`hello.ads` containing the single line that is the procedure spec,
1194and the other called :file:`hello.adb` containing the remaining text. The
1195original file is not affected. The generated files can be compiled in
1196the normal manner.
1197
1198When gnatchop is invoked on a file that is empty or that contains only empty
1199lines and/or comments, gnatchop will not fail, but will not produce any
1200new sources.
1201
1202For example, given a
1203file called :file:`toto.txt` containing
1204
1205.. code-block:: ada
1206
1207     --  Just a comment
1208
1209the command
1210
1211.. code-block:: sh
1212
1213     $ gnatchop toto.txt
1214
1215will not produce any new file and will result in the following warnings::
1216
1217     toto.txt:1:01: warning: empty file, contains no compilation units
1218     no compilation units found
1219     no source files written
1220
1221
1222.. _Switches_for_gnatchop:
1223
1224Switches for ``gnatchop``
1225^^^^^^^^^^^^^^^^^^^^^^^^^
1226
1227``gnatchop`` recognizes the following switches:
1228
1229
1230.. index:: --version (gnatchop)
1231
1232:switch:`--version`
1233  Display Copyright and version, then exit disregarding all other options.
1234
1235.. index:: --help (gnatchop)
1236
1237:switch:`--help`
1238  If :switch:`--version` was not used, display usage, then exit disregarding
1239  all other options.
1240
1241.. index:: -c (gnatchop)
1242
1243:switch:`-c`
1244  Causes ``gnatchop`` to operate in compilation mode, in which
1245  configuration pragmas are handled according to strict RM rules. See
1246  previous section for a full description of this mode.
1247
1248:switch:`-gnat{xxx}`
1249  This passes the given :switch:`-gnat{xxx}` switch to ``gnat`` which is
1250  used to parse the given file. Not all *xxx* options make sense,
1251  but for example, the use of :switch:`-gnati2` allows ``gnatchop`` to
1252  process a source file that uses Latin-2 coding for identifiers.
1253
1254:switch:`-h`
1255  Causes ``gnatchop`` to generate a brief help summary to the standard
1256  output file showing usage information.
1257
1258.. index:: -k (gnatchop)
1259
1260:switch:`-k{mm}`
1261  Limit generated file names to the specified number ``mm``
1262  of characters.
1263  This is useful if the
1264  resulting set of files is required to be interoperable with systems
1265  which limit the length of file names.
1266  No space is allowed between the :switch:`-k` and the numeric value. The numeric
1267  value may be omitted in which case a default of :switch:`-k8`,
1268  suitable for use
1269  with DOS-like file systems, is used. If no :switch:`-k` switch
1270  is present then
1271  there is no limit on the length of file names.
1272
1273.. index:: -p (gnatchop)
1274
1275:switch:`-p`
1276  Causes the file modification time stamp of the input file to be
1277  preserved and used for the time stamp of the output file(s). This may be
1278  useful for preserving coherency of time stamps in an environment where
1279  ``gnatchop`` is used as part of a standard build process.
1280
1281.. index:: -q (gnatchop)
1282
1283:switch:`-q`
1284  Causes output of informational messages indicating the set of generated
1285  files to be suppressed. Warnings and error messages are unaffected.
1286
1287.. index:: -r (gnatchop)
1288.. index:: Source_Reference pragmas
1289
1290:switch:`-r`
1291  Generate ``Source_Reference`` pragmas. Use this switch if the output
1292  files are regarded as temporary and development is to be done in terms
1293  of the original unchopped file. This switch causes
1294  ``Source_Reference`` pragmas to be inserted into each of the
1295  generated files to refers back to the original file name and line number.
1296  The result is that all error messages refer back to the original
1297  unchopped file.
1298  In addition, the debugging information placed into the object file (when
1299  the :switch:`-g` switch of ``gcc`` or ``gnatmake`` is
1300  specified)
1301  also refers back to this original file so that tools like profilers and
1302  debuggers will give information in terms of the original unchopped file.
1303
1304  If the original file to be chopped itself contains
1305  a ``Source_Reference``
1306  pragma referencing a third file, then gnatchop respects
1307  this pragma, and the generated ``Source_Reference`` pragmas
1308  in the chopped file refer to the original file, with appropriate
1309  line numbers. This is particularly useful when ``gnatchop``
1310  is used in conjunction with ``gnatprep`` to compile files that
1311  contain preprocessing statements and multiple units.
1312
1313.. index:: -v (gnatchop)
1314
1315:switch:`-v`
1316  Causes ``gnatchop`` to operate in verbose mode. The version
1317  number and copyright notice are output, as well as exact copies of
1318  the gnat1 commands spawned to obtain the chop control information.
1319
1320.. index:: -w (gnatchop)
1321
1322:switch:`-w`
1323  Overwrite existing file names. Normally ``gnatchop`` regards it as a
1324  fatal error if there is already a file with the same name as a
1325  file it would otherwise output, in other words if the files to be
1326  chopped contain duplicated units. This switch bypasses this
1327  check, and causes all but the last instance of such duplicated
1328  units to be skipped.
1329
1330.. index:: --GCC= (gnatchop)
1331
1332:switch:`--GCC={xxxx}`
1333  Specify the path of the GNAT parser to be used. When this switch is used,
1334  no attempt is made to add the prefix to the GNAT parser executable.
1335
1336
1337.. _Examples_of_gnatchop_Usage:
1338
1339Examples of ``gnatchop`` Usage
1340^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1341
1342.. code-block:: sh
1343
1344      $ gnatchop -w hello_s.ada prerelease/files
1345
1346Chops the source file :file:`hello_s.ada`. The output files will be
1347placed in the directory :file:`prerelease/files`,
1348overwriting any
1349files with matching names in that directory (no files in the current
1350directory are modified).
1351
1352.. code-block:: sh
1353
1354      $ gnatchop archive
1355
1356Chops the source file :file:`archive`
1357into the current directory. One
1358useful application of ``gnatchop`` is in sending sets of sources
1359around, for example in email messages. The required sources are simply
1360concatenated (for example, using a Unix ``cat``
1361command), and then
1362``gnatchop`` is used at the other end to reconstitute the original
1363file names.
1364
1365.. code-block:: sh
1366
1367      $ gnatchop file1 file2 file3 direc
1368
1369Chops all units in files :file:`file1`, :file:`file2`, :file:`file3`, placing
1370the resulting files in the directory :file:`direc`. Note that if any units
1371occur more than once anywhere within this set of files, an error message
1372is generated, and no files are written. To override this check, use the
1373:switch:`-w` switch,
1374in which case the last occurrence in the last file will
1375be the one that is output, and earlier duplicate occurrences for a given
1376unit will be skipped.
1377
1378.. _Configuration_Pragmas:
1379
1380Configuration Pragmas
1381=====================
1382
1383.. index:: Configuration pragmas
1384
1385.. index:: Pragmas, configuration
1386
1387Configuration pragmas include those pragmas described as
1388such in the Ada Reference Manual, as well as
1389implementation-dependent pragmas that are configuration pragmas.
1390See the ``Implementation_Defined_Pragmas`` chapter in the
1391:title:`GNAT_Reference_Manual` for details on these
1392additional GNAT-specific configuration pragmas.
1393Most notably, the pragma ``Source_File_Name``, which allows
1394specifying non-default names for source files, is a configuration
1395pragma. The following is a complete list of configuration pragmas
1396recognized by GNAT::
1397
1398     Ada_83
1399     Ada_95
1400     Ada_05
1401     Ada_2005
1402     Ada_12
1403     Ada_2012
1404     Allow_Integer_Address
1405     Annotate
1406     Assertion_Policy
1407     Assume_No_Invalid_Values
1408     C_Pass_By_Copy
1409     Check_Float_Overflow
1410     Check_Name
1411     Check_Policy
1412     Compile_Time_Error
1413     Compile_Time_Warning
1414     Compiler_Unit
1415     Compiler_Unit_Warning
1416     Component_Alignment
1417     Convention_Identifier
1418     Debug_Policy
1419     Detect_Blocking
1420     Default_Scalar_Storage_Order
1421     Default_Storage_Pool
1422     Disable_Atomic_Synchronization
1423     Discard_Names
1424     Elaboration_Checks
1425     Eliminate
1426     Enable_Atomic_Synchronization
1427     Extend_System
1428     Extensions_Allowed
1429     External_Name_Casing
1430     Fast_Math
1431     Favor_Top_Level
1432     Ignore_Pragma
1433     Implicit_Packing
1434     Initialize_Scalars
1435     Interrupt_State
1436     License
1437     Locking_Policy
1438     No_Component_Reordering
1439     No_Heap_Finalization
1440     No_Run_Time
1441     No_Strict_Aliasing
1442     Normalize_Scalars
1443     Optimize_Alignment
1444     Overflow_Mode
1445     Overriding_Renamings
1446     Partition_Elaboration_Policy
1447     Persistent_BSS
1448     Prefix_Exception_Messages
1449     Priority_Specific_Dispatching
1450     Profile
1451     Profile_Warnings
1452     Propagate_Exceptions
1453     Queuing_Policy
1454     Rational
1455     Ravenscar
1456     Rename_Pragma
1457     Restricted_Run_Time
1458     Restrictions
1459     Restrictions_Warnings
1460     Reviewable
1461     Short_Circuit_And_Or
1462     Short_Descriptors
1463     Source_File_Name
1464     Source_File_Name_Project
1465     SPARK_Mode
1466     Style_Checks
1467     Suppress
1468     Suppress_Exception_Locations
1469     Task_Dispatching_Policy
1470     Unevaluated_Use_Of_Old
1471     Universal_Data
1472     Unsuppress
1473     Use_VADS_Size
1474     Validity_Checks
1475     Warning_As_Error
1476     Warnings
1477     Wide_Character_Encoding
1478
1479
1480.. _Handling_of_Configuration_Pragmas:
1481
1482Handling of Configuration Pragmas
1483---------------------------------
1484
1485Configuration pragmas may either appear at the start of a compilation
1486unit, or they can appear in a configuration pragma file to apply to
1487all compilations performed in a given compilation environment.
1488
1489GNAT also provides the ``gnatchop`` utility to provide an automatic
1490way to handle configuration pragmas following the semantics for
1491compilations (that is, files with multiple units), described in the RM.
1492See :ref:`Operating_gnatchop_in_Compilation_Mode` for details.
1493However, for most purposes, it will be more convenient to edit the
1494:file:`gnat.adc` file that contains configuration pragmas directly,
1495as described in the following section.
1496
1497In the case of ``Restrictions`` pragmas appearing as configuration
1498pragmas in individual compilation units, the exact handling depends on
1499the type of restriction.
1500
1501Restrictions that require partition-wide consistency (like
1502``No_Tasking``) are
1503recognized wherever they appear
1504and can be freely inherited, e.g. from a |withed| unit to the |withing|
1505unit. This makes sense since the binder will in any case insist on seeing
1506consistent use, so any unit not conforming to any restrictions that are
1507anywhere in the partition will be rejected, and you might as well find
1508that out at compile time rather than at bind time.
1509
1510For restrictions that do not require partition-wide consistency, e.g.
1511SPARK or No_Implementation_Attributes, in general the restriction applies
1512only to the unit in which the pragma appears, and not to any other units.
1513
1514The exception is No_Elaboration_Code which always applies to the entire
1515object file from a compilation, i.e. to the body, spec, and all subunits.
1516This restriction can be specified in a configuration pragma file, or it
1517can be on the body and/or the spec (in eithe case it applies to all the
1518relevant units). It can appear on a subunit only if it has previously
1519appeared in the body of spec.
1520
1521
1522.. _The_Configuration_Pragmas_Files:
1523
1524The Configuration Pragmas Files
1525-------------------------------
1526
1527.. index:: gnat.adc
1528
1529In GNAT a compilation environment is defined by the current
1530directory at the time that a compile command is given. This current
1531directory is searched for a file whose name is :file:`gnat.adc`. If
1532this file is present, it is expected to contain one or more
1533configuration pragmas that will be applied to the current compilation.
1534However, if the switch :switch:`-gnatA` is used, :file:`gnat.adc` is not
1535considered. When taken into account, :file:`gnat.adc` is added to the
1536dependencies, so that if :file:`gnat.adc` is modified later, an invocation of
1537``gnatmake`` will recompile the source.
1538
1539Configuration pragmas may be entered into the :file:`gnat.adc` file
1540either by running ``gnatchop`` on a source file that consists only of
1541configuration pragmas, or more conveniently by direct editing of the
1542:file:`gnat.adc` file, which is a standard format source file.
1543
1544Besides :file:`gnat.adc`, additional files containing configuration
1545pragmas may be applied to the current compilation using the switch
1546:switch:`-gnatec={path}` where ``path`` must designate an existing file that
1547contains only configuration pragmas. These configuration pragmas are
1548in addition to those found in :file:`gnat.adc` (provided :file:`gnat.adc`
1549is present and switch :switch:`-gnatA` is not used).
1550
1551It is allowable to specify several switches :switch:`-gnatec=`, all of which
1552will be taken into account.
1553
1554Files containing configuration pragmas specified with switches
1555:switch:`-gnatec=` are added to the dependencies, unless they are
1556temporary files. A file is considered temporary if its name ends in
1557:file:`.tmp` or :file:`.TMP`. Certain tools follow this naming
1558convention because they pass information to ``gcc`` via
1559temporary files that are immediately deleted; it doesn't make sense to
1560depend on a file that no longer exists. Such tools include
1561``gprbuild``, ``gnatmake``, and ``gnatcheck``.
1562
1563By default, configuration pragma files are stored by their absolute paths in
1564ALI files. You can use the :switch:`-gnateb` switch in order to store them by
1565their basename instead.
1566
1567If you are using project file, a separate mechanism is provided using
1568project attributes.
1569
1570.. --Comment
1571   See :ref:`Specifying_Configuration_Pragmas` for more details.
1572
1573
1574.. _Generating_Object_Files:
1575
1576Generating Object Files
1577=======================
1578
1579An Ada program consists of a set of source files, and the first step in
1580compiling the program is to generate the corresponding object files.
1581These are generated by compiling a subset of these source files.
1582The files you need to compile are the following:
1583
1584* If a package spec has no body, compile the package spec to produce the
1585  object file for the package.
1586
1587* If a package has both a spec and a body, compile the body to produce the
1588  object file for the package. The source file for the package spec need
1589  not be compiled in this case because there is only one object file, which
1590  contains the code for both the spec and body of the package.
1591
1592* For a subprogram, compile the subprogram body to produce the object file
1593  for the subprogram. The spec, if one is present, is as usual in a
1594  separate file, and need not be compiled.
1595
1596.. index:: Subunits
1597
1598* In the case of subunits, only compile the parent unit. A single object
1599  file is generated for the entire subunit tree, which includes all the
1600  subunits.
1601
1602* Compile child units independently of their parent units
1603  (though, of course, the spec of all the ancestor unit must be present in order
1604  to compile a child unit).
1605
1606  .. index:: Generics
1607
1608* Compile generic units in the same manner as any other units. The object
1609  files in this case are small dummy files that contain at most the
1610  flag used for elaboration checking. This is because GNAT always handles generic
1611  instantiation by means of macro expansion. However, it is still necessary to
1612  compile generic units, for dependency checking and elaboration purposes.
1613
1614The preceding rules describe the set of files that must be compiled to
1615generate the object files for a program. Each object file has the same
1616name as the corresponding source file, except that the extension is
1617:file:`.o` as usual.
1618
1619You may wish to compile other files for the purpose of checking their
1620syntactic and semantic correctness. For example, in the case where a
1621package has a separate spec and body, you would not normally compile the
1622spec. However, it is convenient in practice to compile the spec to make
1623sure it is error-free before compiling clients of this spec, because such
1624compilations will fail if there is an error in the spec.
1625
1626GNAT provides an option for compiling such files purely for the
1627purposes of checking correctness; such compilations are not required as
1628part of the process of building a program. To compile a file in this
1629checking mode, use the :switch:`-gnatc` switch.
1630
1631.. _Source_Dependencies:
1632
1633Source Dependencies
1634===================
1635
1636A given object file clearly depends on the source file which is compiled
1637to produce it. Here we are using "depends" in the sense of a typical
1638``make`` utility; in other words, an object file depends on a source
1639file if changes to the source file require the object file to be
1640recompiled.
1641In addition to this basic dependency, a given object may depend on
1642additional source files as follows:
1643
1644* If a file being compiled |withs| a unit ``X``, the object file
1645  depends on the file containing the spec of unit ``X``. This includes
1646  files that are |withed| implicitly either because they are parents
1647  of |withed| child units or they are run-time units required by the
1648  language constructs used in a particular unit.
1649
1650* If a file being compiled instantiates a library level generic unit, the
1651  object file depends on both the spec and body files for this generic
1652  unit.
1653
1654* If a file being compiled instantiates a generic unit defined within a
1655  package, the object file depends on the body file for the package as
1656  well as the spec file.
1657
1658.. index:: Inline
1659.. index:: -gnatn switch
1660
1661* If a file being compiled contains a call to a subprogram for which
1662  pragma ``Inline`` applies and inlining is activated with the
1663  :switch:`-gnatn` switch, the object file depends on the file containing the
1664  body of this subprogram as well as on the file containing the spec. Note
1665  that for inlining to actually occur as a result of the use of this switch,
1666  it is necessary to compile in optimizing mode.
1667
1668  .. index:: -gnatN switch
1669
1670  The use of :switch:`-gnatN` activates  inlining optimization
1671  that is performed by the front end of the compiler. This inlining does
1672  not require that the code generation be optimized. Like :switch:`-gnatn`,
1673  the use of this switch generates additional dependencies.
1674
1675  When using a gcc-based back end (in practice this means using any version
1676  of GNAT other than for the JVM, .NET or GNAAMP platforms), then the use of
1677  :switch:`-gnatN` is deprecated, and the use of :switch:`-gnatn` is preferred.
1678  Historically front end inlining was more extensive than the gcc back end
1679  inlining, but that is no longer the case.
1680
1681* If an object file :file:`O` depends on the proper body of a subunit through
1682  inlining or instantiation, it depends on the parent unit of the subunit.
1683  This means that any modification of the parent unit or one of its subunits
1684  affects the compilation of :file:`O`.
1685
1686* The object file for a parent unit depends on all its subunit body files.
1687
1688* The previous two rules meant that for purposes of computing dependencies and
1689  recompilation, a body and all its subunits are treated as an indivisible whole.
1690
1691  These rules are applied transitively: if unit ``A`` |withs|
1692  unit ``B``, whose elaboration calls an inlined procedure in package
1693  ``C``, the object file for unit ``A`` will depend on the body of
1694  ``C``, in file :file:`c.adb`.
1695
1696  The set of dependent files described by these rules includes all the
1697  files on which the unit is semantically dependent, as dictated by the
1698  Ada language standard. However, it is a superset of what the
1699  standard describes, because it includes generic, inline, and subunit
1700  dependencies.
1701
1702  An object file must be recreated by recompiling the corresponding source
1703  file if any of the source files on which it depends are modified. For
1704  example, if the ``make`` utility is used to control compilation,
1705  the rule for an Ada object file must mention all the source files on
1706  which the object file depends, according to the above definition.
1707  The determination of the necessary
1708  recompilations is done automatically when one uses ``gnatmake``.
1709
1710.. _The_Ada_Library_Information_Files:
1711
1712The Ada Library Information Files
1713=================================
1714
1715.. index:: Ada Library Information files
1716
1717.. index:: ALI files
1718
1719Each compilation actually generates two output files. The first of these
1720is the normal object file that has a :file:`.o` extension. The second is a
1721text file containing full dependency information. It has the same
1722name as the source file, but an :file:`.ali` extension.
1723This file is known as the Ada Library Information (:file:`ALI`) file.
1724The following information is contained in the :file:`ALI` file.
1725
1726* Version information (indicates which version of GNAT was used to compile
1727  the unit(s) in question)
1728
1729* Main program information (including priority and time slice settings,
1730  as well as the wide character encoding used during compilation).
1731
1732* List of arguments used in the ``gcc`` command for the compilation
1733
1734* Attributes of the unit, including configuration pragmas used, an indication
1735  of whether the compilation was successful, exception model used etc.
1736
1737* A list of relevant restrictions applying to the unit (used for consistency)
1738  checking.
1739
1740* Categorization information (e.g., use of pragma ``Pure``).
1741
1742* Information on all |withed| units, including presence of
1743  ``Elaborate`` or ``Elaborate_All`` pragmas.
1744
1745* Information from any ``Linker_Options`` pragmas used in the unit
1746
1747* Information on the use of ``Body_Version`` or ``Version``
1748  attributes in the unit.
1749
1750* Dependency information. This is a list of files, together with
1751  time stamp and checksum information. These are files on which
1752  the unit depends in the sense that recompilation is required
1753  if any of these units are modified.
1754
1755* Cross-reference data. Contains information on all entities referenced
1756  in the unit. Used by tools like ``gnatxref`` and ``gnatfind`` to
1757  provide cross-reference information.
1758
1759For a full detailed description of the format of the :file:`ALI` file,
1760see the source of the body of unit ``Lib.Writ``, contained in file
1761:file:`lib-writ.adb` in the GNAT compiler sources.
1762
1763
1764.. _Binding_an_Ada_Program:
1765
1766Binding an Ada Program
1767======================
1768
1769When using languages such as C and C++, once the source files have been
1770compiled the only remaining step in building an executable program
1771is linking the object modules together. This means that it is possible to
1772link an inconsistent version of a program, in which two units have
1773included different versions of the same header.
1774
1775The rules of Ada do not permit such an inconsistent program to be built.
1776For example, if two clients have different versions of the same package,
1777it is illegal to build a program containing these two clients.
1778These rules are enforced by the GNAT binder, which also determines an
1779elaboration order consistent with the Ada rules.
1780
1781The GNAT binder is run after all the object files for a program have
1782been created. It is given the name of the main program unit, and from
1783this it determines the set of units required by the program, by reading the
1784corresponding ALI files. It generates error messages if the program is
1785inconsistent or if no valid order of elaboration exists.
1786
1787If no errors are detected, the binder produces a main program, in Ada by
1788default, that contains calls to the elaboration procedures of those
1789compilation unit that require them, followed by
1790a call to the main program. This Ada program is compiled to generate the
1791object file for the main program. The name of
1792the Ada file is :file:`b~xxx`.adb` (with the corresponding spec
1793:file:`b~xxx`.ads`) where ``xxx`` is the name of the
1794main program unit.
1795
1796Finally, the linker is used to build the resulting executable program,
1797using the object from the main program from the bind step as well as the
1798object files for the Ada units of the program.
1799
1800
1801.. _GNAT_and_Libraries:
1802
1803GNAT and Libraries
1804==================
1805
1806.. index:: Library building and using
1807
1808This section describes how to build and use libraries with GNAT, and also shows
1809how to recompile the GNAT run-time library. You should be familiar with the
1810Project Manager facility (see the *GNAT_Project_Manager* chapter of the
1811*GPRbuild User's Guide*) before reading this chapter.
1812
1813.. _Introduction_to_Libraries_in_GNAT:
1814
1815Introduction to Libraries in GNAT
1816---------------------------------
1817
1818A library is, conceptually, a collection of objects which does not have its
1819own main thread of execution, but rather provides certain services to the
1820applications that use it. A library can be either statically linked with the
1821application, in which case its code is directly included in the application,
1822or, on platforms that support it, be dynamically linked, in which case
1823its code is shared by all applications making use of this library.
1824
1825GNAT supports both types of libraries.
1826In the static case, the compiled code can be provided in different ways. The
1827simplest approach is to provide directly the set of objects resulting from
1828compilation of the library source files. Alternatively, you can group the
1829objects into an archive using whatever commands are provided by the operating
1830system. For the latter case, the objects are grouped into a shared library.
1831
1832In the GNAT environment, a library has three types of components:
1833
1834*  Source files,
1835
1836*  :file:`ALI` files (see :ref:`The_Ada_Library_Information_Files`), and
1837
1838*  Object files, an archive or a shared library.
1839
1840A GNAT library may expose all its source files, which is useful for
1841documentation purposes. Alternatively, it may expose only the units needed by
1842an external user to make use of the library. That is to say, the specs
1843reflecting the library services along with all the units needed to compile
1844those specs, which can include generic bodies or any body implementing an
1845inlined routine. In the case of *stand-alone libraries* those exposed
1846units are called *interface units* (:ref:`Stand-alone_Ada_Libraries`).
1847
1848All compilation units comprising an application, including those in a library,
1849need to be elaborated in an order partially defined by Ada's semantics. GNAT
1850computes the elaboration order from the :file:`ALI` files and this is why they
1851constitute a mandatory part of GNAT libraries.
1852*Stand-alone libraries* are the exception to this rule because a specific
1853library elaboration routine is produced independently of the application(s)
1854using the library.
1855
1856.. _General_Ada_Libraries:
1857
1858General Ada Libraries
1859---------------------
1860
1861
1862.. _Building_a_library:
1863
1864Building a library
1865^^^^^^^^^^^^^^^^^^
1866
1867The easiest way to build a library is to use the Project Manager,
1868which supports a special type of project called a *Library Project*
1869(see the *Library Projects* section in the *GNAT Project Manager*
1870chapter of the *GPRbuild User's Guide*).
1871
1872A project is considered a library project, when two project-level attributes
1873are defined in it: ``Library_Name`` and ``Library_Dir``. In order to
1874control different aspects of library configuration, additional optional
1875project-level attributes can be specified:
1876
1877* ``Library_Kind``
1878    This attribute controls whether the library is to be static or dynamic
1879
1880
1881* ``Library_Version``
1882    This attribute specifies the library version; this value is used
1883    during dynamic linking of shared libraries to determine if the currently
1884    installed versions of the binaries are compatible.
1885
1886* ``Library_Options``
1887
1888* ``Library_GCC``
1889    These attributes specify additional low-level options to be used during
1890    library generation, and redefine the actual application used to generate
1891    library.
1892
1893The GNAT Project Manager takes full care of the library maintenance task,
1894including recompilation of the source files for which objects do not exist
1895or are not up to date, assembly of the library archive, and installation of
1896the library (i.e., copying associated source, object and :file:`ALI` files
1897to the specified location).
1898
1899Here is a simple library project file:
1900
1901.. code-block:: gpr
1902
1903       project My_Lib is
1904         for Source_Dirs use ("src1", "src2");
1905         for Object_Dir use "obj";
1906         for Library_Name use "mylib";
1907         for Library_Dir use "lib";
1908         for Library_Kind use "dynamic";
1909       end My_lib;
1910
1911and the compilation command to build and install the library:
1912
1913.. code-block:: sh
1914
1915     $ gnatmake -Pmy_lib
1916
1917It is not entirely trivial to perform manually all the steps required to
1918produce a library. We recommend that you use the GNAT Project Manager
1919for this task. In special cases where this is not desired, the necessary
1920steps are discussed below.
1921
1922There are various possibilities for compiling the units that make up the
1923library: for example with a Makefile (:ref:`Using_the_GNU_make_Utility`) or
1924with a conventional script. For simple libraries, it is also possible to create
1925a dummy main program which depends upon all the packages that comprise the
1926interface of the library. This dummy main program can then be given to
1927``gnatmake``, which will ensure that all necessary objects are built.
1928
1929After this task is accomplished, you should follow the standard procedure
1930of the underlying operating system to produce the static or shared library.
1931
1932Here is an example of such a dummy program:
1933
1934.. code-block:: ada
1935
1936       with My_Lib.Service1;
1937       with My_Lib.Service2;
1938       with My_Lib.Service3;
1939       procedure My_Lib_Dummy is
1940       begin
1941          null;
1942       end;
1943
1944Here are the generic commands that will build an archive or a shared library.
1945
1946.. code-block:: sh
1947
1948     # compiling the library
1949     $ gnatmake -c my_lib_dummy.adb
1950
1951     # we don't need the dummy object itself
1952     $ rm my_lib_dummy.o my_lib_dummy.ali
1953
1954     # create an archive with the remaining objects
1955     $ ar rc libmy_lib.a *.o
1956     # some systems may require "ranlib" to be run as well
1957
1958     # or create a shared library
1959     $ gcc -shared -o libmy_lib.so *.o
1960     # some systems may require the code to have been compiled with -fPIC
1961
1962     # remove the object files that are now in the library
1963     $ rm *.o
1964
1965     # Make the ALI files read-only so that gnatmake will not try to
1966     # regenerate the objects that are in the library
1967     $ chmod -w *.ali
1968
1969Please note that the library must have a name of the form :file:`lib{xxx}.a`
1970or :file:`lib{xxx}.so` (or :file:`lib{xxx}.dll` on Windows) in order to
1971be accessed by the directive :switch:`-l{xxx}` at link time.
1972
1973.. _Installing_a_library:
1974
1975Installing a library
1976^^^^^^^^^^^^^^^^^^^^
1977
1978.. index:: ADA_PROJECT_PATH
1979.. index:: GPR_PROJECT_PATH
1980
1981If you use project files, library installation is part of the library build
1982process (see the *Installing a Library with Project Files* section of the
1983*GNAT Project Manager* chapter of the *GPRbuild User's Guide*).
1984
1985When project files are not an option, it is also possible, but not recommended,
1986to install the library so that the sources needed to use the library are on the
1987Ada source path and the ALI files & libraries be on the Ada Object path (see
1988:ref:`Search_Paths_and_the_Run-Time_Library_RTL`. Alternatively, the system
1989administrator can place general-purpose libraries in the default compiler
1990paths, by specifying the libraries' location in the configuration files
1991:file:`ada_source_path` and :file:`ada_object_path`. These configuration files
1992must be located in the GNAT installation tree at the same place as the gcc spec
1993file. The location of the gcc spec file can be determined as follows:
1994
1995.. code-block:: sh
1996
1997     $ gcc -v
1998
1999
2000The configuration files mentioned above have a simple format: each line
2001must contain one unique directory name.
2002Those names are added to the corresponding path
2003in their order of appearance in the file. The names can be either absolute
2004or relative; in the latter case, they are relative to where theses files
2005are located.
2006
2007The files :file:`ada_source_path` and :file:`ada_object_path` might not be
2008present in a
2009GNAT installation, in which case, GNAT will look for its run-time library in
2010the directories :file:`adainclude` (for the sources) and :file:`adalib` (for the
2011objects and :file:`ALI` files). When the files exist, the compiler does not
2012look in :file:`adainclude` and :file:`adalib`, and thus the
2013:file:`ada_source_path` file
2014must contain the location for the GNAT run-time sources (which can simply
2015be :file:`adainclude`). In the same way, the :file:`ada_object_path` file must
2016contain the location for the GNAT run-time objects (which can simply
2017be :file:`adalib`).
2018
2019You can also specify a new default path to the run-time library at compilation
2020time with the switch :switch:`--RTS=rts-path`. You can thus choose / change
2021the run-time library you want your program to be compiled with. This switch is
2022recognized by ``gcc``, ``gnatmake``, ``gnatbind``,
2023``gnatls``, ``gnatfind`` and ``gnatxref``.
2024
2025It is possible to install a library before or after the standard GNAT
2026library, by reordering the lines in the configuration files. In general, a
2027library must be installed before the GNAT library if it redefines
2028any part of it.
2029
2030.. _Using_a_library:
2031
2032Using a library
2033^^^^^^^^^^^^^^^
2034
2035Once again, the project facility greatly simplifies the use of
2036libraries. In this context, using a library is just a matter of adding a
2037|with| clause in the user project. For instance, to make use of the
2038library ``My_Lib`` shown in examples in earlier sections, you can
2039write:
2040
2041.. code-block:: gpr
2042
2043       with "my_lib";
2044       project My_Proj is
2045         ...
2046       end My_Proj;
2047
2048Even if you have a third-party, non-Ada library, you can still use GNAT's
2049Project Manager facility to provide a wrapper for it. For example, the
2050following project, when |withed| by your main project, will link with the
2051third-party library :file:`liba.a`:
2052
2053.. code-block:: gpr
2054
2055       project Liba is
2056          for Externally_Built use "true";
2057          for Source_Files use ();
2058          for Library_Dir use "lib";
2059          for Library_Name use "a";
2060          for Library_Kind use "static";
2061       end Liba;
2062
2063This is an alternative to the use of ``pragma Linker_Options``. It is
2064especially interesting in the context of systems with several interdependent
2065static libraries where finding a proper linker order is not easy and best be
2066left to the tools having visibility over project dependence information.
2067
2068In order to use an Ada library manually, you need to make sure that this
2069library is on both your source and object path
2070(see :ref:`Search_Paths_and_the_Run-Time_Library_RTL`
2071and :ref:`Search_Paths_for_gnatbind`). Furthermore, when the objects are grouped
2072in an archive or a shared library, you need to specify the desired
2073library at link time.
2074
2075For example, you can use the library :file:`mylib` installed in
2076:file:`/dir/my_lib_src` and :file:`/dir/my_lib_obj` with the following commands:
2077
2078.. code-block:: sh
2079
2080     $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \\
2081       -largs -lmy_lib
2082
2083This can be expressed more simply:
2084
2085.. code-block:: sh
2086
2087    $ gnatmake my_appl
2088
2089when the following conditions are met:
2090
2091* :file:`/dir/my_lib_src` has been added by the user to the environment
2092  variable :envvar:`ADA_INCLUDE_PATH`, or by the administrator to the file
2093  :file:`ada_source_path`
2094
2095* :file:`/dir/my_lib_obj` has been added by the user to the environment
2096  variable :envvar:`ADA_OBJECTS_PATH`, or by the administrator to the file
2097  :file:`ada_object_path`
2098
2099* a pragma ``Linker_Options`` has been added to one of the sources.
2100  For example:
2101
2102  .. code-block:: ada
2103
2104       pragma Linker_Options ("-lmy_lib");
2105
2106Note that you may also load a library dynamically at
2107run time given its filename, as illustrated in the GNAT :file:`plugins` example
2108in the directory :file:`share/examples/gnat/plugins` within the GNAT
2109install area.
2110
2111.. _Stand-alone_Ada_Libraries:
2112
2113Stand-alone Ada Libraries
2114-------------------------
2115
2116.. index:: ! Stand-alone libraries
2117
2118.. _Introduction_to_Stand-alone_Libraries:
2119
2120Introduction to Stand-alone Libraries
2121^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2122
2123A Stand-alone Library (abbreviated 'SAL') is a library that contains the
2124necessary code to
2125elaborate the Ada units that are included in the library. In contrast with
2126an ordinary library, which consists of all sources, objects and :file:`ALI`
2127files of the
2128library, a SAL may specify a restricted subset of compilation units
2129to serve as a library interface. In this case, the fully
2130self-sufficient set of files will normally consist of an objects
2131archive, the sources of interface units' specs, and the :file:`ALI`
2132files of interface units.
2133If an interface spec contains a generic unit or an inlined subprogram,
2134the body's
2135source must also be provided; if the units that must be provided in the source
2136form depend on other units, the source and :file:`ALI` files of those must
2137also be provided.
2138
2139The main purpose of a SAL is to minimize the recompilation overhead of client
2140applications when a new version of the library is installed. Specifically,
2141if the interface sources have not changed, client applications do not need to
2142be recompiled. If, furthermore, a SAL is provided in the shared form and its
2143version, controlled by ``Library_Version`` attribute, is not changed,
2144then the clients do not need to be relinked.
2145
2146SALs also allow the library providers to minimize the amount of library source
2147text exposed to the clients.  Such 'information hiding' might be useful or
2148necessary for various reasons.
2149
2150Stand-alone libraries are also well suited to be used in an executable whose
2151main routine is not written in Ada.
2152
2153.. _Building_a_Stand-alone_Library:
2154
2155Building a Stand-alone Library
2156^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2157
2158GNAT's Project facility provides a simple way of building and installing
2159stand-alone libraries; see the *Stand-alone Library Projects* section
2160in the *GNAT Project Manager* chapter of the *GPRbuild User's Guide*.
2161To be a Stand-alone Library Project, in addition to the two attributes
2162that make a project a Library Project (``Library_Name`` and
2163``Library_Dir``; see the *Library Projects* section in the
2164*GNAT Project Manager* chapter of the *GPRbuild User's Guide*),
2165the attribute ``Library_Interface`` must be defined.  For example:
2166
2167.. code-block:: gpr
2168
2169       for Library_Dir use "lib_dir";
2170       for Library_Name use "dummy";
2171       for Library_Interface use ("int1", "int1.child");
2172
2173Attribute ``Library_Interface`` has a non-empty string list value,
2174each string in the list designating a unit contained in an immediate source
2175of the project file.
2176
2177When a Stand-alone Library is built, first the binder is invoked to build
2178a package whose name depends on the library name
2179(:file:`b~dummy.ads/b` in the example above).
2180This binder-generated package includes initialization and
2181finalization procedures whose
2182names depend on the library name (``dummyinit`` and ``dummyfinal``
2183in the example
2184above). The object corresponding to this package is included in the library.
2185
2186You must ensure timely (e.g., prior to any use of interfaces in the SAL)
2187calling of these procedures if a static SAL is built, or if a shared SAL
2188is built
2189with the project-level attribute ``Library_Auto_Init`` set to
2190``"false"``.
2191
2192For a Stand-Alone Library, only the :file:`ALI` files of the Interface Units
2193(those that are listed in attribute ``Library_Interface``) are copied to
2194the Library Directory. As a consequence, only the Interface Units may be
2195imported from Ada units outside of the library. If other units are imported,
2196the binding phase will fail.
2197
2198It is also possible to build an encapsulated library where not only
2199the code to elaborate and finalize the library is embedded but also
2200ensuring that the library is linked only against static
2201libraries. So an encapsulated library only depends on system
2202libraries, all other code, including the GNAT runtime, is embedded. To
2203build an encapsulated library the attribute
2204``Library_Standalone`` must be set to ``encapsulated``:
2205
2206.. code-block:: gpr
2207
2208       for Library_Dir use "lib_dir";
2209       for Library_Name use "dummy";
2210       for Library_Kind use "dynamic";
2211       for Library_Interface use ("int1", "int1.child");
2212       for Library_Standalone use "encapsulated";
2213
2214The default value for this attribute is ``standard`` in which case
2215a stand-alone library is built.
2216
2217The attribute ``Library_Src_Dir`` may be specified for a
2218Stand-Alone Library. ``Library_Src_Dir`` is a simple attribute that has a
2219single string value. Its value must be the path (absolute or relative to the
2220project directory) of an existing directory. This directory cannot be the
2221object directory or one of the source directories, but it can be the same as
2222the library directory. The sources of the Interface
2223Units of the library that are needed by an Ada client of the library will be
2224copied to the designated directory, called the Interface Copy directory.
2225These sources include the specs of the Interface Units, but they may also
2226include bodies and subunits, when pragmas ``Inline`` or ``Inline_Always``
2227are used, or when there is a generic unit in the spec. Before the sources
2228are copied to the Interface Copy directory, an attempt is made to delete all
2229files in the Interface Copy directory.
2230
2231Building stand-alone libraries by hand is somewhat tedious, but for those
2232occasions when it is necessary here are the steps that you need to perform:
2233
2234* Compile all library sources.
2235
2236* Invoke the binder with the switch :switch:`-n` (No Ada main program),
2237  with all the :file:`ALI` files of the interfaces, and
2238  with the switch :switch:`-L` to give specific names to the ``init``
2239  and ``final`` procedures.  For example:
2240
2241  .. code-block:: sh
2242
2243      $ gnatbind -n int1.ali int2.ali -Lsal1
2244
2245* Compile the binder generated file:
2246
2247  .. code-block:: sh
2248
2249      $ gcc -c b~int2.adb
2250
2251* Link the dynamic library with all the necessary object files,
2252  indicating to the linker the names of the ``init`` (and possibly
2253  ``final``) procedures for automatic initialization (and finalization).
2254  The built library should be placed in a directory different from
2255  the object directory.
2256
2257* Copy the ``ALI`` files of the interface to the library directory,
2258  add in this copy an indication that it is an interface to a SAL
2259  (i.e., add a word ``SL`` on the line in the :file:`ALI` file that starts
2260  with letter 'P') and make the modified copy of the :file:`ALI` file
2261  read-only.
2262
2263Using SALs is not different from using other libraries
2264(see :ref:`Using_a_library`).
2265
2266.. _Creating_a_Stand-alone_Library_to_be_used_in_a_non-Ada_context:
2267
2268Creating a Stand-alone Library to be used in a non-Ada context
2269^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2270
2271It is easy to adapt the SAL build procedure discussed above for use of a SAL in
2272a non-Ada context.
2273
2274The only extra step required is to ensure that library interface subprograms
2275are compatible with the main program, by means of ``pragma Export``
2276or ``pragma Convention``.
2277
2278Here is an example of simple library interface for use with C main program:
2279
2280.. code-block:: ada
2281
2282       package My_Package is
2283
2284          procedure Do_Something;
2285          pragma Export (C, Do_Something, "do_something");
2286
2287          procedure Do_Something_Else;
2288          pragma Export (C, Do_Something_Else, "do_something_else");
2289
2290       end My_Package;
2291
2292On the foreign language side, you must provide a 'foreign' view of the
2293library interface; remember that it should contain elaboration routines in
2294addition to interface subprograms.
2295
2296The example below shows the content of :file:`mylib_interface.h` (note
2297that there is no rule for the naming of this file, any name can be used)
2298
2299.. code-block:: c
2300
2301       /* the library elaboration procedure */
2302       extern void mylibinit (void);
2303
2304       /* the library finalization procedure */
2305       extern void mylibfinal (void);
2306
2307       /* the interface exported by the library */
2308       extern void do_something (void);
2309       extern void do_something_else (void);
2310
2311Libraries built as explained above can be used from any program, provided
2312that the elaboration procedures (named ``mylibinit`` in the previous
2313example) are called before the library services are used. Any number of
2314libraries can be used simultaneously, as long as the elaboration
2315procedure of each library is called.
2316
2317Below is an example of a C program that uses the ``mylib`` library.
2318
2319.. code-block:: c
2320
2321       #include "mylib_interface.h"
2322
2323       int
2324       main (void)
2325       {
2326          /* First, elaborate the library before using it */
2327          mylibinit ();
2328
2329          /* Main program, using the library exported entities */
2330          do_something ();
2331          do_something_else ();
2332
2333          /* Library finalization at the end of the program */
2334          mylibfinal ();
2335          return 0;
2336       }
2337
2338Note that invoking any library finalization procedure generated by
2339``gnatbind`` shuts down the Ada run-time environment.
2340Consequently, the
2341finalization of all Ada libraries must be performed at the end of the program.
2342No call to these libraries or to the Ada run-time library should be made
2343after the finalization phase.
2344
2345Note also that special care must be taken with multi-tasks
2346applications. The initialization and finalization routines are not
2347protected against concurrent access. If such requirement is needed it
2348must be ensured at the application level using a specific operating
2349system services like a mutex or a critical-section.
2350
2351.. _Restrictions_in_Stand-alone_Libraries:
2352
2353Restrictions in Stand-alone Libraries
2354^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2355
2356The pragmas listed below should be used with caution inside libraries,
2357as they can create incompatibilities with other Ada libraries:
2358
2359* pragma ``Locking_Policy``
2360* pragma ``Partition_Elaboration_Policy``
2361* pragma ``Queuing_Policy``
2362* pragma ``Task_Dispatching_Policy``
2363* pragma ``Unreserve_All_Interrupts``
2364
2365When using a library that contains such pragmas, the user must make sure
2366that all libraries use the same pragmas with the same values. Otherwise,
2367``Program_Error`` will
2368be raised during the elaboration of the conflicting
2369libraries. The usage of these pragmas and its consequences for the user
2370should therefore be well documented.
2371
2372Similarly, the traceback in the exception occurrence mechanism should be
2373enabled or disabled in a consistent manner across all libraries.
2374Otherwise, Program_Error will be raised during the elaboration of the
2375conflicting libraries.
2376
2377If the ``Version`` or ``Body_Version``
2378attributes are used inside a library, then you need to
2379perform a ``gnatbind`` step that specifies all :file:`ALI` files in all
2380libraries, so that version identifiers can be properly computed.
2381In practice these attributes are rarely used, so this is unlikely
2382to be a consideration.
2383
2384.. _Rebuilding_the_GNAT_Run-Time_Library:
2385
2386Rebuilding the GNAT Run-Time Library
2387------------------------------------
2388
2389.. index:: GNAT Run-Time Library, rebuilding
2390.. index:: Building the GNAT Run-Time Library
2391.. index:: Rebuilding the GNAT Run-Time Library
2392.. index:: Run-Time Library, rebuilding
2393
2394It may be useful to recompile the GNAT library in various debugging or
2395experimentation contexts. A project file called
2396:file:`libada.gpr` is provided to that effect and can be found in
2397the directory containing the GNAT library. The location of this
2398directory depends on the way the GNAT environment has been installed and can
2399be determined by means of the command:
2400
2401.. code-block:: sh
2402
2403      $ gnatls -v
2404
2405The last entry in the source search path usually contains the
2406gnat library (the :file:`adainclude` directory). This project file contains its
2407own documentation and in particular the set of instructions needed to rebuild a
2408new library and to use it.
2409
2410Note that rebuilding the GNAT Run-Time is only recommended for temporary
2411experiments or debugging, and is not supported.
2412
2413
2414.. index:: ! Conditional compilation
2415
2416.. _Conditional_Compilation:
2417
2418Conditional Compilation
2419=======================
2420
2421This section presents some guidelines for modeling conditional compilation in Ada and describes the
2422gnatprep preprocessor utility.
2423
2424.. index:: ! Conditional compilation
2425
2426.. _Modeling_Conditional_Compilation_in_Ada:
2427
2428Modeling Conditional Compilation in Ada
2429---------------------------------------
2430
2431It is often necessary to arrange for a single source program
2432to serve multiple purposes, where it is compiled in different
2433ways to achieve these different goals. Some examples of the
2434need for this feature are
2435
2436* Adapting a program to a different hardware environment
2437* Adapting a program to a different target architecture
2438* Turning debugging features on and off
2439* Arranging for a program to compile with different compilers
2440
2441In C, or C++, the typical approach would be to use the preprocessor
2442that is defined as part of the language. The Ada language does not
2443contain such a feature. This is not an oversight, but rather a very
2444deliberate design decision, based on the experience that overuse of
2445the preprocessing features in C and C++ can result in programs that
2446are extremely difficult to maintain. For example, if we have ten
2447switches that can be on or off, this means that there are a thousand
2448separate programs, any one of which might not even be syntactically
2449correct, and even if syntactically correct, the resulting program
2450might not work correctly. Testing all combinations can quickly become
2451impossible.
2452
2453Nevertheless, the need to tailor programs certainly exists, and in
2454this section we will discuss how this can
2455be achieved using Ada in general, and GNAT in particular.
2456
2457.. _Use_of_Boolean_Constants:
2458
2459Use of Boolean Constants
2460^^^^^^^^^^^^^^^^^^^^^^^^
2461
2462In the case where the difference is simply which code
2463sequence is executed, the cleanest solution is to use Boolean
2464constants to control which code is executed.
2465
2466.. code-block:: ada
2467
2468      FP_Initialize_Required : constant Boolean := True;
2469      ...
2470      if FP_Initialize_Required then
2471      ...
2472      end if;
2473
2474Not only will the code inside the ``if`` statement not be executed if
2475the constant Boolean is ``False``, but it will also be completely
2476deleted from the program.
2477However, the code is only deleted after the ``if`` statement
2478has been checked for syntactic and semantic correctness.
2479(In contrast, with preprocessors the code is deleted before the
2480compiler ever gets to see it, so it is not checked until the switch
2481is turned on.)
2482
2483.. index:: Preprocessors (contrasted with conditional compilation)
2484
2485Typically the Boolean constants will be in a separate package,
2486something like:
2487
2488.. code-block:: ada
2489
2490       package Config is
2491          FP_Initialize_Required : constant Boolean := True;
2492          Reset_Available        : constant Boolean := False;
2493          ...
2494       end Config;
2495
2496The ``Config`` package exists in multiple forms for the various targets,
2497with an appropriate script selecting the version of ``Config`` needed.
2498Then any other unit requiring conditional compilation can do a |with|
2499of ``Config`` to make the constants visible.
2500
2501.. _Debugging_-_A_Special_Case:
2502
2503Debugging - A Special Case
2504^^^^^^^^^^^^^^^^^^^^^^^^^^
2505
2506A common use of conditional code is to execute statements (for example
2507dynamic checks, or output of intermediate results) under control of a
2508debug switch, so that the debugging behavior can be turned on and off.
2509This can be done using a Boolean constant to control whether the code
2510is active:
2511
2512.. code-block:: ada
2513
2514       if Debugging then
2515          Put_Line ("got to the first stage!");
2516       end if;
2517
2518or
2519
2520.. code-block:: ada
2521
2522       if Debugging and then Temperature > 999.0 then
2523          raise Temperature_Crazy;
2524       end if;
2525
2526.. index:: pragma Assert
2527
2528Since this is a common case, there are special features to deal with
2529this in a convenient manner. For the case of tests, Ada 2005 has added
2530a pragma ``Assert`` that can be used for such tests. This pragma is modeled
2531on the ``Assert`` pragma that has always been available in GNAT, so this
2532feature may be used with GNAT even if you are not using Ada 2005 features.
2533The use of pragma ``Assert`` is described in the
2534:title:`GNAT_Reference_Manual`, but as an
2535example, the last test could be written:
2536
2537.. code-block:: ada
2538
2539       pragma Assert (Temperature <= 999.0, "Temperature Crazy");
2540
2541or simply
2542
2543.. code-block:: ada
2544
2545       pragma Assert (Temperature <= 999.0);
2546
2547In both cases, if assertions are active and the temperature is excessive,
2548the exception ``Assert_Failure`` will be raised, with the given string in
2549the first case or a string indicating the location of the pragma in the second
2550case used as the exception message.
2551
2552.. index:: pragma Assertion_Policy
2553
2554You can turn assertions on and off by using the ``Assertion_Policy``
2555pragma.
2556
2557.. index:: -gnata switch
2558
2559This is an Ada 2005 pragma which is implemented in all modes by
2560GNAT. Alternatively, you can use the :switch:`-gnata` switch
2561to enable assertions from the command line, which applies to
2562all versions of Ada.
2563
2564.. index:: pragma Debug
2565
2566For the example above with the ``Put_Line``, the GNAT-specific pragma
2567``Debug`` can be used:
2568
2569.. code-block:: ada
2570
2571       pragma Debug (Put_Line ("got to the first stage!"));
2572
2573If debug pragmas are enabled, the argument, which must be of the form of
2574a procedure call, is executed (in this case, ``Put_Line`` will be called).
2575Only one call can be present, but of course a special debugging procedure
2576containing any code you like can be included in the program and then
2577called in a pragma ``Debug`` argument as needed.
2578
2579One advantage of pragma ``Debug`` over the ``if Debugging then``
2580construct is that pragma ``Debug`` can appear in declarative contexts,
2581such as at the very beginning of a procedure, before local declarations have
2582been elaborated.
2583
2584.. index:: pragma Debug_Policy
2585
2586Debug pragmas are enabled using either the :switch:`-gnata` switch that also
2587controls assertions, or with a separate Debug_Policy pragma.
2588
2589The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
2590in Ada 95 and Ada 83 programs as well), and is analogous to
2591pragma ``Assertion_Policy`` to control assertions.
2592
2593``Assertion_Policy`` and ``Debug_Policy`` are configuration pragmas,
2594and thus they can appear in :file:`gnat.adc` if you are not using a
2595project file, or in the file designated to contain configuration pragmas
2596in a project file.
2597They then apply to all subsequent compilations. In practice the use of
2598the :switch:`-gnata` switch is often the most convenient method of controlling
2599the status of these pragmas.
2600
2601Note that a pragma is not a statement, so in contexts where a statement
2602sequence is required, you can't just write a pragma on its own. You have
2603to add a ``null`` statement.
2604
2605.. code-block:: ada
2606
2607       if ... then
2608          ... -- some statements
2609       else
2610          pragma Assert (Num_Cases < 10);
2611          null;
2612       end if;
2613
2614.. _Conditionalizing_Declarations:
2615
2616Conditionalizing Declarations
2617^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2618
2619In some cases it may be necessary to conditionalize declarations to meet
2620different requirements. For example we might want a bit string whose length
2621is set to meet some hardware message requirement.
2622
2623This may be possible using declare blocks controlled
2624by conditional constants:
2625
2626.. code-block:: ada
2627
2628       if Small_Machine then
2629          declare
2630             X : Bit_String (1 .. 10);
2631          begin
2632             ...
2633          end;
2634       else
2635          declare
2636             X : Large_Bit_String (1 .. 1000);
2637          begin
2638             ...
2639          end;
2640       end if;
2641
2642Note that in this approach, both declarations are analyzed by the
2643compiler so this can only be used where both declarations are legal,
2644even though one of them will not be used.
2645
2646Another approach is to define integer constants, e.g., ``Bits_Per_Word``,
2647or Boolean constants, e.g., ``Little_Endian``, and then write declarations
2648that are parameterized by these constants. For example
2649
2650.. code-block:: ada
2651
2652       for Rec use
2653         Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
2654       end record;
2655
2656If ``Bits_Per_Word`` is set to 32, this generates either
2657
2658.. code-block:: ada
2659
2660       for Rec use
2661         Field1 at 0 range 0 .. 32;
2662       end record;
2663
2664for the big endian case, or
2665
2666.. code-block:: ada
2667
2668       for Rec use record
2669           Field1 at 0 range 10 .. 32;
2670       end record;
2671
2672for the little endian case. Since a powerful subset of Ada expression
2673notation is usable for creating static constants, clever use of this
2674feature can often solve quite difficult problems in conditionalizing
2675compilation (note incidentally that in Ada 95, the little endian
2676constant was introduced as ``System.Default_Bit_Order``, so you do not
2677need to define this one yourself).
2678
2679.. _Use_of_Alternative_Implementations:
2680
2681Use of Alternative Implementations
2682^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2683
2684In some cases, none of the approaches described above are adequate. This
2685can occur for example if the set of declarations required is radically
2686different for two different configurations.
2687
2688In this situation, the official Ada way of dealing with conditionalizing
2689such code is to write separate units for the different cases. As long as
2690this does not result in excessive duplication of code, this can be done
2691without creating maintenance problems. The approach is to share common
2692code as far as possible, and then isolate the code and declarations
2693that are different. Subunits are often a convenient method for breaking
2694out a piece of a unit that is to be conditionalized, with separate files
2695for different versions of the subunit for different targets, where the
2696build script selects the right one to give to the compiler.
2697
2698.. index:: Subunits (and conditional compilation)
2699
2700As an example, consider a situation where a new feature in Ada 2005
2701allows something to be done in a really nice way. But your code must be able
2702to compile with an Ada 95 compiler. Conceptually you want to say:
2703
2704.. code-block:: ada
2705
2706       if Ada_2005 then
2707          ... neat Ada 2005 code
2708       else
2709          ... not quite as neat Ada 95 code
2710       end if;
2711
2712where ``Ada_2005`` is a Boolean constant.
2713
2714But this won't work when ``Ada_2005`` is set to ``False``,
2715since the ``then`` clause will be illegal for an Ada 95 compiler.
2716(Recall that although such unreachable code would eventually be deleted
2717by the compiler, it still needs to be legal.  If it uses features
2718introduced in Ada 2005, it will be illegal in Ada 95.)
2719
2720So instead we write
2721
2722.. code-block:: ada
2723
2724       procedure Insert is separate;
2725
2726Then we have two files for the subunit ``Insert``, with the two sets of
2727code.
2728If the package containing this is called ``File_Queries``, then we might
2729have two files
2730
2731* :file:`file_queries-insert-2005.adb`
2732* :file:`file_queries-insert-95.adb`
2733
2734and the build script renames the appropriate file to :file:`file_queries-insert.adb` and then carries out the compilation.
2735
2736This can also be done with project files' naming schemes. For example:
2737
2738.. code-block:: gpr
2739
2740       for body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
2741
2742Note also that with project files it is desirable to use a different extension
2743than :file:`ads` / :file:`adb` for alternative versions. Otherwise a naming
2744conflict may arise through another commonly used feature: to declare as part
2745of the project a set of directories containing all the sources obeying the
2746default naming scheme.
2747
2748The use of alternative units is certainly feasible in all situations,
2749and for example the Ada part of the GNAT run-time is conditionalized
2750based on the target architecture using this approach. As a specific example,
2751consider the implementation of the AST feature in VMS. There is one
2752spec: :file:`s-asthan.ads` which is the same for all architectures, and three
2753bodies:
2754
2755* :file:`s-asthan.adb`
2756    used for all non-VMS operating systems
2757
2758* :file:`s-asthan-vms-alpha.adb`
2759    used for VMS on the Alpha
2760
2761* :file:`s-asthan-vms-ia64.adb`
2762    used for VMS on the ia64
2763
2764The dummy version :file:`s-asthan.adb` simply raises exceptions noting that
2765this operating system feature is not available, and the two remaining
2766versions interface with the corresponding versions of VMS to provide
2767VMS-compatible AST handling. The GNAT build script knows the architecture
2768and operating system, and automatically selects the right version,
2769renaming it if necessary to :file:`s-asthan.adb` before the run-time build.
2770
2771Another style for arranging alternative implementations is through Ada's
2772access-to-subprogram facility.
2773In case some functionality is to be conditionally included,
2774you can declare an access-to-procedure variable ``Ref`` that is initialized
2775to designate a 'do nothing' procedure, and then invoke ``Ref.all``
2776when appropriate.
2777In some library package, set ``Ref`` to ``Proc'Access`` for some
2778procedure ``Proc`` that performs the relevant processing.
2779The initialization only occurs if the library package is included in the
2780program.
2781The same idea can also be implemented using tagged types and dispatching
2782calls.
2783
2784.. _Preprocessing:
2785
2786Preprocessing
2787^^^^^^^^^^^^^
2788
2789.. index:: Preprocessing
2790
2791Although it is quite possible to conditionalize code without the use of
2792C-style preprocessing, as described earlier in this section, it is
2793nevertheless convenient in some cases to use the C approach. Moreover,
2794older Ada compilers have often provided some preprocessing capability,
2795so legacy code may depend on this approach, even though it is not
2796standard.
2797
2798To accommodate such use, GNAT provides a preprocessor (modeled to a large
2799extent on the various preprocessors that have been used
2800with legacy code on other compilers, to enable easier transition).
2801
2802.. index:: gnatprep
2803
2804The preprocessor may be used in two separate modes. It can be used quite
2805separately from the compiler, to generate a separate output source file
2806that is then fed to the compiler as a separate step. This is the
2807``gnatprep`` utility, whose use is fully described in
2808:ref:`Preprocessing_with_gnatprep`.
2809
2810The preprocessing language allows such constructs as
2811
2812.. code-block:: c
2813
2814       #if DEBUG or else (PRIORITY > 4) then
2815          sequence of declarations
2816       #else
2817          completely different sequence of declarations
2818       #end if;
2819
2820The values of the symbols ``DEBUG`` and ``PRIORITY`` can be
2821defined either on the command line or in a separate file.
2822
2823The other way of running the preprocessor is even closer to the C style and
2824often more convenient. In this approach the preprocessing is integrated into
2825the compilation process. The compiler is given the preprocessor input which
2826includes ``#if`` lines etc, and then the compiler carries out the
2827preprocessing internally and processes the resulting output.
2828For more details on this approach, see :ref:`Integrated_Preprocessing`.
2829
2830.. _Preprocessing_with_gnatprep:
2831
2832Preprocessing with ``gnatprep``
2833-------------------------------
2834
2835.. index:: ! gnatprep
2836.. index:: Preprocessing (gnatprep)
2837
2838This section discusses how to use GNAT's ``gnatprep`` utility for simple
2839preprocessing.
2840Although designed for use with GNAT, ``gnatprep`` does not depend on any
2841special GNAT features.
2842For further discussion of conditional compilation in general, see
2843:ref:`Conditional_Compilation`.
2844
2845.. _Preprocessing_Symbols:
2846
2847Preprocessing Symbols
2848^^^^^^^^^^^^^^^^^^^^^
2849
2850Preprocessing symbols are defined in *definition files* and referenced in the
2851sources to be preprocessed. A preprocessing symbol is an identifier, following
2852normal Ada (case-insensitive) rules for its syntax, with the restriction that
2853all characters need to be in the ASCII set (no accented letters).
2854
2855.. _Using_gnatprep:
2856
2857Using ``gnatprep``
2858^^^^^^^^^^^^^^^^^^
2859
2860To call ``gnatprep`` use:
2861
2862.. code-block:: sh
2863
2864    $ gnatprep [ switches ] infile outfile [ deffile ]
2865
2866where
2867
2868* *switches*
2869    is an optional sequence of switches as described in the next section.
2870
2871* *infile*
2872    is the full name of the input file, which is an Ada source
2873    file containing preprocessor directives.
2874
2875* *outfile*
2876    is the full name of the output file, which is an Ada source
2877    in standard Ada form. When used with GNAT, this file name will
2878    normally have an ``ads`` or ``adb`` suffix.
2879
2880* ``deffile``
2881    is the full name of a text file containing definitions of
2882    preprocessing symbols to be referenced by the preprocessor. This argument is
2883    optional, and can be replaced by the use of the :switch:`-D` switch.
2884
2885
2886.. _Switches_for_gnatprep:
2887
2888Switches for ``gnatprep``
2889^^^^^^^^^^^^^^^^^^^^^^^^^
2890
2891.. index:: --version (gnatprep)
2892
2893:switch:`--version`
2894  Display Copyright and version, then exit disregarding all other options.
2895
2896.. index:: --help (gnatprep)
2897
2898:switch:`--help`
2899  If :switch:`--version` was not used, display usage and then exit disregarding
2900  all other options.
2901
2902.. index:: -b (gnatprep)
2903
2904:switch:`-b`
2905  Causes both preprocessor lines and the lines deleted by
2906  preprocessing to be replaced by blank lines in the output source file,
2907  preserving line numbers in the output file.
2908
2909.. index:: -c (gnatprep)
2910
2911:switch:`-c`
2912  Causes both preprocessor lines and the lines deleted
2913  by preprocessing to be retained in the output source as comments marked
2914  with the special string ``"--! "``. This option will result in line numbers
2915  being preserved in the output file.
2916
2917.. index:: -C (gnatprep)
2918
2919:switch:`-C`
2920  Causes comments to be scanned. Normally comments are ignored by gnatprep.
2921  If this option is specified, then comments are scanned and any $symbol
2922  substitutions performed as in program text. This is particularly useful
2923  when structured comments are used (e.g., for programs written in a
2924  pre-2014 version of the SPARK Ada subset). Note that this switch is not
2925  available when  doing integrated preprocessing (it would be useless in
2926  this context since comments are ignored by the compiler in any case).
2927
2928.. index:: -D (gnatprep)
2929
2930:switch:`-D{symbol}[={value}]`
2931  Defines a new preprocessing symbol with the specified value. If no value is given
2932  on the command line, then symbol is considered to be ``True``. This switch
2933  can be used in place of a definition file.
2934
2935.. index:: -r (gnatprep)
2936
2937:switch:`-r`
2938  Causes a ``Source_Reference`` pragma to be generated that
2939  references the original input file, so that error messages will use
2940  the file name of this original file. The use of this switch implies
2941  that preprocessor lines are not to be removed from the file, so its
2942  use will force ``-b`` mode if ``-c``
2943  has not been specified explicitly.
2944
2945  Note that if the file to be preprocessed contains multiple units, then
2946  it will be necessary to ``gnatchop`` the output file from
2947  ``gnatprep``. If a ``Source_Reference`` pragma is present
2948  in the preprocessed file, it will be respected by
2949  ``gnatchop -r``
2950  so that the final chopped files will correctly refer to the original
2951  input source file for ``gnatprep``.
2952
2953.. index:: -s (gnatprep)
2954
2955:switch:`-s`
2956  Causes a sorted list of symbol names and values to be
2957  listed on the standard output file.
2958
2959.. index:: -T (gnatprep)
2960
2961:switch:`-T`
2962  Use LF as line terminators when writing files. By default the line terminator
2963  of the host (LF under unix, CR/LF under Windows) is used.
2964
2965.. index:: -u (gnatprep)
2966
2967:switch:`-u`
2968  Causes undefined symbols to be treated as having the value FALSE in the context
2969  of a preprocessor test. In the absence of this option, an undefined symbol in
2970  a ``#if`` or ``#elsif`` test will be treated as an error.
2971
2972.. index:: -v (gnatprep)
2973
2974:switch:`-v`
2975  Verbose mode: generates more output about work done.
2976
2977
2978Note: if neither :switch:`-b` nor :switch:`-c` is present,
2979then preprocessor lines and
2980deleted lines are completely removed from the output, unless -r is
2981specified, in which case -b is assumed.
2982
2983
2984.. _Form_of_Definitions_File:
2985
2986Form of Definitions File
2987^^^^^^^^^^^^^^^^^^^^^^^^
2988
2989The definitions file contains lines of the form::
2990
2991      symbol := value
2992
2993where ``symbol`` is a preprocessing symbol, and ``value`` is one of the following:
2994
2995*  Empty, corresponding to a null substitution,
2996*  A string literal using normal Ada syntax, or
2997*  Any sequence of characters from the set {letters, digits, period, underline}.
2998
2999Comment lines may also appear in the definitions file, starting with
3000the usual ``--``,
3001and comments may be added to the definitions lines.
3002
3003
3004.. _Form_of_Input_Text_for_gnatprep:
3005
3006Form of Input Text for ``gnatprep``
3007^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3008
3009The input text may contain preprocessor conditional inclusion lines,
3010as well as general symbol substitution sequences.
3011
3012The preprocessor conditional inclusion commands have the form:
3013
3014.. code-block:: c
3015
3016       #if <expression> [then]
3017          lines
3018       #elsif <expression> [then]
3019          lines
3020       #elsif <expression> [then]
3021          lines
3022       ...
3023       #else
3024          lines
3025       #end if;
3026
3027In this example, <expression> is defined by the following grammar::
3028
3029       <expression> ::=  <symbol>
3030       <expression> ::=  <symbol> = "<value>"
3031       <expression> ::=  <symbol> = <symbol>
3032       <expression> ::=  <symbol> = <integer>
3033       <expression> ::=  <symbol> > <integer>
3034       <expression> ::=  <symbol> >= <integer>
3035       <expression> ::=  <symbol> < <integer>
3036       <expression> ::=  <symbol> <= <integer>
3037       <expression> ::=  <symbol> 'Defined
3038       <expression> ::=  not <expression>
3039       <expression> ::=  <expression> and <expression>
3040       <expression> ::=  <expression> or <expression>
3041       <expression> ::=  <expression> and then <expression>
3042       <expression> ::=  <expression> or else <expression>
3043       <expression> ::=  ( <expression> )
3044
3045Note the following restriction: it is not allowed to have "and" or "or"
3046following "not" in the same expression without parentheses. For example, this
3047is not allowed:
3048
3049.. code-block:: ada
3050
3051       not X or Y
3052
3053This can be expressed instead as one of the following forms:
3054
3055.. code-block:: ada
3056
3057     (not X) or Y
3058     not (X or Y)
3059
3060For the first test (<expression> ::= <symbol>) the symbol must have
3061either the value true or false, that is to say the right-hand of the
3062symbol definition must be one of the (case-insensitive) literals
3063``True`` or ``False``. If the value is true, then the
3064corresponding lines are included, and if the value is false, they are
3065excluded.
3066
3067When comparing a symbol to an integer, the integer is any non negative
3068literal integer as defined in the Ada Reference Manual, such as 3, 16#FF# or
30692#11#. The symbol value must also be a non negative integer. Integer values
3070in the range 0 .. 2**31-1 are supported.
3071
3072The test (<expression> ::= <symbol>'Defined) is true only if
3073the symbol has been defined in the definition file or by a :switch:`-D`
3074switch on the command line. Otherwise, the test is false.
3075
3076The equality tests are case insensitive, as are all the preprocessor lines.
3077
3078If the symbol referenced is not defined in the symbol definitions file,
3079then the effect depends on whether or not switch :switch:`-u`
3080is specified. If so, then the symbol is treated as if it had the value
3081false and the test fails. If this switch is not specified, then
3082it is an error to reference an undefined symbol. It is also an error to
3083reference a symbol that is defined with a value other than ``True``
3084or ``False``.
3085
3086The use of the ``not`` operator inverts the sense of this logical test.
3087The ``not`` operator cannot be combined with the ``or`` or ``and``
3088operators, without parentheses. For example, "if not X or Y then" is not
3089allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
3090
3091The ``then`` keyword is optional as shown
3092
3093The ``#`` must be the first non-blank character on a line, but
3094otherwise the format is free form. Spaces or tabs may appear between
3095the ``#`` and the keyword. The keywords and the symbols are case
3096insensitive as in normal Ada code. Comments may be used on a
3097preprocessor line, but other than that, no other tokens may appear on a
3098preprocessor line. Any number of ``elsif`` clauses can be present,
3099including none at all. The ``else`` is optional, as in Ada.
3100
3101The ``#`` marking the start of a preprocessor line must be the first
3102non-blank character on the line, i.e., it must be preceded only by
3103spaces or horizontal tabs.
3104
3105Symbol substitution outside of preprocessor lines is obtained by using
3106the sequence::
3107
3108      $symbol
3109
3110anywhere within a source line, except in a comment or within a
3111string literal. The identifier
3112following the ``$`` must match one of the symbols defined in the symbol
3113definition file, and the result is to substitute the value of the
3114symbol in place of ``$symbol`` in the output file.
3115
3116Note that although the substitution of strings within a string literal
3117is not possible, it is possible to have a symbol whose defined value is
3118a string literal. So instead of setting XYZ to ``hello`` and writing:
3119
3120.. code-block:: ada
3121
3122     Header : String := "$XYZ";
3123
3124you should set XYZ to ``"hello"`` and write:
3125
3126.. code-block:: ada
3127
3128     Header : String := $XYZ;
3129
3130and then the substitution will occur as desired.
3131
3132
3133.. _Integrated_Preprocessing:
3134
3135Integrated Preprocessing
3136------------------------
3137
3138As noted above, a file to be preprocessed consists of Ada source code
3139in which preprocessing lines have been inserted. However,
3140instead of using ``gnatprep`` to explicitly preprocess a file as a separate
3141step before compilation, you can carry out the preprocessing implicitly
3142as part of compilation. Such *integrated preprocessing*, which is the common
3143style with C, is performed when either or both of the following switches
3144are passed to the compiler:
3145
3146   *   :switch:`-gnatep`, which specifies the *preprocessor data file*.
3147       This file dictates how the source files will be preprocessed (e.g., which
3148       symbol definition files apply to which sources).
3149
3150   *   :switch:`-gnateD`, which defines values for preprocessing symbols.
3151
3152Integrated preprocessing applies only to Ada source files, it is
3153not available for configuration pragma files.
3154
3155With integrated preprocessing, the output from the preprocessor is not,
3156by default, written to any external file. Instead it is passed
3157internally to the compiler. To preserve the result of
3158preprocessing in a file, either run ``gnatprep``
3159in standalone mode or else supply the :switch:`-gnateG` switch
3160(described below) to the compiler.
3161
3162When using project files:
3163
3164   *    the builder switch :switch:`-x` should be used if any Ada source is
3165        compiled with :switch:`gnatep=`, so that the compiler finds the
3166        *preprocessor data file*.
3167
3168   *    the preprocessing data file and the symbol definition files should be
3169        located in the source directories of the project.
3170
3171Note that the ``gnatmake`` switch :switch:`-m` will almost
3172always trigger recompilation for sources that are preprocessed,
3173because ``gnatmake`` cannot compute the checksum of the source after
3174preprocessing.
3175
3176The actual preprocessing function is described in detail in
3177:ref:`Preprocessing_with_gnatprep`. This section explains the switches
3178that relate to integrated preprocessing.
3179
3180.. index:: -gnatep (gcc)
3181
3182:switch:`-gnatep={preprocessor_data_file}`
3183  This switch specifies the file name (without directory
3184  information) of the preprocessor data file. Either place this file
3185  in one of the source directories, or, when using project
3186  files, reference the project file's directory via the
3187  ``project_name'Project_Dir`` project attribute; e.g:
3188
3189     .. code-block:: gpr
3190
3191         project Prj is
3192            package Compiler is
3193               for Switches ("Ada") use
3194                 ("-gnatep=" & Prj'Project_Dir & "prep.def");
3195            end Compiler;
3196         end Prj;
3197
3198  A preprocessor data file is a text file that contains *preprocessor
3199  control lines*.  A preprocessor control line directs the preprocessing of
3200  either a particular source file, or, analogous to ``others`` in Ada,
3201  all sources not specified elsewhere in  the preprocessor data file.
3202  A preprocessor control line
3203  can optionally identify a *definition file* that assigns values to
3204  preprocessor symbols, as well as a list of switches that relate to
3205  preprocessing.
3206  Empty lines and comments (using Ada syntax) are also permitted, with no
3207  semantic effect.
3208
3209  Here's an example of a preprocessor data file:
3210
3211    .. code-block:: ada
3212
3213        "toto.adb"  "prep.def" -u
3214        --  Preprocess toto.adb, using definition file prep.def
3215        --  Undefined symbols are treated as False
3216
3217        * -c -DVERSION=V101
3218        --  Preprocess all other sources without using a definition file
3219        --  Suppressed lined are commented
3220        --  Symbol VERSION has the value V101
3221
3222        "tata.adb" "prep2.def" -s
3223        --  Preprocess tata.adb, using definition file prep2.def
3224        --  List all symbols with their values
3225
3226  A preprocessor control line has the following syntax:
3227
3228    ::
3229
3230        <preprocessor_control_line> ::=
3231           <preprocessor_input> [ <definition_file_name> ] { <switch> }
3232
3233        <preprocessor_input> ::= <source_file_name> | '*'
3234
3235        <definition_file_name> ::= <string_literal>
3236
3237        <source_file_name> := <string_literal>
3238
3239        <switch> := (See below for list)
3240
3241  Thus  each preprocessor control line starts with either a literal string or
3242  the character '*':
3243
3244  *  A literal string is the file name (without directory information) of the source
3245     file that will be input to the preprocessor.
3246
3247  *  The character '*' is a wild-card indicator; the additional parameters on the line
3248     indicate the preprocessing for all the sources
3249     that are not specified explicitly on other lines (the order of the lines is not
3250     significant).
3251
3252  It is an error to have two lines with the same file name or two
3253  lines starting with the character '*'.
3254
3255  After the file name or '*', an optional literal string specifies the name of
3256  the definition file to be used for preprocessing
3257  (:ref:`Form_of_Definitions_File`). The definition files are found by the
3258  compiler in one of the source directories. In some cases, when compiling
3259  a source in a directory other than the current directory, if the definition
3260  file is in the current directory, it may be necessary to add the current
3261  directory as a source directory through the :switch:`-I` switch; otherwise
3262  the compiler would not find the definition file.
3263
3264  Finally, switches similar to those of ``gnatprep`` may optionally appear:
3265
3266  :switch:`-b`
3267    Causes both preprocessor lines and the lines deleted by
3268    preprocessing to be replaced by blank lines, preserving the line number.
3269    This switch is always implied; however, if specified after :switch:`-c`
3270    it cancels the effect of :switch:`-c`.
3271
3272
3273  :switch:`-c`
3274    Causes both preprocessor lines and the lines deleted
3275    by preprocessing to be retained as comments marked
3276    with the special string '`--!`'.
3277
3278
3279  :switch:`-D{symbol}={new_value}`
3280    Define or redefine ``symbol`` to have ``new_value`` as its value.
3281    The permitted form for ``symbol`` is either an Ada identifier, or any Ada reserved word
3282    aside from ``if``,
3283    ``else``, ``elsif``, ``end``, ``and``, ``or`` and ``then``.
3284    The permitted form for ``new_value`` is a literal string, an Ada identifier or any Ada reserved
3285    word. A symbol declared with this switch replaces a symbol with the
3286    same name defined in a definition file.
3287
3288
3289  :switch:`-s`
3290    Causes a sorted list of symbol names and values to be
3291    listed on the standard output file.
3292
3293
3294  :switch:`-u`
3295    Causes undefined symbols to be treated as having the value ``FALSE``
3296    in the context
3297    of a preprocessor test. In the absence of this option, an undefined symbol in
3298    a ``#if`` or ``#elsif`` test will be treated as an error.
3299
3300
3301.. index:: -gnateD (gcc)
3302
3303:switch:`-gnateD{symbol}[={new_value}]`
3304  Define or redefine ``symbol`` to have ``new_value`` as its value. If no value
3305  is supplied, then the value of ``symbol`` is ``True``.
3306  The form of ``symbol`` is an identifier, following normal Ada (case-insensitive)
3307  rules for its syntax, and ``new_value`` is either an arbitrary string between double
3308  quotes or any sequence (including an empty sequence) of characters from the
3309  set (letters, digits, period, underline).
3310  Ada reserved words may be used as symbols, with the exceptions of ``if``,
3311  ``else``, ``elsif``, ``end``, ``and``, ``or`` and ``then``.
3312
3313  Examples:
3314
3315    ::
3316
3317        -gnateDToto=Tata
3318        -gnateDFoo
3319        -gnateDFoo=\"Foo-Bar\"
3320
3321  A symbol declared with this switch on the command line replaces a
3322  symbol with the same name either in a definition file or specified with a
3323  switch :switch:`-D` in the preprocessor data file.
3324
3325  This switch is similar to switch :switch:`-D` of ``gnatprep``.
3326
3327
3328:switch:`-gnateG`
3329  When integrated preprocessing is performed on source file :file:`filename.extension`,
3330  create or overwrite :file:`filename.extension.prep` to contain
3331  the result of the preprocessing.
3332  For example if the source file is :file:`foo.adb` then
3333  the output file will be :file:`foo.adb.prep`.
3334
3335
3336.. _Mixed_Language_Programming:
3337
3338Mixed Language Programming
3339==========================
3340
3341.. index:: Mixed Language Programming
3342
3343This section describes how to develop a mixed-language program,
3344with a focus on combining Ada with C or C++.
3345
3346.. _Interfacing_to_C:
3347
3348Interfacing to C
3349----------------
3350
3351Interfacing Ada with a foreign language such as C involves using
3352compiler directives to import and/or export entity definitions in each
3353language -- using ``extern`` statements in C, for instance, and the
3354``Import``, ``Export``, and ``Convention`` pragmas in Ada.
3355A full treatment of these topics is provided in Appendix B, section 1
3356of the Ada Reference Manual.
3357
3358There are two ways to build a program using GNAT that contains some Ada
3359sources and some foreign language sources, depending on whether or not
3360the main subprogram is written in Ada.  Here is a source example with
3361the main subprogram in Ada:
3362
3363.. code-block:: c
3364
3365    /* file1.c */
3366    #include <stdio.h>
3367
3368    void print_num (int num)
3369    {
3370      printf ("num is %d.\\n", num);
3371      return;
3372    }
3373
3374.. code-block:: c
3375
3376    /* file2.c */
3377
3378    /* num_from_Ada is declared in my_main.adb */
3379    extern int num_from_Ada;
3380
3381    int get_num (void)
3382    {
3383      return num_from_Ada;
3384    }
3385
3386.. code-block:: ada
3387
3388    --  my_main.adb
3389    procedure My_Main is
3390
3391       --  Declare then export an Integer entity called num_from_Ada
3392       My_Num : Integer := 10;
3393       pragma Export (C, My_Num, "num_from_Ada");
3394
3395       --  Declare an Ada function spec for Get_Num, then use
3396       --  C function get_num for the implementation.
3397       function Get_Num return Integer;
3398       pragma Import (C, Get_Num, "get_num");
3399
3400       --  Declare an Ada procedure spec for Print_Num, then use
3401       --  C function print_num for the implementation.
3402       procedure Print_Num (Num : Integer);
3403       pragma Import (C, Print_Num, "print_num");
3404
3405    begin
3406       Print_Num (Get_Num);
3407    end My_Main;
3408
3409To build this example:
3410
3411* First compile the foreign language files to
3412  generate object files:
3413
3414  .. code-block:: sh
3415
3416      $ gcc -c file1.c
3417      $ gcc -c file2.c
3418
3419* Then, compile the Ada units to produce a set of object files and ALI
3420  files:
3421
3422  .. code-block:: sh
3423
3424      $ gnatmake -c my_main.adb
3425
3426* Run the Ada binder on the Ada main program:
3427
3428  .. code-block:: sh
3429
3430      $ gnatbind my_main.ali
3431
3432* Link the Ada main program, the Ada objects and the other language
3433  objects:
3434
3435  .. code-block:: sh
3436
3437      $ gnatlink my_main.ali file1.o file2.o
3438
3439The last three steps can be grouped in a single command:
3440
3441.. code-block:: sh
3442
3443   $ gnatmake my_main.adb -largs file1.o file2.o
3444
3445
3446.. index:: Binder output file
3447
3448If the main program is in a language other than Ada, then you may have
3449more than one entry point into the Ada subsystem. You must use a special
3450binder option to generate callable routines that initialize and
3451finalize the Ada units (:ref:`Binding_with_Non-Ada_Main_Programs`).
3452Calls to the initialization and finalization routines must be inserted
3453in the main program, or some other appropriate point in the code. The
3454call to initialize the Ada units must occur before the first Ada
3455subprogram is called, and the call to finalize the Ada units must occur
3456after the last Ada subprogram returns. The binder will place the
3457initialization and finalization subprograms into the
3458:file:`b~xxx.adb` file where they can be accessed by your C
3459sources.  To illustrate, we have the following example:
3460
3461.. code-block:: c
3462
3463     /* main.c */
3464     extern void adainit (void);
3465     extern void adafinal (void);
3466     extern int add (int, int);
3467     extern int sub (int, int);
3468
3469     int main (int argc, char *argv[])
3470     {
3471        int a = 21, b = 7;
3472
3473        adainit();
3474
3475        /* Should print "21 + 7 = 28" */
3476        printf ("%d + %d = %d\\n", a, b, add (a, b));
3477
3478        /* Should print "21 - 7 = 14" */
3479        printf ("%d - %d = %d\\n", a, b, sub (a, b));
3480
3481        adafinal();
3482     }
3483
3484.. code-block:: ada
3485
3486     --  unit1.ads
3487     package Unit1 is
3488        function Add (A, B : Integer) return Integer;
3489        pragma Export (C, Add, "add");
3490     end Unit1;
3491
3492.. code-block:: ada
3493
3494     --  unit1.adb
3495     package body Unit1 is
3496        function Add (A, B : Integer) return Integer is
3497        begin
3498           return A + B;
3499        end Add;
3500     end Unit1;
3501
3502.. code-block:: ada
3503
3504     --  unit2.ads
3505     package Unit2 is
3506        function Sub (A, B : Integer) return Integer;
3507        pragma Export (C, Sub, "sub");
3508     end Unit2;
3509
3510.. code-block:: ada
3511
3512     --  unit2.adb
3513     package body Unit2 is
3514        function Sub (A, B : Integer) return Integer is
3515        begin
3516           return A - B;
3517        end Sub;
3518     end Unit2;
3519
3520The build procedure for this application is similar to the last
3521example's:
3522
3523* First, compile the foreign language files to generate object files:
3524
3525  .. code-block:: sh
3526
3527      $ gcc -c main.c
3528
3529
3530* Next, compile the Ada units to produce a set of object files and ALI
3531  files:
3532
3533  .. code-block:: sh
3534
3535      $ gnatmake -c unit1.adb
3536      $ gnatmake -c unit2.adb
3537
3538* Run the Ada binder on every generated ALI file.  Make sure to use the
3539  :switch:`-n` option to specify a foreign main program:
3540
3541  .. code-block:: sh
3542
3543      $ gnatbind -n unit1.ali unit2.ali
3544
3545* Link the Ada main program, the Ada objects and the foreign language
3546  objects. You need only list the last ALI file here:
3547
3548  .. code-block:: sh
3549
3550      $ gnatlink unit2.ali main.o -o exec_file
3551
3552  This procedure yields a binary executable called :file:`exec_file`.
3553
3554Depending on the circumstances (for example when your non-Ada main object
3555does not provide symbol ``main``), you may also need to instruct the
3556GNAT linker not to include the standard startup objects by passing the
3557:switch:`-nostartfiles` switch to ``gnatlink``.
3558
3559.. _Calling_Conventions:
3560
3561Calling Conventions
3562-------------------
3563
3564.. index:: Foreign Languages
3565
3566.. index:: Calling Conventions
3567
3568GNAT follows standard calling sequence conventions and will thus interface
3569to any other language that also follows these conventions. The following
3570Convention identifiers are recognized by GNAT:
3571
3572
3573.. index:: Interfacing to Ada
3574
3575.. index:: Other Ada compilers
3576
3577.. index:: Convention Ada
3578
3579``Ada``
3580  This indicates that the standard Ada calling sequence will be
3581  used and all Ada data items may be passed without any limitations in the
3582  case where GNAT is used to generate both the caller and callee. It is also
3583  possible to mix GNAT generated code and code generated by another Ada
3584  compiler. In this case, the data types should be restricted to simple
3585  cases, including primitive types. Whether complex data types can be passed
3586  depends on the situation. Probably it is safe to pass simple arrays, such
3587  as arrays of integers or floats. Records may or may not work, depending
3588  on whether both compilers lay them out identically. Complex structures
3589  involving variant records, access parameters, tasks, or protected types,
3590  are unlikely to be able to be passed.
3591
3592  Note that in the case of GNAT running
3593  on a platform that supports HP Ada 83, a higher degree of compatibility
3594  can be guaranteed, and in particular records are laid out in an identical
3595  manner in the two compilers. Note also that if output from two different
3596  compilers is mixed, the program is responsible for dealing with elaboration
3597  issues. Probably the safest approach is to write the main program in the
3598  version of Ada other than GNAT, so that it takes care of its own elaboration
3599  requirements, and then call the GNAT-generated adainit procedure to ensure
3600  elaboration of the GNAT components. Consult the documentation of the other
3601  Ada compiler for further details on elaboration.
3602
3603  However, it is not possible to mix the tasking run time of GNAT and
3604  HP Ada 83, All the tasking operations must either be entirely within
3605  GNAT compiled sections of the program, or entirely within HP Ada 83
3606  compiled sections of the program.
3607
3608.. index:: Interfacing to Assembly
3609
3610.. index:: Convention Assembler
3611
3612
3613``Assembler``
3614  Specifies assembler as the convention. In practice this has the
3615  same effect as convention Ada (but is not equivalent in the sense of being
3616  considered the same convention).
3617
3618.. index:: Convention Asm
3619
3620.. index:: Asm
3621
3622``Asm``
3623  Equivalent to Assembler.
3624
3625  .. index:: Interfacing to COBOL
3626
3627  .. index:: Convention COBOL
3628
3629.. index:: COBOL
3630
3631``COBOL``
3632  Data will be passed according to the conventions described
3633  in section B.4 of the Ada Reference Manual.
3634
3635.. index:: C
3636.. index:: Interfacing to C
3637
3638.. index:: Convention C
3639
3640
3641``C``
3642  Data will be passed according to the conventions described
3643  in section B.3 of the Ada Reference Manual.
3644
3645  A note on interfacing to a C 'varargs' function:
3646
3647    .. index:: C varargs function
3648    .. index:: Interfacing to C varargs function
3649    .. index:: varargs function interfaces
3650
3651    In C, ``varargs`` allows a function to take a variable number of
3652    arguments. There is no direct equivalent in this to Ada. One
3653    approach that can be used is to create a C wrapper for each
3654    different profile and then interface to this C wrapper. For
3655    example, to print an ``int`` value using ``printf``,
3656    create a C function ``printfi`` that takes two arguments, a
3657    pointer to a string and an int, and calls ``printf``.
3658    Then in the Ada program, use pragma ``Import`` to
3659    interface to ``printfi``.
3660
3661    It may work on some platforms to directly interface to
3662    a ``varargs`` function by providing a specific Ada profile
3663    for a particular call. However, this does not work on
3664    all platforms, since there is no guarantee that the
3665    calling sequence for a two argument normal C function
3666    is the same as for calling a ``varargs`` C function with
3667    the same two arguments.
3668
3669.. index:: Convention Default
3670
3671.. index:: Default
3672
3673``Default``
3674  Equivalent to C.
3675
3676.. index:: Convention External
3677
3678.. index:: External
3679
3680``External``
3681  Equivalent to C.
3682
3683.. index:: C++
3684.. index:: Interfacing to C++
3685
3686.. index:: Convention C++
3687
3688
3689``C_Plus_Plus`` (or ``CPP``)
3690  This stands for C++. For most purposes this is identical to C.
3691  See the separate description of the specialized GNAT pragmas relating to
3692  C++ interfacing for further details.
3693
3694.. index:: Fortran
3695.. index:: Interfacing to Fortran
3696.. index:: Convention Fortran
3697
3698
3699``Fortran``
3700  Data will be passed according to the conventions described
3701  in section B.5 of the Ada Reference Manual.
3702
3703
3704``Intrinsic``
3705  This applies to an intrinsic operation, as defined in the Ada
3706  Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
3707  this means that the body of the subprogram is provided by the compiler itself,
3708  usually by means of an efficient code sequence, and that the user does not
3709  supply an explicit body for it. In an application program, the pragma may
3710  be applied to the following sets of names:
3711
3712
3713  * Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_Arithmetic.
3714    The corresponding subprogram declaration must have
3715    two formal parameters. The
3716    first one must be a signed integer type or a modular type with a binary
3717    modulus, and the second parameter must be of type Natural.
3718    The return type must be the same as the type of the first argument. The size
3719    of this type can only be 8, 16, 32, or 64.
3720
3721
3722  * Binary arithmetic operators: '+', '-', '*', '/'.
3723    The corresponding operator declaration must have parameters and result type
3724    that have the same root numeric type (for example, all three are long_float
3725    types). This simplifies the definition of operations that use type checking
3726    to perform dimensional checks:
3727
3728
3729  .. code-block:: ada
3730
3731      type Distance is new Long_Float;
3732      type Time     is new Long_Float;
3733      type Velocity is new Long_Float;
3734      function "/" (D : Distance; T : Time)
3735        return Velocity;
3736      pragma Import (Intrinsic, "/");
3737
3738    This common idiom is often programmed with a generic definition and an
3739    explicit body. The pragma makes it simpler to introduce such declarations.
3740    It incurs no overhead in compilation time or code size, because it is
3741    implemented as a single machine instruction.
3742
3743
3744  * General subprogram entities. This is used  to bind an Ada subprogram
3745    declaration to
3746    a compiler builtin by name with back-ends where such interfaces are
3747    available. A typical example is the set of ``__builtin`` functions
3748    exposed by the GCC back-end, as in the following example:
3749
3750
3751    .. code-block:: ada
3752
3753         function builtin_sqrt (F : Float) return Float;
3754         pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
3755
3756    Most of the GCC builtins are accessible this way, and as for other
3757    import conventions (e.g. C), it is the user's responsibility to ensure
3758    that the Ada subprogram profile matches the underlying builtin
3759    expectations.
3760
3761.. index:: Stdcall
3762.. index:: Convention Stdcall
3763
3764``Stdcall``
3765  This is relevant only to Windows implementations of GNAT,
3766  and specifies that the ``Stdcall`` calling sequence will be used,
3767  as defined by the NT API. Nevertheless, to ease building
3768  cross-platform bindings this convention will be handled as a ``C`` calling
3769  convention on non-Windows platforms.
3770
3771.. index:: DLL
3772.. index:: Convention DLL
3773
3774
3775``DLL``
3776  This is equivalent to ``Stdcall``.
3777
3778.. index:: Win32
3779.. index:: Convention Win32
3780
3781
3782``Win32``
3783  This is equivalent to ``Stdcall``.
3784
3785.. index:: Stubbed
3786.. index:: Convention Stubbed
3787
3788
3789``Stubbed``
3790  This is a special convention that indicates that the compiler
3791  should provide a stub body that raises ``Program_Error``.
3792
3793GNAT additionally provides a useful pragma ``Convention_Identifier``
3794that can be used to parameterize conventions and allow additional synonyms
3795to be specified. For example if you have legacy code in which the convention
3796identifier Fortran77 was used for Fortran, you can use the configuration
3797pragma:
3798
3799.. code-block:: ada
3800
3801     pragma Convention_Identifier (Fortran77, Fortran);
3802
3803And from now on the identifier Fortran77 may be used as a convention
3804identifier (for example in an ``Import`` pragma) with the same
3805meaning as Fortran.
3806
3807
3808.. _Building_Mixed_Ada_and_C++_Programs:
3809
3810Building Mixed Ada and C++ Programs
3811-----------------------------------
3812
3813A programmer inexperienced with mixed-language development may find that
3814building an application containing both Ada and C++ code can be a
3815challenge.  This section gives a few hints that should make this task easier.
3816
3817.. _Interfacing_to_C++:
3818
3819Interfacing to C++
3820^^^^^^^^^^^^^^^^^^
3821
3822GNAT supports interfacing with the G++ compiler (or any C++ compiler
3823generating code that is compatible with the G++ Application Binary
3824Interface ---see http://www.codesourcery.com/archives/cxx-abi).
3825
3826Interfacing can be done at 3 levels: simple data, subprograms, and
3827classes. In the first two cases, GNAT offers a specific ``Convention C_Plus_Plus``
3828(or ``CPP``) that behaves exactly like ``Convention C``.
3829Usually, C++ mangles the names of subprograms. To generate proper mangled
3830names automatically, see :ref:`Generating_Ada_Bindings_for_C_and_C++_headers`).
3831This problem can also be addressed manually in two ways:
3832
3833* by modifying the C++ code in order to force a C convention using
3834  the ``extern "C"`` syntax.
3835
3836* by figuring out the mangled name (using e.g. ``nm``) and using it as the
3837  Link_Name argument of the pragma import.
3838
3839Interfacing at the class level can be achieved by using the GNAT specific
3840pragmas such as ``CPP_Constructor``.  See the :title:`GNAT_Reference_Manual` for additional information.
3841
3842.. _Linking_a_Mixed_C++_and_Ada_Program:
3843
3844Linking a Mixed C++ & Ada Program
3845^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3846
3847Usually the linker of the C++ development system must be used to link
3848mixed applications because most C++ systems will resolve elaboration
3849issues (such as calling constructors on global class instances)
3850transparently during the link phase. GNAT has been adapted to ease the
3851use of a foreign linker for the last phase. Three cases can be
3852considered:
3853
3854
3855* Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3856  The C++ linker can simply be called by using the C++ specific driver
3857  called ``g++``.
3858
3859  Note that if the C++ code uses inline functions, you will need to
3860  compile your C++ code with the :switch:`-fkeep-inline-functions` switch in
3861  order to provide an existing function implementation that the Ada code can
3862  link with.
3863
3864  .. code-block:: sh
3865
3866    $ g++ -c -fkeep-inline-functions file1.C
3867    $ g++ -c -fkeep-inline-functions file2.C
3868    $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
3869
3870
3871* Using GNAT and G++ from two different GCC installations: If both
3872  compilers are on the :envvar`PATH`, the previous method may be used. It is
3873  important to note that environment variables such as
3874  :envvar:`C_INCLUDE_PATH`, :envvar:`GCC_EXEC_PREFIX`,
3875  :envvar:`BINUTILS_ROOT`, and
3876  :envvar:`GCC_ROOT` will affect both compilers
3877  at the same time and may make one of the two compilers operate
3878  improperly if set during invocation of the wrong compiler.  It is also
3879  very important that the linker uses the proper :file:`libgcc.a` GCC
3880  library -- that is, the one from the C++ compiler installation. The
3881  implicit link command as suggested in the ``gnatmake`` command
3882  from the former example can be replaced by an explicit link command with
3883  the full-verbosity option in order to verify which library is used:
3884
3885  .. code-block:: sh
3886
3887    $ gnatbind ada_unit
3888    $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3889
3890  If there is a problem due to interfering environment variables, it can
3891  be worked around by using an intermediate script. The following example
3892  shows the proper script to use when GNAT has not been installed at its
3893  default location and g++ has been installed at its default location:
3894
3895  .. code-block:: sh
3896
3897    $ cat ./my_script
3898    #!/bin/sh
3899    unset BINUTILS_ROOT
3900    unset GCC_ROOT
3901    c++ $*
3902    $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3903
3904
3905* Using a non-GNU C++ compiler: The commands previously described can be
3906  used to insure that the C++ linker is used. Nonetheless, you need to add
3907  a few more parameters to the link command line, depending on the exception
3908  mechanism used.
3909
3910  If the ``setjmp`` / ``longjmp`` exception mechanism is used, only the paths
3911  to the ``libgcc`` libraries are required:
3912
3913  .. code-block:: sh
3914
3915    $ cat ./my_script
3916    #!/bin/sh
3917    CC $* gcc -print-file-name=libgcc.a gcc -print-file-name=libgcc_eh.a
3918    $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3919
3920
3921  where CC is the name of the non-GNU C++ compiler.
3922
3923  If the "zero cost" exception mechanism is used, and the platform
3924  supports automatic registration of exception tables (e.g., Solaris),
3925  paths to more objects are required:
3926
3927  .. code-block:: sh
3928
3929    $ cat ./my_script
3930    #!/bin/sh
3931    CC gcc -print-file-name=crtbegin.o $* \\
3932    gcc -print-file-name=libgcc.a gcc -print-file-name=libgcc_eh.a \\
3933    gcc -print-file-name=crtend.o
3934    $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3935
3936
3937  If the "zero cost exception" mechanism is used, and the platform
3938  doesn't support automatic registration of exception tables (e.g., HP-UX
3939  or AIX), the simple approach described above will not work and
3940  a pre-linking phase using GNAT will be necessary.
3941
3942
3943Another alternative is to use the :command:`gprbuild` multi-language builder
3944which has a large knowledge base and knows how to link Ada and C++ code
3945together automatically in most cases.
3946
3947.. _A_Simple_Example:
3948
3949A Simple Example
3950^^^^^^^^^^^^^^^^
3951
3952The following example, provided as part of the GNAT examples, shows how
3953to achieve procedural interfacing between Ada and C++ in both
3954directions. The C++ class A has two methods. The first method is exported
3955to Ada by the means of an extern C wrapper function. The second method
3956calls an Ada subprogram. On the Ada side, the C++ calls are modelled by
3957a limited record with a layout comparable to the C++ class. The Ada
3958subprogram, in turn, calls the C++ method. So, starting from the C++
3959main program, the process passes back and forth between the two
3960languages.
3961
3962Here are the compilation commands:
3963
3964.. code-block:: sh
3965
3966     $ gnatmake -c simple_cpp_interface
3967     $ g++ -c cpp_main.C
3968     $ g++ -c ex7.C
3969     $ gnatbind -n simple_cpp_interface
3970     $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++ -lstdc++ ex7.o cpp_main.o
3971
3972Here are the corresponding sources:
3973
3974.. code-block:: cpp
3975
3976     //cpp_main.C
3977
3978     #include "ex7.h"
3979
3980     extern "C" {
3981       void adainit (void);
3982       void adafinal (void);
3983       void method1 (A *t);
3984     }
3985
3986     void method1 (A *t)
3987     {
3988       t->method1 ();
3989     }
3990
3991     int main ()
3992     {
3993       A obj;
3994       adainit ();
3995       obj.method2 (3030);
3996       adafinal ();
3997     }
3998
3999.. code-block:: cpp
4000
4001     //ex7.h
4002
4003     class Origin {
4004      public:
4005       int o_value;
4006     };
4007     class A : public Origin {
4008      public:
4009       void method1 (void);
4010       void method2 (int v);
4011       A();
4012       int   a_value;
4013     };
4014
4015.. code-block:: cpp
4016
4017     //ex7.C
4018
4019     #include "ex7.h"
4020     #include <stdio.h>
4021
4022     extern "C" { void ada_method2 (A *t, int v);}
4023
4024     void A::method1 (void)
4025     {
4026       a_value = 2020;
4027       printf ("in A::method1, a_value = %d \\n",a_value);
4028     }
4029
4030     void A::method2 (int v)
4031     {
4032        ada_method2 (this, v);
4033        printf ("in A::method2, a_value = %d \\n",a_value);
4034     }
4035
4036     A::A(void)
4037     {
4038        a_value = 1010;
4039       printf ("in A::A, a_value = %d \\n",a_value);
4040     }
4041
4042.. code-block:: ada
4043
4044     -- simple_cpp_interface.ads
4045     with System;
4046     package Simple_Cpp_Interface is
4047        type A is limited
4048           record
4049              Vptr    : System.Address;
4050              O_Value : Integer;
4051              A_Value : Integer;
4052           end record;
4053        pragma Convention (C, A);
4054
4055        procedure Method1 (This : in out A);
4056        pragma Import (C, Method1);
4057
4058        procedure Ada_Method2 (This : in out A; V : Integer);
4059        pragma Export (C, Ada_Method2);
4060
4061     end Simple_Cpp_Interface;
4062
4063.. code-block:: ada
4064
4065     -- simple_cpp_interface.adb
4066     package body Simple_Cpp_Interface is
4067
4068        procedure Ada_Method2 (This : in out A; V : Integer) is
4069        begin
4070           Method1 (This);
4071           This.A_Value := V;
4072        end Ada_Method2;
4073
4074     end Simple_Cpp_Interface;
4075
4076
4077.. _Interfacing_with_C++_constructors:
4078
4079Interfacing with C++ constructors
4080^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4081
4082In order to interface with C++ constructors GNAT provides the
4083``pragma CPP_Constructor`` (see the :title:`GNAT_Reference_Manual`
4084for additional information).
4085In this section we present some common uses of C++ constructors
4086in mixed-languages programs in GNAT.
4087
4088Let us assume that we need to interface with the following
4089C++ class:
4090
4091.. code-block:: cpp
4092
4093     class Root {
4094     public:
4095       int  a_value;
4096       int  b_value;
4097       virtual int Get_Value ();
4098       Root();              // Default constructor
4099       Root(int v);         // 1st non-default constructor
4100       Root(int v, int w);  // 2nd non-default constructor
4101     };
4102
4103For this purpose we can write the following package spec (further
4104information on how to build this spec is available in
4105:ref:`Interfacing_with_C++_at_the_Class_Level` and
4106:ref:`Generating_Ada_Bindings_for_C_and_C++_headers`).
4107
4108.. code-block:: ada
4109
4110     with Interfaces.C; use Interfaces.C;
4111     package Pkg_Root is
4112       type Root is tagged limited record
4113          A_Value : int;
4114          B_Value : int;
4115       end record;
4116       pragma Import (CPP, Root);
4117
4118       function Get_Value (Obj : Root) return int;
4119       pragma Import (CPP, Get_Value);
4120
4121       function Constructor return Root;
4122       pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
4123
4124       function Constructor (v : Integer) return Root;
4125       pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
4126
4127       function Constructor (v, w : Integer) return Root;
4128       pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
4129     end Pkg_Root;
4130
4131On the Ada side the constructor is represented by a function (whose
4132name is arbitrary) that returns the classwide type corresponding to
4133the imported C++ class. Although the constructor is described as a
4134function, it is typically a procedure with an extra implicit argument
4135(the object being initialized) at the implementation level. GNAT
4136issues the appropriate call, whatever it is, to get the object
4137properly initialized.
4138
4139Constructors can only appear in the following contexts:
4140
4141* On the right side of an initialization of an object of type ``T``.
4142* On the right side of an initialization of a record component of type ``T``.
4143* In an Ada 2005 limited aggregate.
4144* In an Ada 2005 nested limited aggregate.
4145* In an Ada 2005 limited aggregate that initializes an object built in
4146  place by an extended return statement.
4147
4148In a declaration of an object whose type is a class imported from C++,
4149either the default C++ constructor is implicitly called by GNAT, or
4150else the required C++ constructor must be explicitly called in the
4151expression that initializes the object. For example:
4152
4153.. code-block:: ada
4154
4155     Obj1 : Root;
4156     Obj2 : Root := Constructor;
4157     Obj3 : Root := Constructor (v => 10);
4158     Obj4 : Root := Constructor (30, 40);
4159
4160The first two declarations are equivalent: in both cases the default C++
4161constructor is invoked (in the former case the call to the constructor is
4162implicit, and in the latter case the call is explicit in the object
4163declaration). ``Obj3`` is initialized by the C++ non-default constructor
4164that takes an integer argument, and ``Obj4`` is initialized by the
4165non-default C++ constructor that takes two integers.
4166
4167Let us derive the imported C++ class in the Ada side. For example:
4168
4169.. code-block:: ada
4170
4171     type DT is new Root with record
4172        C_Value : Natural := 2009;
4173     end record;
4174
4175In this case the components DT inherited from the C++ side must be
4176initialized by a C++ constructor, and the additional Ada components
4177of type DT are initialized by GNAT. The initialization of such an
4178object is done either by default, or by means of a function returning
4179an aggregate of type DT, or by means of an extension aggregate.
4180
4181.. code-block:: ada
4182
4183     Obj5 : DT;
4184     Obj6 : DT := Function_Returning_DT (50);
4185     Obj7 : DT := (Constructor (30,40) with C_Value => 50);
4186
4187The declaration of ``Obj5`` invokes the default constructors: the
4188C++ default constructor of the parent type takes care of the initialization
4189of the components inherited from Root, and GNAT takes care of the default
4190initialization of the additional Ada components of type DT (that is,
4191``C_Value`` is initialized to value 2009). The order of invocation of
4192the constructors is consistent with the order of elaboration required by
4193Ada and C++. That is, the constructor of the parent type is always called
4194before the constructor of the derived type.
4195
4196Let us now consider a record that has components whose type is imported
4197from C++. For example:
4198
4199.. code-block:: ada
4200
4201     type Rec1 is limited record
4202        Data1 : Root := Constructor (10);
4203        Value : Natural := 1000;
4204     end record;
4205
4206     type Rec2 (D : Integer := 20) is limited record
4207        Rec   : Rec1;
4208        Data2 : Root := Constructor (D, 30);
4209     end record;
4210
4211The initialization of an object of type ``Rec2`` will call the
4212non-default C++ constructors specified for the imported components.
4213For example:
4214
4215.. code-block:: ada
4216
4217     Obj8 : Rec2 (40);
4218
4219Using Ada 2005 we can use limited aggregates to initialize an object
4220invoking C++ constructors that differ from those specified in the type
4221declarations. For example:
4222
4223.. code-block:: ada
4224
4225     Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
4226                             others => <>),
4227                     others => <>);
4228
4229The above declaration uses an Ada 2005 limited aggregate to
4230initialize ``Obj9``, and the C++ constructor that has two integer
4231arguments is invoked to initialize the ``Data1`` component instead
4232of the constructor specified in the declaration of type ``Rec1``. In
4233Ada 2005 the box in the aggregate indicates that unspecified components
4234are initialized using the expression (if any) available in the component
4235declaration. That is, in this case discriminant ``D`` is initialized
4236to value ``20``, ``Value`` is initialized to value 1000, and the
4237non-default C++ constructor that handles two integers takes care of
4238initializing component ``Data2`` with values ``20,30``.
4239
4240In Ada 2005 we can use the extended return statement to build the Ada
4241equivalent to C++ non-default constructors. For example:
4242
4243.. code-block:: ada
4244
4245     function Constructor (V : Integer) return Rec2 is
4246     begin
4247        return Obj : Rec2 := (Rec => (Data1  => Constructor (V, 20),
4248                                      others => <>),
4249                              others => <>) do
4250           --  Further actions required for construction of
4251           --  objects of type Rec2
4252           ...
4253        end record;
4254     end Constructor;
4255
4256In this example the extended return statement construct is used to
4257build in place the returned object whose components are initialized
4258by means of a limited aggregate. Any further action associated with
4259the constructor can be placed inside the construct.
4260
4261.. _Interfacing_with_C++_at_the_Class_Level:
4262
4263Interfacing with C++ at the Class Level
4264^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4265
4266In this section we demonstrate the GNAT features for interfacing with
4267C++ by means of an example making use of Ada 2005 abstract interface
4268types. This example consists of a classification of animals; classes
4269have been used to model our main classification of animals, and
4270interfaces provide support for the management of secondary
4271classifications. We first demonstrate a case in which the types and
4272constructors are defined on the C++ side and imported from the Ada
4273side, and latter the reverse case.
4274
4275The root of our derivation will be the ``Animal`` class, with a
4276single private attribute (the ``Age`` of the animal), a constructor,
4277and two public primitives to set and get the value of this attribute.
4278
4279.. code-block:: cpp
4280
4281     class Animal {
4282      public:
4283        virtual void Set_Age (int New_Age);
4284        virtual int Age ();
4285        Animal() {Age_Count = 0;};
4286      private:
4287        int Age_Count;
4288     };
4289
4290Abstract interface types are defined in C++ by means of classes with pure
4291virtual functions and no data members. In our example we will use two
4292interfaces that provide support for the common management of ``Carnivore``
4293and ``Domestic`` animals:
4294
4295.. code-block:: cpp
4296
4297     class Carnivore {
4298     public:
4299        virtual int Number_Of_Teeth () = 0;
4300     };
4301
4302     class Domestic {
4303     public:
4304        virtual void Set_Owner (char* Name) = 0;
4305     };
4306
4307Using these declarations, we can now say that a ``Dog`` is an animal that is
4308both Carnivore and Domestic, that is:
4309
4310.. code-block:: cpp
4311
4312     class Dog : Animal, Carnivore, Domestic {
4313      public:
4314        virtual int  Number_Of_Teeth ();
4315        virtual void Set_Owner (char* Name);
4316
4317        Dog(); // Constructor
4318      private:
4319        int  Tooth_Count;
4320        char *Owner;
4321     };
4322
4323In the following examples we will assume that the previous declarations are
4324located in a file named :file:`animals.h`. The following package demonstrates
4325how to import these C++ declarations from the Ada side:
4326
4327.. code-block:: ada
4328
4329     with Interfaces.C.Strings; use Interfaces.C.Strings;
4330     package Animals is
4331       type Carnivore is limited interface;
4332       pragma Convention (C_Plus_Plus, Carnivore);
4333       function Number_Of_Teeth (X : Carnivore)
4334          return Natural is abstract;
4335
4336       type Domestic is limited interface;
4337       pragma Convention (C_Plus_Plus, Domestic);
4338       procedure Set_Owner
4339         (X    : in out Domestic;
4340          Name : Chars_Ptr) is abstract;
4341
4342       type Animal is tagged limited record
4343         Age : Natural;
4344       end record;
4345       pragma Import (C_Plus_Plus, Animal);
4346
4347       procedure Set_Age (X : in out Animal; Age : Integer);
4348       pragma Import (C_Plus_Plus, Set_Age);
4349
4350       function Age (X : Animal) return Integer;
4351       pragma Import (C_Plus_Plus, Age);
4352
4353       function New_Animal return Animal;
4354       pragma CPP_Constructor (New_Animal);
4355       pragma Import (CPP, New_Animal, "_ZN6AnimalC1Ev");
4356
4357       type Dog is new Animal and Carnivore and Domestic with record
4358         Tooth_Count : Natural;
4359         Owner       : Chars_Ptr;
4360       end record;
4361       pragma Import (C_Plus_Plus, Dog);
4362
4363       function Number_Of_Teeth (A : Dog) return Natural;
4364       pragma Import (C_Plus_Plus, Number_Of_Teeth);
4365
4366       procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
4367       pragma Import (C_Plus_Plus, Set_Owner);
4368
4369       function New_Dog return Dog;
4370       pragma CPP_Constructor (New_Dog);
4371       pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
4372     end Animals;
4373
4374Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
4375interfacing with these C++ classes is easy. The only requirement is that all
4376the primitives and components must be declared exactly in the same order in
4377the two languages.
4378
4379Regarding the abstract interfaces, we must indicate to the GNAT compiler by
4380means of a ``pragma Convention (C_Plus_Plus)``, the convention used to pass
4381the arguments to the called primitives will be the same as for C++. For the
4382imported classes we use ``pragma Import`` with convention ``C_Plus_Plus``
4383to indicate that they have been defined on the C++ side; this is required
4384because the dispatch table associated with these tagged types will be built
4385in the C++ side and therefore will not contain the predefined Ada primitives
4386which Ada would otherwise expect.
4387
4388As the reader can see there is no need to indicate the C++ mangled names
4389associated with each subprogram because it is assumed that all the calls to
4390these primitives will be dispatching calls. The only exception is the
4391constructor, which must be registered with the compiler by means of
4392``pragma CPP_Constructor`` and needs to provide its associated C++
4393mangled name because the Ada compiler generates direct calls to it.
4394
4395With the above packages we can now declare objects of type Dog on the Ada side
4396and dispatch calls to the corresponding subprograms on the C++ side. We can
4397also extend the tagged type Dog with further fields and primitives, and
4398override some of its C++ primitives on the Ada side. For example, here we have
4399a type derivation defined on the Ada side that inherits all the dispatching
4400primitives of the ancestor from the C++ side.
4401
4402.. code-block:: ada
4403
4404     with Animals; use Animals;
4405     package Vaccinated_Animals is
4406       type Vaccinated_Dog is new Dog with null record;
4407       function Vaccination_Expired (A : Vaccinated_Dog) return Boolean;
4408     end Vaccinated_Animals;
4409
4410It is important to note that, because of the ABI compatibility, the programmer
4411does not need to add any further information to indicate either the object
4412layout or the dispatch table entry associated with each dispatching operation.
4413
4414Now let us define all the types and constructors on the Ada side and export
4415them to C++, using the same hierarchy of our previous example:
4416
4417.. code-block:: ada
4418
4419     with Interfaces.C.Strings;
4420     use Interfaces.C.Strings;
4421     package Animals is
4422       type Carnivore is limited interface;
4423       pragma Convention (C_Plus_Plus, Carnivore);
4424       function Number_Of_Teeth (X : Carnivore)
4425          return Natural is abstract;
4426
4427       type Domestic is limited interface;
4428       pragma Convention (C_Plus_Plus, Domestic);
4429       procedure Set_Owner
4430         (X    : in out Domestic;
4431          Name : Chars_Ptr) is abstract;
4432
4433       type Animal is tagged record
4434         Age : Natural;
4435       end record;
4436       pragma Convention (C_Plus_Plus, Animal);
4437
4438       procedure Set_Age (X : in out Animal; Age : Integer);
4439       pragma Export (C_Plus_Plus, Set_Age);
4440
4441       function Age (X : Animal) return Integer;
4442       pragma Export (C_Plus_Plus, Age);
4443
4444       function New_Animal return Animal'Class;
4445       pragma Export (C_Plus_Plus, New_Animal);
4446
4447       type Dog is new Animal and Carnivore and Domestic with record
4448         Tooth_Count : Natural;
4449         Owner       : String (1 .. 30);
4450       end record;
4451       pragma Convention (C_Plus_Plus, Dog);
4452
4453       function Number_Of_Teeth (A : Dog) return Natural;
4454       pragma Export (C_Plus_Plus, Number_Of_Teeth);
4455
4456       procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
4457       pragma Export (C_Plus_Plus, Set_Owner);
4458
4459       function New_Dog return Dog'Class;
4460       pragma Export (C_Plus_Plus, New_Dog);
4461     end Animals;
4462
4463Compared with our previous example the only differences are the use of
4464``pragma Convention`` (instead of ``pragma Import``), and the use of
4465``pragma Export`` to indicate to the GNAT compiler that the primitives will
4466be available to C++. Thanks to the ABI compatibility, on the C++ side there is
4467nothing else to be done; as explained above, the only requirement is that all
4468the primitives and components are declared in exactly the same order.
4469
4470For completeness, let us see a brief C++ main program that uses the
4471declarations available in :file:`animals.h` (presented in our first example) to
4472import and use the declarations from the Ada side, properly initializing and
4473finalizing the Ada run-time system along the way:
4474
4475.. code-block:: cpp
4476
4477     #include "animals.h"
4478     #include <iostream>
4479     using namespace std;
4480
4481     void Check_Carnivore (Carnivore *obj) {...}
4482     void Check_Domestic (Domestic *obj)   {...}
4483     void Check_Animal (Animal *obj)       {...}
4484     void Check_Dog (Dog *obj)             {...}
4485
4486     extern "C" {
4487       void adainit (void);
4488       void adafinal (void);
4489       Dog* new_dog ();
4490     }
4491
4492     void test ()
4493     {
4494       Dog *obj = new_dog();  // Ada constructor
4495       Check_Carnivore (obj); // Check secondary DT
4496       Check_Domestic (obj);  // Check secondary DT
4497       Check_Animal (obj);    // Check primary DT
4498       Check_Dog (obj);       // Check primary DT
4499     }
4500
4501     int main ()
4502     {
4503       adainit ();  test();  adafinal ();
4504       return 0;
4505     }
4506
4507.. _Generating_Ada_Bindings_for_C_and_C++_headers:
4508
4509Generating Ada Bindings for C and C++ headers
4510---------------------------------------------
4511
4512.. index:: Binding generation (for C and C++ headers)
4513.. index:: C headers (binding generation)
4514.. index:: C++ headers (binding generation)
4515
4516GNAT includes a binding generator for C and C++ headers which is
4517intended to do 95% of the tedious work of generating Ada specs from C
4518or C++ header files.
4519
4520Note that this capability is not intended to generate 100% correct Ada specs,
4521and will is some cases require manual adjustments, although it can often
4522be used out of the box in practice.
4523
4524Some of the known limitations include:
4525
4526* only very simple character constant macros are translated into Ada
4527  constants. Function macros (macros with arguments) are partially translated
4528  as comments, to be completed manually if needed.
4529* some extensions (e.g. vector types) are not supported
4530* pointers to pointers or complex structures are mapped to System.Address
4531* identifiers with identical name (except casing) will generate compilation
4532  errors (e.g. ``shm_get`` vs ``SHM_GET``).
4533
4534The code is generated using Ada 2012 syntax, which makes it easier to interface
4535with other languages. In most cases you can still use the generated binding
4536even if your code is compiled using earlier versions of Ada (e.g. ``-gnat95``).
4537
4538.. _Running_the_binding_generator:
4539
4540Running the Binding Generator
4541^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4542
4543The binding generator is part of the ``gcc`` compiler and can be
4544invoked via the :switch:`-fdump-ada-spec` switch, which will generate Ada
4545spec files for the header files specified on the command line, and all
4546header files needed by these files transitively. For example:
4547
4548.. code-block:: sh
4549
4550      $ g++ -c -fdump-ada-spec -C /usr/include/time.h
4551      $ gcc -c *.ads
4552
4553will generate, under GNU/Linux, the following files: :file:`time_h.ads`,
4554:file:`bits_time_h.ads`, :file:`stddef_h.ads`, :file:`bits_types_h.ads` which
4555correspond to the files :file:`/usr/include/time.h`,
4556:file:`/usr/include/bits/time.h`, etc..., and will then compile these Ada specs
4557in Ada 2005 mode.
4558
4559The :switch:`-C` switch tells ``gcc`` to extract comments from headers,
4560and will attempt to generate corresponding Ada comments.
4561
4562If you want to generate a single Ada file and not the transitive closure, you
4563can use instead the :switch:`-fdump-ada-spec-slim` switch.
4564
4565You can optionally specify a parent unit, of which all generated units will
4566be children, using :switch:`-fada-spec-parent={unit}`.
4567
4568Note that we recommend when possible to use the *g++* driver to
4569generate bindings, even for most C headers, since this will in general
4570generate better Ada specs. For generating bindings for C++ headers, it is
4571mandatory to use the *g++* command, or *gcc -x c++* which
4572is equivalent in this case. If *g++* cannot work on your C headers
4573because of incompatibilities between C and C++, then you can fallback to
4574``gcc`` instead.
4575
4576For an example of better bindings generated from the C++ front-end,
4577the name of the parameters (when available) are actually ignored by the C
4578front-end. Consider the following C header:
4579
4580.. code-block:: c
4581
4582     extern void foo (int variable);
4583
4584with the C front-end, ``variable`` is ignored, and the above is handled as:
4585
4586.. code-block:: c
4587
4588     extern void foo (int);
4589
4590generating a generic:
4591
4592.. code-block:: ada
4593
4594     procedure foo (param1 : int);
4595
4596with the C++ front-end, the name is available, and we generate:
4597
4598.. code-block:: ada
4599
4600     procedure foo (variable : int);
4601
4602In some cases, the generated bindings will be more complete or more meaningful
4603when defining some macros, which you can do via the :switch:`-D` switch. This
4604is for example the case with :file:`Xlib.h` under GNU/Linux:
4605
4606.. code-block:: sh
4607
4608      $ g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
4609
4610The above will generate more complete bindings than a straight call without
4611the :switch:`-DXLIB_ILLEGAL_ACCESS` switch.
4612
4613In other cases, it is not possible to parse a header file in a stand-alone
4614manner, because other include files need to be included first. In this
4615case, the solution is to create a small header file including the needed
4616``#include`` and possible ``#define`` directives. For example, to
4617generate Ada bindings for :file:`readline/readline.h`, you need to first
4618include :file:`stdio.h`, so you can create a file with the following two
4619lines in e.g. :file:`readline1.h`:
4620
4621.. code-block:: cpp
4622
4623      #include <stdio.h>
4624      #include <readline/readline.h>
4625
4626and then generate Ada bindings from this file:
4627
4628.. code-block:: sh
4629
4630      $ g++ -c -fdump-ada-spec readline1.h
4631
4632
4633.. _Generating_bindings_for_C++_headers:
4634
4635Generating Bindings for C++ Headers
4636^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4637
4638Generating bindings for C++ headers is done using the same options, always
4639with the *g++* compiler. Note that generating Ada spec from C++ headers is a
4640much more complex job and support for C++ headers is much more limited that
4641support for C headers. As a result, you will need to modify the resulting
4642bindings by hand more extensively when using C++ headers.
4643
4644In this mode, C++ classes will be mapped to Ada tagged types, constructors
4645will be mapped using the ``CPP_Constructor`` pragma, and when possible,
4646multiple inheritance of abstract classes will be mapped to Ada interfaces
4647(see the *Interfacing to C++* section in the :title:`GNAT Reference Manual`
4648for additional information on interfacing to C++).
4649
4650For example, given the following C++ header file:
4651
4652.. code-block:: cpp
4653
4654       class Carnivore {
4655       public:
4656          virtual int Number_Of_Teeth () = 0;
4657       };
4658
4659       class Domestic {
4660       public:
4661          virtual void Set_Owner (char* Name) = 0;
4662       };
4663
4664       class Animal {
4665       public:
4666         int Age_Count;
4667         virtual void Set_Age (int New_Age);
4668       };
4669
4670       class Dog : Animal, Carnivore, Domestic {
4671        public:
4672         int  Tooth_Count;
4673         char *Owner;
4674
4675         virtual int  Number_Of_Teeth ();
4676         virtual void Set_Owner (char* Name);
4677
4678         Dog();
4679       };
4680
4681The corresponding Ada code is generated:
4682
4683.. code-block:: ada
4684
4685         package Class_Carnivore is
4686           type Carnivore is limited interface;
4687           pragma Import (CPP, Carnivore);
4688
4689           function Number_Of_Teeth (this : access Carnivore) return int is abstract;
4690         end;
4691         use Class_Carnivore;
4692
4693         package Class_Domestic is
4694           type Domestic is limited interface;
4695           pragma Import (CPP, Domestic);
4696
4697           procedure Set_Owner
4698             (this : access Domestic;
4699              Name : Interfaces.C.Strings.chars_ptr) is abstract;
4700         end;
4701         use Class_Domestic;
4702
4703         package Class_Animal is
4704           type Animal is tagged limited record
4705             Age_Count : aliased int;
4706           end record;
4707           pragma Import (CPP, Animal);
4708
4709           procedure Set_Age (this : access Animal; New_Age : int);
4710           pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
4711         end;
4712         use Class_Animal;
4713
4714         package Class_Dog is
4715           type Dog is new Animal and Carnivore and Domestic with record
4716             Tooth_Count : aliased int;
4717             Owner : Interfaces.C.Strings.chars_ptr;
4718           end record;
4719           pragma Import (CPP, Dog);
4720
4721           function Number_Of_Teeth (this : access Dog) return int;
4722           pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
4723
4724           procedure Set_Owner
4725             (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
4726           pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
4727
4728           function New_Dog return Dog;
4729           pragma CPP_Constructor (New_Dog);
4730           pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
4731         end;
4732         use Class_Dog;
4733
4734
4735.. _Switches_for_Ada_Binding_Generation:
4736
4737Switches
4738^^^^^^^^
4739
4740.. index:: -fdump-ada-spec (gcc)
4741
4742:switch:`-fdump-ada-spec`
4743  Generate Ada spec files for the given header files transitively (including
4744  all header files that these headers depend upon).
4745
4746.. index:: -fdump-ada-spec-slim (gcc)
4747
4748:switch:`-fdump-ada-spec-slim`
4749  Generate Ada spec files for the header files specified on the command line
4750  only.
4751
4752.. index:: -fada-spec-parent (gcc)
4753
4754:switch:`-fada-spec-parent={unit}`
4755  Specifies that all files generated by :switch:`-fdump-ada-spec` are
4756  to be child units of the specified parent unit.
4757
4758.. index:: -C (gcc)
4759
4760:switch:`-C`
4761  Extract comments from headers and generate Ada comments in the Ada spec files.
4762
4763.. _Generating_C_Headers_for_Ada_Specifications:
4764
4765Generating C Headers for Ada Specifications
4766-------------------------------------------
4767
4768.. index:: Binding generation (for Ada specs)
4769.. index:: C headers (binding generation)
4770
4771GNAT includes a C header generator for Ada specifications which supports
4772Ada types that have a direct mapping to C types. This includes in particular
4773support for:
4774
4775* Scalar types
4776* Constrained arrays
4777* Records (untagged)
4778* Composition of the above types
4779* Constant declarations
4780* Object declarations
4781* Subprogram declarations
4782
4783Running the C Header Generator
4784^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4785
4786The C header generator is part of the GNAT compiler and can be invoked via
4787the :switch:`-gnatceg` combination of switches, which will generate a :file:`.h`
4788file corresponding to the given input file (Ada spec or body). Note that
4789only spec files are processed in any case, so giving a spec or a body file
4790as input is equivalent. For example:
4791
4792.. code-block:: sh
4793
4794   $ gcc -c -gnatceg pack1.ads
4795
4796will generate a self-contained file called :file:`pack1.h` including
4797common definitions from the Ada Standard package, followed by the
4798definitions included in :file:`pack1.ads`, as well as all the other units
4799withed by this file.
4800
4801For instance, given the following Ada files:
4802
4803.. code-block:: ada
4804
4805   package Pack2 is
4806      type Int is range 1 .. 10;
4807   end Pack2;
4808
4809.. code-block:: ada
4810
4811   with Pack2;
4812
4813   package Pack1 is
4814      type Rec is record
4815         Field1, Field2 : Pack2.Int;
4816      end record;
4817
4818      Global : Rec := (1, 2);
4819
4820      procedure Proc1 (R : Rec);
4821      procedure Proc2 (R : in out Rec);
4822   end Pack1;
4823
4824The above ``gcc`` command will generate the following :file:`pack1.h` file:
4825
4826.. code-block:: c
4827
4828   /* Standard definitions skipped */
4829   #ifndef PACK2_ADS
4830   #define PACK2_ADS
4831   typedef short_short_integer pack2__TintB;
4832   typedef pack2__TintB pack2__int;
4833   #endif /* PACK2_ADS */
4834
4835   #ifndef PACK1_ADS
4836   #define PACK1_ADS
4837   typedef struct _pack1__rec {
4838     pack2__int field1;
4839     pack2__int field2;
4840   } pack1__rec;
4841   extern pack1__rec pack1__global;
4842   extern void pack1__proc1(const pack1__rec r);
4843   extern void pack1__proc2(pack1__rec *r);
4844   #endif /* PACK1_ADS */
4845
4846You can then ``include`` :file:`pack1.h` from a C source file and use the types,
4847call subprograms, reference objects, and constants.
4848
4849.. _GNAT_and_Other_Compilation_Models:
4850
4851GNAT and Other Compilation Models
4852=================================
4853
4854This section compares the GNAT model with the approaches taken in
4855other environents, first the C/C++ model and then the mechanism that
4856has been used in other Ada systems, in particular those traditionally
4857used for Ada 83.
4858
4859.. _Comparison_between_GNAT_and_C/C++_Compilation_Models:
4860
4861Comparison between GNAT and C/C++ Compilation Models
4862----------------------------------------------------
4863
4864The GNAT model of compilation is close to the C and C++ models. You can
4865think of Ada specs as corresponding to header files in C. As in C, you
4866don't need to compile specs; they are compiled when they are used. The
4867Ada |with| is similar in effect to the ``#include`` of a C
4868header.
4869
4870One notable difference is that, in Ada, you may compile specs separately
4871to check them for semantic and syntactic accuracy. This is not always
4872possible with C headers because they are fragments of programs that have
4873less specific syntactic or semantic rules.
4874
4875The other major difference is the requirement for running the binder,
4876which performs two important functions. First, it checks for
4877consistency. In C or C++, the only defense against assembling
4878inconsistent programs lies outside the compiler, in a makefile, for
4879example. The binder satisfies the Ada requirement that it be impossible
4880to construct an inconsistent program when the compiler is used in normal
4881mode.
4882
4883.. index:: Elaboration order control
4884
4885The other important function of the binder is to deal with elaboration
4886issues. There are also elaboration issues in C++ that are handled
4887automatically. This automatic handling has the advantage of being
4888simpler to use, but the C++ programmer has no control over elaboration.
4889Where ``gnatbind`` might complain there was no valid order of
4890elaboration, a C++ compiler would simply construct a program that
4891malfunctioned at run time.
4892
4893.. _Comparison_between_GNAT_and_Conventional_Ada_Library_Models:
4894
4895Comparison between GNAT and Conventional Ada Library Models
4896-----------------------------------------------------------
4897
4898This section is intended for Ada programmers who have
4899used an Ada compiler implementing the traditional Ada library
4900model, as described in the Ada Reference Manual.
4901
4902.. index:: GNAT library
4903
4904In GNAT, there is no 'library' in the normal sense. Instead, the set of
4905source files themselves acts as the library. Compiling Ada programs does
4906not generate any centralized information, but rather an object file and
4907a ALI file, which are of interest only to the binder and linker.
4908In a traditional system, the compiler reads information not only from
4909the source file being compiled, but also from the centralized library.
4910This means that the effect of a compilation depends on what has been
4911previously compiled. In particular:
4912
4913* When a unit is |withed|, the unit seen by the compiler corresponds
4914  to the version of the unit most recently compiled into the library.
4915
4916* Inlining is effective only if the necessary body has already been
4917  compiled into the library.
4918
4919* Compiling a unit may obsolete other units in the library.
4920
4921In GNAT, compiling one unit never affects the compilation of any other
4922units because the compiler reads only source files. Only changes to source
4923files can affect the results of a compilation. In particular:
4924
4925* When a unit is |withed|, the unit seen by the compiler corresponds
4926  to the source version of the unit that is currently accessible to the
4927  compiler.
4928
4929  .. index:: Inlining
4930
4931* Inlining requires the appropriate source files for the package or
4932  subprogram bodies to be available to the compiler. Inlining is always
4933  effective, independent of the order in which units are compiled.
4934
4935* Compiling a unit never affects any other compilations. The editing of
4936  sources may cause previous compilations to be out of date if they
4937  depended on the source file being modified.
4938
4939The most important result of these differences is that order of compilation
4940is never significant in GNAT. There is no situation in which one is
4941required to do one compilation before another. What shows up as order of
4942compilation requirements in the traditional Ada library becomes, in
4943GNAT, simple source dependencies; in other words, there is only a set
4944of rules saying what source files must be present when a file is
4945compiled.
4946
4947
4948.. _Using_GNAT_Files_with_External_Tools:
4949
4950Using GNAT Files with External Tools
4951====================================
4952
4953This section explains how files that are produced by GNAT may be
4954used with tools designed for other languages.
4955
4956
4957.. _Using_Other_Utility_Programs_with_GNAT:
4958
4959Using Other Utility Programs with GNAT
4960--------------------------------------
4961
4962The object files generated by GNAT are in standard system format and in
4963particular the debugging information uses this format. This means
4964programs generated by GNAT can be used with existing utilities that
4965depend on these formats.
4966
4967In general, any utility program that works with C will also often work with
4968Ada programs generated by GNAT. This includes software utilities such as
4969gprof (a profiling program), gdb (the FSF debugger), and utilities such
4970as Purify.
4971
4972
4973.. _The_External_Symbol_Naming_Scheme_of_GNAT:
4974
4975The External Symbol Naming Scheme of GNAT
4976-----------------------------------------
4977
4978In order to interpret the output from GNAT, when using tools that are
4979originally intended for use with other languages, it is useful to
4980understand the conventions used to generate link names from the Ada
4981entity names.
4982
4983All link names are in all lowercase letters. With the exception of library
4984procedure names, the mechanism used is simply to use the full expanded
4985Ada name with dots replaced by double underscores. For example, suppose
4986we have the following package spec:
4987
4988.. code-block:: ada
4989
4990     package QRS is
4991        MN : Integer;
4992     end QRS;
4993
4994.. index:: pragma Export
4995
4996The variable ``MN`` has a full expanded Ada name of ``QRS.MN``, so
4997the corresponding link name is ``qrs__mn``.
4998Of course if a ``pragma Export`` is used this may be overridden:
4999
5000.. code-block:: ada
5001
5002     package Exports is
5003        Var1 : Integer;
5004        pragma Export (Var1, C, External_Name => "var1_name");
5005        Var2 : Integer;
5006        pragma Export (Var2, C, Link_Name => "var2_link_name");
5007     end Exports;
5008
5009In this case, the link name for ``Var1`` is whatever link name the
5010C compiler would assign for the C function ``var1_name``. This typically
5011would be either ``var1_name`` or ``_var1_name``, depending on operating
5012system conventions, but other possibilities exist. The link name for
5013``Var2`` is ``var2_link_name``, and this is not operating system
5014dependent.
5015
5016One exception occurs for library level procedures. A potential ambiguity
5017arises between the required name ``_main`` for the C main program,
5018and the name we would otherwise assign to an Ada library level procedure
5019called ``Main`` (which might well not be the main program).
5020
5021To avoid this ambiguity, we attach the prefix ``_ada_`` to such
5022names. So if we have a library level procedure such as:
5023
5024.. code-block:: ada
5025
5026     procedure Hello (S : String);
5027
5028the external name of this procedure will be ``_ada_hello``.
5029