Ability to build the GNAT runtime with project files
[official-gcc.git] / gcc / ada / doc / gnat_ugn / the_gnat_compilation_model.rst
blob0b587efac12014b5c6667338ef54e5824f51ae3b
1 .. role:: switch(samp)
3 .. |with| replace:: *with*
4 .. |withs| replace:: *with*\ s
5 .. |withed| replace:: *with*\ ed
6 .. |withing| replace:: *with*\ ing
8 .. -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
11 .. _The_GNAT_Compilation_Model:
13 **************************
14 The GNAT Compilation Model
15 **************************
17 .. index:: ! GNAT compilation model
19 .. index:: Compilation model
21 This chapter describes the compilation model used by GNAT. Although
22 similar to that used by other languages such as C and C++, this model
23 is substantially different from the traditional Ada compilation models,
24 which are based on a centralized program library. The chapter covers
25 the following material:
27 * Topics related to source file makeup and naming
29   * :ref:`Source_Representation`
30   * :ref:`Foreign_Language_Representation`
31   * :ref:`File_Naming_Topics_and_Utilities`
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`
45 .. _Source_Representation:
47 Source Representation
48 =====================
50 .. index:: Latin-1
52 .. index:: VT, HT, CR, LF, FF
54 Ada source programs are represented in standard text files, using
55 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
56 7-bit ASCII set, plus additional characters used for
57 representing foreign languages (see :ref:`Foreign_Language_Representation`
58 for support of non-USA character sets). The format effector characters
59 are represented using their standard ASCII encodings, as follows:
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     =========== ======================= ===========
71 Source files are in standard text file format. In addition, GNAT will
72 recognize a wide variety of stream formats, in which the end of
73 physical lines is marked by any of the following sequences:
74 ``LF``, ``CR``, ``CR-LF``, or ``LF-CR``. This is useful
75 in accommodating files that are imported from other operating systems.
77 .. index:: pair: End of source file; Source file, end
79 .. index:: SUB (control character)
81 The end of a source file is normally represented by the physical end of
82 file. However, the control character ``16#1A#`` (:kbd:`SUB`) is also
83 recognized as signalling the end of the source file. Again, this is
84 provided for compatibility with other operating systems where this
85 code is used to represent the end of file.
87 .. index:: spec (definition), compilation (definition)
89 Each file contains a single Ada compilation unit, including any pragmas
90 associated with the unit. For example, this means you must place a
91 package declaration (a package *spec*) and the corresponding body in
92 separate files. An Ada *compilation* (which is a sequence of
93 compilation units) is represented using a sequence of files. Similarly,
94 you will place each subunit or child unit in a separate file.
96 .. _Foreign_Language_Representation:
98 Foreign Language Representation
99 ===============================
101 GNAT supports the standard character sets defined in Ada as well as
102 several other non-standard character sets for use in localized versions
103 of the compiler (:ref:`Character_Set_Control`).
105 .. _Latin-1:
107 Latin-1
108 -------
110 .. index:: Latin-1
112 The basic character set is Latin-1. This character set is defined by ISO
113 standard 8859, part 1. The lower half (character codes ``16#00#``
114 ... ``16#7F#)`` is identical to standard ASCII coding, but the upper
115 half is used to represent additional characters. These include extended letters
116 used by European languages, such as French accents, the vowels with umlauts
117 used in German, and the extra letter A-ring used in Swedish.
119 .. index:: Ada.Characters.Latin_1
121 For a complete list of Latin-1 codes and their encodings, see the source
122 file of library unit ``Ada.Characters.Latin_1`` in file
123 :file:`a-chlat1.ads`.
124 You may use any of these extended characters freely in character or
125 string literals. In addition, the extended characters that represent
126 letters can be used in identifiers.
128 .. _Other_8-Bit_Codes:
130 Other 8-Bit Codes
131 -----------------
133 GNAT also supports several other 8-bit coding schemes:
136 .. index:: Latin-2
137 .. index:: ISO 8859-2
139 *ISO 8859-2 (Latin-2)*
140   Latin-2 letters allowed in identifiers, with uppercase and lowercase
141   equivalence.
143 .. index:: Latin-3
144 .. index:: ISO 8859-3
146 *ISO 8859-3 (Latin-3)*
147   Latin-3 letters allowed in identifiers, with uppercase and lowercase
148   equivalence.
151 .. index:: Latin-4
152 .. index:: ISO 8859-4
154 *ISO 8859-4 (Latin-4)*
155   Latin-4 letters allowed in identifiers, with uppercase and lowercase
156   equivalence.
159 .. index:: ISO 8859-5
160 .. index:: Cyrillic
162 *ISO 8859-5 (Cyrillic)*
163   ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
164   lowercase equivalence.
166 .. index:: ISO 8859-15
167 .. index:: Latin-9
169 *ISO 8859-15 (Latin-9)*
170   ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
171   lowercase equivalence
173 .. index:: code page 437 (IBM PC)
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.
182 .. index:: code page 850 (IBM PC)
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.
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).
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.
203 For precise data on the encodings permitted, and the uppercase and lowercase
204 equivalences that are recognized, see the file :file:`csets.adb` in
205 the GNAT compiler sources. You will need to obtain a full source release
206 of GNAT to obtain this file.
208 .. _Wide_Character_Encodings:
210 Wide_Character Encodings
211 ------------------------
213 GNAT allows wide character codes to appear in character and string
214 literals, and also optionally in identifiers, by means of the following
215 possible encoding schemes:
217 *Hex Coding*
218   In this encoding, a wide character is represented by the following five
219   character sequence::
221     ESC a b c d
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.
229 *Upper-Half Coding*
230   .. index:: Upper-Half Coding
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.
239 *Shift JIS Coding*
240   .. index:: Shift JIS Coding
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.
251 *EUC Coding*
252   .. index:: EUC Coding
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.
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::
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#
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).
281 *Brackets Coding*
282   In this encoding, a wide character is represented by the following eight
283   character sequence::
285     [ " a b c d " ]
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']``.
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.
298 .. note::
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.
304 .. _Wide_Wide_Character_Encodings:
306 Wide_Wide_Character Encodings
307 -----------------------------
309 GNAT allows wide wide character codes to appear in character and string
310 literals, and also optionally in identifiers, by means of the following
311 possible encoding schemes:
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::
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
328   where the ``xxx`` bits correspond to the left-padded bits of the
329   32-bit character value.
331 *Brackets Coding*
332   In this encoding, a wide wide character is represented by the following ten or
333   twelve byte character sequence::
335     [ " a b c d e f " ]
336     [ " a b c d e f g h " ]
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#``.
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.
348 .. _File_Naming_Topics_and_Utilities:
350 File Naming Topics and Utilities
351 ================================
353 GNAT has a default file naming scheme and also provides the user with
354 a high degree of control over how the names and extensions of the
355 source files correspond to the Ada compilation units that they contain.
358 .. _File_Naming_Rules:
360 File Naming Rules
361 -----------------
363 The default file name is determined by the name of the unit that the
364 file contains. The name is formed by taking the full expanded name of
365 the unit and replacing the separating dots with hyphens and using
366 lowercase for all letters.
368 An exception arises if the file name generated by the above rules starts
369 with one of the characters
370 ``a``, ``g``, ``i``, or ``s``, and the second character is a
371 minus. In this case, the character tilde is used in place
372 of the minus. The reason for this special rule is to avoid clashes with
373 the standard names for child units of the packages System, Ada,
374 Interfaces, and GNAT, which use the prefixes
375 ``s-``, ``a-``, ``i-``, and ``g-``,
376 respectively.
378 The file extension is :file:`.ads` for a spec and
379 :file:`.adb` for a body. The following table shows some
380 examples of these rules.
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    ============================ ===============================
395 Following these rules can result in excessively long
396 file names if corresponding
397 unit names are long (for example, if child units or subunits are
398 heavily nested). An option is available to shorten such long file names
399 (called file name 'krunching'). This may be particularly useful when
400 programs being developed with GNAT are to be used on operating systems
401 with limited file name lengths. :ref:`Using_gnatkr`.
403 Of course, no file shortening algorithm can guarantee uniqueness over
404 all possible unit names; if file name krunching is used, it is your
405 responsibility to ensure no name clashes occur. Alternatively you
406 can specify the exact file names that you want used, as described
407 in the next section. Finally, if your Ada programs are migrating from a
408 compiler with a different naming convention, you can use the gnatchop
409 utility to produce source files that follow the GNAT naming conventions.
410 (For details see :ref:`Renaming_Files_with_gnatchop`.)
412 Note: in the case of Windows or Mac OS operating systems, case is not
413 significant. 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.
415 However, case is significant for other operating systems, so for example,
416 if you want to use other than canonically cased file names on a Unix system,
417 you need to follow the procedures described in the next section.
419 .. _Using_Other_File_Names:
421 Using Other File Names
422 ----------------------
424 .. index:: File names
426 In the previous section, we have described the default rules used by
427 GNAT to determine the file name in which a given unit resides. It is
428 often convenient to follow these default rules, and if you follow them,
429 the compiler knows without being explicitly told where to find all
430 the files it needs.
432 .. index:: Source_File_Name pragma
434 However, in some cases, particularly when a program is imported from
435 another Ada compiler environment, it may be more convenient for the
436 programmer to specify which file names contain which units. GNAT allows
437 arbitrary file names to be used by means of the Source_File_Name pragma.
438 The form of this pragma is as shown in the following examples:
440 .. code-block:: ada
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");
447 As shown in this example, the first argument for the pragma is the unit
448 name (in this example a child unit). The second argument has the form
449 of a named association. The identifier
450 indicates whether the file name is for a spec or a body;
451 the file name itself is given by a string literal.
453 The source file name pragma is a configuration pragma, which means that
454 normally it will be placed in the :file:`gnat.adc`
455 file used to hold configuration
456 pragmas that apply to a complete compilation environment.
457 For more details on how the :file:`gnat.adc` file is created and used
458 see :ref:`Handling_of_Configuration_Pragmas`.
460 .. index:: gnat.adc
462 GNAT allows completely arbitrary file names to be specified using the
463 source file name pragma. However, if the file name specified has an
464 extension other than :file:`.ads` or :file:`.adb` it is necessary to use
465 a special syntax when compiling the file. The name in this case must be
466 preceded by the special sequence ``-x`` followed by a space and the name
467 of the language, here ``ada``, as in:
469 .. code-block:: sh
471      $ gcc -c -x ada peculiar_file_name.sim
473 ``gnatmake`` handles non-standard file names in the usual manner (the
474 non-standard file name for the main program is simply used as the
475 argument to gnatmake). Note that if the extension is also non-standard,
476 then it must be included in the ``gnatmake`` command, it may not
477 be omitted.
479 .. _Alternative_File_Naming_Schemes:
481 Alternative File Naming Schemes
482 -------------------------------
484 .. index:: File naming schemes, alternative
486 .. index:: File names
488 The previous section described the use of the ``Source_File_Name``
489 pragma to allow arbitrary names to be assigned to individual source files.
490 However, this approach requires one pragma for each file, and especially in
491 large systems can result in very long :file:`gnat.adc` files, and also create
492 a maintenance problem.
494 .. index:: Source_File_Name pragma
496 GNAT also provides a facility for specifying systematic file naming schemes
497 other than the standard default naming scheme previously described. An
498 alternative scheme for naming is specified by the use of
499 ``Source_File_Name`` pragmas having the following format:
501 .. code-block:: ada
503      pragma Source_File_Name (
504         Spec_File_Name  => FILE_NAME_PATTERN
505       [ , Casing          => CASING_SPEC]
506       [ , Dot_Replacement => STRING_LITERAL ] );
508      pragma Source_File_Name (
509         Body_File_Name  => FILE_NAME_PATTERN
510       [ , Casing          => CASING_SPEC ]
511       [ , Dot_Replacement => STRING_LITERAL ] ) ;
513      pragma Source_File_Name (
514         Subunit_File_Name  => FILE_NAME_PATTERN
515       [ , Casing          => CASING_SPEC ]
516       [ , Dot_Replacement => STRING_LITERAL ] ) ;
518      FILE_NAME_PATTERN ::= STRING_LITERAL
519      CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
521 The ``FILE_NAME_PATTERN`` string shows how the file name is constructed.
522 It contains a single asterisk character, and the unit name is substituted
523 systematically for this asterisk. The optional parameter
524 ``Casing`` indicates
525 whether the unit name is to be all upper-case letters, all lower-case letters,
526 or mixed-case. If no
527 ``Casing`` parameter is used, then the default is all
528 lower-case.
530 The optional ``Dot_Replacement`` string is used to replace any periods
531 that occur in subunit or child unit names. If no ``Dot_Replacement``
532 argument is used then separating dots appear unchanged in the resulting
533 file name.
534 Although the above syntax indicates that the
535 ``Casing`` argument must appear
536 before the ``Dot_Replacement`` argument, but it
537 is also permissible to write these arguments in the opposite order.
539 As indicated, it is possible to specify different naming schemes for
540 bodies, specs, and subunits. Quite often the rule for subunits is the
541 same as the rule for bodies, in which case, there is no need to give
542 a separate ``Subunit_File_Name`` rule, and in this case the
543 ``Body_File_name`` rule is used for subunits as well.
545 The separate rule for subunits can also be used to implement the rather
546 unusual case of a compilation environment (e.g., a single directory) which
547 contains a subunit and a child unit with the same unit name. Although
548 both units cannot appear in the same partition, the Ada Reference Manual
549 allows (but does not require) the possibility of the two units coexisting
550 in the same environment.
552 The file name translation works in the following steps:
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.
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.
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.
566 As an example of the use of this mechanism, consider a commonly used scheme
567 in which file names are all lower case, with separating periods copied
568 unchanged to the resulting file name, and specs end with :file:`.1.ada`, and
569 bodies end with :file:`.2.ada`. GNAT will follow this scheme if the following
570 two pragmas appear:
572 .. code-block:: ada
574      pragma Source_File_Name
575        (Spec_File_Name => ".1.ada");
576      pragma Source_File_Name
577        (Body_File_Name => ".2.ada");
579 The default GNAT scheme is actually implemented by providing the following
580 default pragmas internally:
582 .. code-block:: ada
584      pragma Source_File_Name
585        (Spec_File_Name => ".ads", Dot_Replacement => "-");
586      pragma Source_File_Name
587        (Body_File_Name => ".adb", Dot_Replacement => "-");
589 Our final example implements a scheme typically used with one of the
590 Ada 83 compilers, where the separator character for subunits was '__'
591 (two underscores), specs were identified by adding :file:`_.ADA`, bodies
592 by adding :file:`.ADA`, and subunits by
593 adding :file:`.SEP`. All file names were
594 upper case. Child units were not present of course since this was an
595 Ada 83 compiler, but it seems reasonable to extend this scheme to use
596 the same double underscore separator for child units.
598 .. code-block:: ada
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);
614 .. index:: ! gnatname
616 .. _Handling_Arbitrary_File_Naming_Conventions_with_gnatname:
618 Handling Arbitrary File Naming Conventions with ``gnatname``
619 ------------------------------------------------------------
621 .. index:: File Naming Conventions
623 .. _Arbitrary_File_Naming_Conventions:
625 Arbitrary File Naming Conventions
626 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
628 The GNAT compiler must be able to know the source file name of a compilation
629 unit.  When using the standard GNAT default file naming conventions
630 (``.ads`` for specs, ``.adb`` for bodies), the GNAT compiler
631 does not need additional information.
633 When the source file names do not follow the standard GNAT default file naming
634 conventions, the GNAT compiler must be given additional information through
635 a configuration pragmas file (:ref:`Configuration_Pragmas`)
636 or a project file.
637 When the non-standard file naming conventions are well-defined,
638 a small number of pragmas ``Source_File_Name`` specifying a naming pattern
639 (:ref:`Alternative_File_Naming_Schemes`) may be sufficient. However,
640 if the file naming conventions are irregular or arbitrary, a number
641 of pragma ``Source_File_Name`` for individual compilation units
642 must be defined.
643 To help maintain the correspondence between compilation unit names and
644 source file names within the compiler,
645 GNAT provides a tool ``gnatname`` to generate the required pragmas for a
646 set of files.
648 .. _Running_gnatname:
650 Running ``gnatname``
651 ^^^^^^^^^^^^^^^^^^^^
653 The usual form of the ``gnatname`` command is:
655 .. code-block:: sh
657       $ gnatname [ switches ]  naming_pattern  [ naming_patterns ]
658           [--and [ switches ]  naming_pattern  [ naming_patterns ]]
661 All of the arguments are optional. If invoked without any argument,
662 ``gnatname`` will display its usage.
664 When used with at least one naming pattern, ``gnatname`` will attempt to
665 find all the compilation units in files that follow at least one of the
666 naming patterns. To find these compilation units,
667 ``gnatname`` will use the GNAT compiler in syntax-check-only mode on all
668 regular files.
670 One or several Naming Patterns may be given as arguments to ``gnatname``.
671 Each Naming Pattern is enclosed between double quotes (or single
672 quotes on Windows).
673 A Naming Pattern is a regular expression similar to the wildcard patterns
674 used in file names by the Unix shells or the DOS prompt.
676 ``gnatname`` may be called with several sections of directories/patterns.
677 Sections are separated by the switch :switch:`--and`. In each section, there must be
678 at least one pattern. If no directory is specified in a section, the current
679 directory (or the project directory if :switch:`-P` is used) is implied.
680 The options other that the directory switches and the patterns apply globally
681 even if they are in different sections.
683 Examples of Naming Patterns are::
685      "*.[12].ada"
686      "*.ad[sb]*"
687      "body_*"    "spec_*"
689 For a more complete description of the syntax of Naming Patterns,
690 see the second kind of regular expressions described in :file:`g-regexp.ads`
691 (the 'Glob' regular expressions).
693 When invoked without the switch :switch:`-P`, ``gnatname`` will create a
694 configuration pragmas file :file:`gnat.adc` in the current working directory,
695 with pragmas ``Source_File_Name`` for each file that contains a valid Ada
696 unit.
698 .. _Switches_for_gnatname:
700 Switches for ``gnatname``
701 ^^^^^^^^^^^^^^^^^^^^^^^^^
703 Switches for ``gnatname`` must precede any specified Naming Pattern.
705 You may specify any of the following switches to ``gnatname``:
707 .. index:: --version (gnatname)
709 :switch:`--version`
710   Display Copyright and version, then exit disregarding all other options.
712 .. index:: --help (gnatname)
714 :switch:`--help`
715   If :switch:`--version` was not used, display usage, then exit disregarding
716   all other options.
718 :switch:`--subdirs={dir}`
719   Real object, library or exec directories are subdirectories <dir> of the
720   specified ones.
722 :switch:`--no-backup`
723   Do not create a backup copy of an existing project file.
725 :switch:`--and`
726   Start another section of directories/patterns.
728 .. index:: -c (gnatname)
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).
740 .. index:: -d (gnatname)
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.
763 .. index:: -D (gnatname)
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`.
775 :switch:`-eL`
776   Follow symbolic links when processing project files.
778   .. index:: -f (gnatname)
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,
786   .. code-block:: sh
788      gnatname -Pprj -f"*.c" "*.ada"
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`.
794   .. index:: -h (gnatname)
796 :switch:`-h`
797   Output usage (help) information. The output is written to :file:`stdout`.
799   .. index:: -P (gnatname)
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.
813   .. index:: -v (gnatname)
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.
822 .. index:: -v -v (gnatname)
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.
829   .. index:: -x (gnatname)
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,
835   .. code-block:: sh
837       gnatname -x "*_nt.ada" "*.ada"
839   will look for Ada units in all files with the :file:`.ada` extension,
840   except those whose names end with :file:`_nt.ada`.
843 .. _Examples_of_gnatname_Usage:
845 Examples of ``gnatname`` Usage
846 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
848 .. code-block:: sh
850      $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
852 In this example, the directory :file:`/home/me` must already exist
853 and be writable. In addition, the directory
854 :file:`/home/me/sources` (specified by
855 :switch:`-d sources`) must exist and be readable.
857 Note the optional spaces after :switch:`-c` and :switch:`-d`.
859 .. code-block:: sh
861      $ gnatname -P/home/me/proj -x "*_nt_body.ada"
862      -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
864 Note that several switches :switch:`-d` may be used,
865 even in conjunction with one or several switches
866 :switch:`-D`. Several Naming Patterns and one excluded pattern
867 are used in this example.
870 .. _File_Name_Krunching_with_gnatkr:
872 File Name Krunching with ``gnatkr``
873 -----------------------------------
875 .. index:: ! gnatkr
877 This section discusses the method used by the compiler to shorten
878 the default file names chosen for Ada units so that they do not
879 exceed the maximum length permitted. It also describes the
880 ``gnatkr`` utility that can be used to determine the result of
881 applying this shortening.
883 .. _About_gnatkr:
885 About ``gnatkr``
886 ^^^^^^^^^^^^^^^^
888 The default file naming rule in GNAT
889 is that the file name must be derived from
890 the unit name. The exact default rule is as follows:
892 * Take the unit name and replace all dots by hyphens.
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.
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.
907 The :switch:`-gnatk{nn}`
908 switch of the compiler activates a 'krunching'
909 circuit that limits file names to nn characters (where nn is a decimal
910 integer).
912 The ``gnatkr`` utility can be used to determine the krunched name for
913 a given file, when krunched to a specified maximum length.
915 .. _Using_gnatkr:
917 Using ``gnatkr``
918 ^^^^^^^^^^^^^^^^
920 The ``gnatkr`` command has the form:
922 .. code-block:: sh
924       $ gnatkr name [ length ]
926 ``name`` is the uncrunched file name, derived from the name of the unit
927 in the standard manner described in the previous section (i.e., in particular
928 all dots are replaced by hyphens). The file name may or may not have an
929 extension (defined as a suffix of the form period followed by arbitrary
930 characters other than period). If an extension is present then it will
931 be preserved in the output. For example, when krunching :file:`hellofile.ads`
932 to eight characters, the result will be hellofil.ads.
934 Note: for compatibility with previous versions of ``gnatkr`` dots may
935 appear in the name instead of hyphens, but the last dot will always be
936 taken as the start of an extension. So if ``gnatkr`` is given an argument
937 such as :file:`Hello.World.adb` it will be treated exactly as if the first
938 period had been a hyphen, and for example krunching to eight characters
939 gives the result :file:`hellworl.adb`.
941 Note that the result is always all lower case.
942 Characters of the other case are folded as required.
944 ``length`` represents the length of the krunched name. The default
945 when no argument is given is 8 characters. A length of zero stands for
946 unlimited, in other words do not chop except for system files where the
947 implied crunching length is always eight characters.
949 The output is the krunched name. The output has an extension only if the
950 original argument was a file name with an extension.
952 .. _Krunching_Method:
954 Krunching Method
955 ^^^^^^^^^^^^^^^^
957 The initial file name is determined by the name of the unit that the file
958 contains. The name is formed by taking the full expanded name of the
959 unit and replacing the separating dots with hyphens and
960 using lowercase
961 for all letters, except that a hyphen in the second character position is
962 replaced by a tilde if the first character is
963 :samp:`a`, :samp:`i`, :samp:`g`, or :samp:`s`.
964 The extension is ``.ads`` for a
965 spec and ``.adb`` for a body.
966 Krunching does not affect the extension, but the file name is shortened to
967 the specified length by following these rules:
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.
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.
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::
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
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:
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   ===================== ==============
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.
1012   As an example of this special rule, consider
1013   :file:`ada-strings-wide_fixed.adb`, which gets krunched as follows::
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
1029 Of course no file shortening algorithm can guarantee uniqueness over all
1030 possible unit names, and if file name krunching is used then it is your
1031 responsibility to ensure that no name clashes occur. The utility
1032 program ``gnatkr`` is supplied for conveniently determining the
1033 krunched name of a file.
1035 .. _Examples_of_gnatkr_Usage:
1037 Examples of ``gnatkr`` Usage
1038 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
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
1050 .. _Renaming_Files_with_gnatchop:
1052 Renaming Files with ``gnatchop``
1053 --------------------------------
1055 .. index:: ! gnatchop
1057 This section discusses how to handle files with multiple units by using
1058 the ``gnatchop`` utility. This utility is also useful in renaming
1059 files to meet the standard GNAT default file naming conventions.
1061 .. _Handling_Files_with_Multiple_Units:
1063 Handling Files with Multiple Units
1064 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1066 The basic compilation model of GNAT requires that a file submitted to the
1067 compiler have only one unit and there be a strict correspondence
1068 between the file name and the unit name.
1070 The ``gnatchop`` utility allows both of these rules to be relaxed,
1071 allowing GNAT to process files which contain multiple compilation units
1072 and files with arbitrary file names. ``gnatchop``
1073 reads the specified file and generates one or more output files,
1074 containing one unit per file. The unit and the file name correspond,
1075 as required by GNAT.
1077 If you want to permanently restructure a set of 'foreign' files so that
1078 they match the GNAT rules, and do the remaining development using the
1079 GNAT structure, you can simply use ``gnatchop`` once, generate the
1080 new set of files and work with them from that point on.
1082 Alternatively, if you want to keep your files in the 'foreign' format,
1083 perhaps to maintain compatibility with some other Ada compilation
1084 system, you can set up a procedure where you use ``gnatchop`` each
1085 time you compile, regarding the source files that it writes as temporary
1086 files that you throw away.
1088 Note that if your file containing multiple units starts with a byte order
1089 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
1090 will each start with a copy of this BOM, meaning that they can be compiled
1091 automatically in UTF-8 mode without needing to specify an explicit encoding.
1093 .. _Operating_gnatchop_in_Compilation_Mode:
1095 Operating gnatchop in Compilation Mode
1096 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1098 The basic function of ``gnatchop`` is to take a file with multiple units
1099 and split it into separate files. The boundary between files is reasonably
1100 clear, except for the issue of comments and pragmas. In default mode, the
1101 rule is that any pragmas between units belong to the previous unit, except
1102 that configuration pragmas always belong to the following unit. Any comments
1103 belong to the following unit. These rules
1104 almost always result in the right choice of
1105 the split point without needing to mark it explicitly and most users will
1106 find this default to be what they want. In this default mode it is incorrect to
1107 submit a file containing only configuration pragmas, or one that ends in
1108 configuration pragmas, to ``gnatchop``.
1110 However, using a special option to activate 'compilation mode',
1111 ``gnatchop``
1112 can perform another function, which is to provide exactly the semantics
1113 required by the RM for handling of configuration pragmas in a compilation.
1114 In the absence of configuration pragmas (at the main file level), this
1115 option has no effect, but it causes such configuration pragmas to be handled
1116 in a quite different manner.
1118 First, in compilation mode, if ``gnatchop`` is given a file that consists of
1119 only configuration pragmas, then this file is appended to the
1120 :file:`gnat.adc` file in the current directory. This behavior provides
1121 the required behavior described in the RM for the actions to be taken
1122 on submitting such a file to the compiler, namely that these pragmas
1123 should apply to all subsequent compilations in the same compilation
1124 environment. Using GNAT, the current directory, possibly containing a
1125 :file:`gnat.adc` file is the representation
1126 of a compilation environment. For more information on the
1127 :file:`gnat.adc` file, see :ref:`Handling_of_Configuration_Pragmas`.
1129 Second, in compilation mode, if ``gnatchop``
1130 is given a file that starts with
1131 configuration pragmas, and contains one or more units, then these
1132 configuration pragmas are prepended to each of the chopped files. This
1133 behavior provides the required behavior described in the RM for the
1134 actions to be taken on compiling such a file, namely that the pragmas
1135 apply to all units in the compilation, but not to subsequently compiled
1136 units.
1138 Finally, if configuration pragmas appear between units, they are appended
1139 to the previous unit. This results in the previous unit being illegal,
1140 since the compiler does not accept configuration pragmas that follow
1141 a unit. This provides the required RM behavior that forbids configuration
1142 pragmas other than those preceding the first compilation unit of a
1143 compilation.
1145 For most purposes, ``gnatchop`` will be used in default mode. The
1146 compilation mode described above is used only if you need exactly
1147 accurate behavior with respect to compilations, and you have files
1148 that contain multiple units and configuration pragmas. In this
1149 circumstance the use of ``gnatchop`` with the compilation mode
1150 switch provides the required behavior, and is for example the mode
1151 in which GNAT processes the ACVC tests.
1154 .. _Command_Line_for_gnatchop:
1156 Command Line for ``gnatchop``
1157 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1159 The ``gnatchop`` command has the form:
1161 .. code-block:: sh
1163      $ gnatchop switches file_name [file_name ...]
1164            [directory]
1166 The only required argument is the file name of the file to be chopped.
1167 There are no restrictions on the form of this file name. The file itself
1168 contains one or more Ada units, in normal GNAT format, concatenated
1169 together. As shown, more than one file may be presented to be chopped.
1171 When run in default mode, ``gnatchop`` generates one output file in
1172 the current directory for each unit in each of the files.
1174 ``directory``, if specified, gives the name of the directory to which
1175 the output files will be written. If it is not specified, all files are
1176 written to the current directory.
1178 For example, given a
1179 file called :file:`hellofiles` containing
1181 .. code-block:: ada
1183      procedure Hello;
1185      with Ada.Text_IO; use Ada.Text_IO;
1186      procedure Hello is
1187      begin
1188         Put_Line ("Hello");
1189      end Hello;
1191 the command
1193 .. code-block:: sh
1195      $ gnatchop hellofiles
1197 generates two files in the current directory, one called
1198 :file:`hello.ads` containing the single line that is the procedure spec,
1199 and the other called :file:`hello.adb` containing the remaining text. The
1200 original file is not affected. The generated files can be compiled in
1201 the normal manner.
1203 When gnatchop is invoked on a file that is empty or that contains only empty
1204 lines and/or comments, gnatchop will not fail, but will not produce any
1205 new sources.
1207 For example, given a
1208 file called :file:`toto.txt` containing
1210 .. code-block:: ada
1212      --  Just a comment
1214 the command
1216 .. code-block:: sh
1218      $ gnatchop toto.txt
1220 will not produce any new file and will result in the following warnings::
1222      toto.txt:1:01: warning: empty file, contains no compilation units
1223      no compilation units found
1224      no source files written
1227 .. _Switches_for_gnatchop:
1229 Switches for ``gnatchop``
1230 ^^^^^^^^^^^^^^^^^^^^^^^^^
1232 ``gnatchop`` recognizes the following switches:
1235 .. index:: --version (gnatchop)
1237 :switch:`--version`
1238   Display Copyright and version, then exit disregarding all other options.
1240 .. index:: --help (gnatchop)
1242 :switch:`--help`
1243   If :switch:`--version` was not used, display usage, then exit disregarding
1244   all other options.
1246 .. index:: -c (gnatchop)
1248 :switch:`-c`
1249   Causes ``gnatchop`` to operate in compilation mode, in which
1250   configuration pragmas are handled according to strict RM rules. See
1251   previous section for a full description of this mode.
1253 :switch:`-gnat{xxx}`
1254   This passes the given :switch:`-gnat{xxx}` switch to ``gnat`` which is
1255   used to parse the given file. Not all *xxx* options make sense,
1256   but for example, the use of :switch:`-gnati2` allows ``gnatchop`` to
1257   process a source file that uses Latin-2 coding for identifiers.
1259 :switch:`-h`
1260   Causes ``gnatchop`` to generate a brief help summary to the standard
1261   output file showing usage information.
1263 .. index:: -k (gnatchop)
1265 :switch:`-k{mm}`
1266   Limit generated file names to the specified number ``mm``
1267   of characters.
1268   This is useful if the
1269   resulting set of files is required to be interoperable with systems
1270   which limit the length of file names.
1271   No space is allowed between the :switch:`-k` and the numeric value. The numeric
1272   value may be omitted in which case a default of :switch:`-k8`,
1273   suitable for use
1274   with DOS-like file systems, is used. If no :switch:`-k` switch
1275   is present then
1276   there is no limit on the length of file names.
1278 .. index:: -p (gnatchop)
1280 :switch:`-p`
1281   Causes the file modification time stamp of the input file to be
1282   preserved and used for the time stamp of the output file(s). This may be
1283   useful for preserving coherency of time stamps in an environment where
1284   ``gnatchop`` is used as part of a standard build process.
1286 .. index:: -q (gnatchop)
1288 :switch:`-q`
1289   Causes output of informational messages indicating the set of generated
1290   files to be suppressed. Warnings and error messages are unaffected.
1292 .. index:: -r (gnatchop)
1293 .. index:: Source_Reference pragmas
1295 :switch:`-r`
1296   Generate ``Source_Reference`` pragmas. Use this switch if the output
1297   files are regarded as temporary and development is to be done in terms
1298   of the original unchopped file. This switch causes
1299   ``Source_Reference`` pragmas to be inserted into each of the
1300   generated files to refers back to the original file name and line number.
1301   The result is that all error messages refer back to the original
1302   unchopped file.
1303   In addition, the debugging information placed into the object file (when
1304   the :switch:`-g` switch of ``gcc`` or ``gnatmake`` is
1305   specified)
1306   also refers back to this original file so that tools like profilers and
1307   debuggers will give information in terms of the original unchopped file.
1309   If the original file to be chopped itself contains
1310   a ``Source_Reference``
1311   pragma referencing a third file, then gnatchop respects
1312   this pragma, and the generated ``Source_Reference`` pragmas
1313   in the chopped file refer to the original file, with appropriate
1314   line numbers. This is particularly useful when ``gnatchop``
1315   is used in conjunction with ``gnatprep`` to compile files that
1316   contain preprocessing statements and multiple units.
1318 .. index:: -v (gnatchop)
1320 :switch:`-v`
1321   Causes ``gnatchop`` to operate in verbose mode. The version
1322   number and copyright notice are output, as well as exact copies of
1323   the gnat1 commands spawned to obtain the chop control information.
1325 .. index:: -w (gnatchop)
1327 :switch:`-w`
1328   Overwrite existing file names. Normally ``gnatchop`` regards it as a
1329   fatal error if there is already a file with the same name as a
1330   file it would otherwise output, in other words if the files to be
1331   chopped contain duplicated units. This switch bypasses this
1332   check, and causes all but the last instance of such duplicated
1333   units to be skipped.
1335 .. index:: --GCC= (gnatchop)
1337 :switch:`--GCC={xxxx}`
1338   Specify the path of the GNAT parser to be used. When this switch is used,
1339   no attempt is made to add the prefix to the GNAT parser executable.
1342 .. _Examples_of_gnatchop_Usage:
1344 Examples of ``gnatchop`` Usage
1345 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1347 .. code-block:: sh
1349       $ gnatchop -w hello_s.ada prerelease/files
1351 Chops the source file :file:`hello_s.ada`. The output files will be
1352 placed in the directory :file:`prerelease/files`,
1353 overwriting any
1354 files with matching names in that directory (no files in the current
1355 directory are modified).
1357 .. code-block:: sh
1359       $ gnatchop archive
1361 Chops the source file :file:`archive`
1362 into the current directory. One
1363 useful application of ``gnatchop`` is in sending sets of sources
1364 around, for example in email messages. The required sources are simply
1365 concatenated (for example, using a Unix ``cat``
1366 command), and then
1367 ``gnatchop`` is used at the other end to reconstitute the original
1368 file names.
1370 .. code-block:: sh
1372       $ gnatchop file1 file2 file3 direc
1374 Chops all units in files :file:`file1`, :file:`file2`, :file:`file3`, placing
1375 the resulting files in the directory :file:`direc`. Note that if any units
1376 occur more than once anywhere within this set of files, an error message
1377 is generated, and no files are written. To override this check, use the
1378 :switch:`-w` switch,
1379 in which case the last occurrence in the last file will
1380 be the one that is output, and earlier duplicate occurrences for a given
1381 unit will be skipped.
1383 .. _Configuration_Pragmas:
1385 Configuration Pragmas
1386 =====================
1388 .. index:: Configuration pragmas
1390 .. index:: Pragmas, configuration
1392 Configuration pragmas include those pragmas described as
1393 such in the Ada Reference Manual, as well as
1394 implementation-dependent pragmas that are configuration pragmas.
1395 See the ``Implementation_Defined_Pragmas`` chapter in the
1396 :title:`GNAT_Reference_Manual` for details on these
1397 additional GNAT-specific configuration pragmas.
1398 Most notably, the pragma ``Source_File_Name``, which allows
1399 specifying non-default names for source files, is a configuration
1400 pragma. The following is a complete list of configuration pragmas
1401 recognized by GNAT::
1403      Ada_83
1404      Ada_95
1405      Ada_05
1406      Ada_2005
1407      Ada_12
1408      Ada_2012
1409      Allow_Integer_Address
1410      Annotate
1411      Assertion_Policy
1412      Assume_No_Invalid_Values
1413      C_Pass_By_Copy
1414      Check_Float_Overflow
1415      Check_Name
1416      Check_Policy
1417      Compile_Time_Error
1418      Compile_Time_Warning
1419      Compiler_Unit
1420      Compiler_Unit_Warning
1421      Component_Alignment
1422      Convention_Identifier
1423      Debug_Policy
1424      Detect_Blocking
1425      Default_Scalar_Storage_Order
1426      Default_Storage_Pool
1427      Disable_Atomic_Synchronization
1428      Discard_Names
1429      Elaboration_Checks
1430      Eliminate
1431      Enable_Atomic_Synchronization
1432      Extend_System
1433      Extensions_Allowed
1434      External_Name_Casing
1435      Fast_Math
1436      Favor_Top_Level
1437      Ignore_Pragma
1438      Implicit_Packing
1439      Initialize_Scalars
1440      Interrupt_State
1441      License
1442      Locking_Policy
1443      No_Component_Reordering
1444      No_Heap_Finalization
1445      No_Run_Time
1446      No_Strict_Aliasing
1447      Normalize_Scalars
1448      Optimize_Alignment
1449      Overflow_Mode
1450      Overriding_Renamings
1451      Partition_Elaboration_Policy
1452      Persistent_BSS
1453      Polling
1454      Prefix_Exception_Messages
1455      Priority_Specific_Dispatching
1456      Profile
1457      Profile_Warnings
1458      Propagate_Exceptions
1459      Queuing_Policy
1460      Rational
1461      Ravenscar
1462      Rename_Pragma
1463      Restricted_Run_Time
1464      Restrictions
1465      Restrictions_Warnings
1466      Reviewable
1467      Short_Circuit_And_Or
1468      Short_Descriptors
1469      Source_File_Name
1470      Source_File_Name_Project
1471      SPARK_Mode
1472      Style_Checks
1473      Suppress
1474      Suppress_Exception_Locations
1475      Task_Dispatching_Policy
1476      Unevaluated_Use_Of_Old
1477      Universal_Data
1478      Unsuppress
1479      Use_VADS_Size
1480      Validity_Checks
1481      Warning_As_Error
1482      Warnings
1483      Wide_Character_Encoding
1486 .. _Handling_of_Configuration_Pragmas:
1488 Handling of Configuration Pragmas
1489 ---------------------------------
1491 Configuration pragmas may either appear at the start of a compilation
1492 unit, or they can appear in a configuration pragma file to apply to
1493 all compilations performed in a given compilation environment.
1495 GNAT also provides the ``gnatchop`` utility to provide an automatic
1496 way to handle configuration pragmas following the semantics for
1497 compilations (that is, files with multiple units), described in the RM.
1498 See :ref:`Operating_gnatchop_in_Compilation_Mode` for details.
1499 However, for most purposes, it will be more convenient to edit the
1500 :file:`gnat.adc` file that contains configuration pragmas directly,
1501 as described in the following section.
1503 In the case of ``Restrictions`` pragmas appearing as configuration
1504 pragmas in individual compilation units, the exact handling depends on
1505 the type of restriction.
1507 Restrictions that require partition-wide consistency (like
1508 ``No_Tasking``) are
1509 recognized wherever they appear
1510 and can be freely inherited, e.g. from a |withed| unit to the |withing|
1511 unit. This makes sense since the binder will in any case insist on seeing
1512 consistent use, so any unit not conforming to any restrictions that are
1513 anywhere in the partition will be rejected, and you might as well find
1514 that out at compile time rather than at bind time.
1516 For restrictions that do not require partition-wide consistency, e.g.
1517 SPARK or No_Implementation_Attributes, in general the restriction applies
1518 only to the unit in which the pragma appears, and not to any other units.
1520 The exception is No_Elaboration_Code which always applies to the entire
1521 object file from a compilation, i.e. to the body, spec, and all subunits.
1522 This restriction can be specified in a configuration pragma file, or it
1523 can be on the body and/or the spec (in eithe case it applies to all the
1524 relevant units). It can appear on a subunit only if it has previously
1525 appeared in the body of spec.
1528 .. _The_Configuration_Pragmas_Files:
1530 The Configuration Pragmas Files
1531 -------------------------------
1533 .. index:: gnat.adc
1535 In GNAT a compilation environment is defined by the current
1536 directory at the time that a compile command is given. This current
1537 directory is searched for a file whose name is :file:`gnat.adc`. If
1538 this file is present, it is expected to contain one or more
1539 configuration pragmas that will be applied to the current compilation.
1540 However, if the switch :switch:`-gnatA` is used, :file:`gnat.adc` is not
1541 considered. When taken into account, :file:`gnat.adc` is added to the
1542 dependencies, so that if :file:`gnat.adc` is modified later, an invocation of
1543 ``gnatmake`` will recompile the source.
1545 Configuration pragmas may be entered into the :file:`gnat.adc` file
1546 either by running ``gnatchop`` on a source file that consists only of
1547 configuration pragmas, or more conveniently by direct editing of the
1548 :file:`gnat.adc` file, which is a standard format source file.
1550 Besides :file:`gnat.adc`, additional files containing configuration
1551 pragmas may be applied to the current compilation using the switch
1552 :switch:`-gnatec={path}` where ``path`` must designate an existing file that
1553 contains only configuration pragmas. These configuration pragmas are
1554 in addition to those found in :file:`gnat.adc` (provided :file:`gnat.adc`
1555 is present and switch :switch:`-gnatA` is not used).
1557 It is allowable to specify several switches :switch:`-gnatec=`, all of which
1558 will be taken into account.
1560 Files containing configuration pragmas specified with switches
1561 :switch:`-gnatec=` are added to the dependencies, unless they are
1562 temporary files. A file is considered temporary if its name ends in
1563 :file:`.tmp` or :file:`.TMP`. Certain tools follow this naming
1564 convention because they pass information to ``gcc`` via
1565 temporary files that are immediately deleted; it doesn't make sense to
1566 depend on a file that no longer exists. Such tools include
1567 ``gprbuild``, ``gnatmake``, and ``gnatcheck``.
1569 If you are using project file, a separate mechanism is provided using
1570 project attributes.
1572 .. --Comment
1573    See :ref:`Specifying_Configuration_Pragmas` for more details.
1576 .. _Generating_Object_Files:
1578 Generating Object Files
1579 =======================
1581 An Ada program consists of a set of source files, and the first step in
1582 compiling the program is to generate the corresponding object files.
1583 These are generated by compiling a subset of these source files.
1584 The files you need to compile are the following:
1586 * If a package spec has no body, compile the package spec to produce the
1587   object file for the package.
1589 * If a package has both a spec and a body, compile the body to produce the
1590   object file for the package. The source file for the package spec need
1591   not be compiled in this case because there is only one object file, which
1592   contains the code for both the spec and body of the package.
1594 * For a subprogram, compile the subprogram body to produce the object file
1595   for the subprogram. The spec, if one is present, is as usual in a
1596   separate file, and need not be compiled.
1598 .. index:: Subunits
1600 * In the case of subunits, only compile the parent unit. A single object
1601   file is generated for the entire subunit tree, which includes all the
1602   subunits.
1604 * Compile child units independently of their parent units
1605   (though, of course, the spec of all the ancestor unit must be present in order
1606   to compile a child unit).
1608   .. index:: Generics
1610 * Compile generic units in the same manner as any other units. The object
1611   files in this case are small dummy files that contain at most the
1612   flag used for elaboration checking. This is because GNAT always handles generic
1613   instantiation by means of macro expansion. However, it is still necessary to
1614   compile generic units, for dependency checking and elaboration purposes.
1616 The preceding rules describe the set of files that must be compiled to
1617 generate the object files for a program. Each object file has the same
1618 name as the corresponding source file, except that the extension is
1619 :file:`.o` as usual.
1621 You may wish to compile other files for the purpose of checking their
1622 syntactic and semantic correctness. For example, in the case where a
1623 package has a separate spec and body, you would not normally compile the
1624 spec. However, it is convenient in practice to compile the spec to make
1625 sure it is error-free before compiling clients of this spec, because such
1626 compilations will fail if there is an error in the spec.
1628 GNAT provides an option for compiling such files purely for the
1629 purposes of checking correctness; such compilations are not required as
1630 part of the process of building a program. To compile a file in this
1631 checking mode, use the :switch:`-gnatc` switch.
1633 .. _Source_Dependencies:
1635 Source Dependencies
1636 ===================
1638 A given object file clearly depends on the source file which is compiled
1639 to produce it. Here we are using "depends" in the sense of a typical
1640 ``make`` utility; in other words, an object file depends on a source
1641 file if changes to the source file require the object file to be
1642 recompiled.
1643 In addition to this basic dependency, a given object may depend on
1644 additional source files as follows:
1646 * If a file being compiled |withs| a unit ``X``, the object file
1647   depends on the file containing the spec of unit ``X``. This includes
1648   files that are |withed| implicitly either because they are parents
1649   of |withed| child units or they are run-time units required by the
1650   language constructs used in a particular unit.
1652 * If a file being compiled instantiates a library level generic unit, the
1653   object file depends on both the spec and body files for this generic
1654   unit.
1656 * If a file being compiled instantiates a generic unit defined within a
1657   package, the object file depends on the body file for the package as
1658   well as the spec file.
1660 .. index:: Inline
1661 .. index:: -gnatn switch
1663 * If a file being compiled contains a call to a subprogram for which
1664   pragma ``Inline`` applies and inlining is activated with the
1665   :switch:`-gnatn` switch, the object file depends on the file containing the
1666   body of this subprogram as well as on the file containing the spec. Note
1667   that for inlining to actually occur as a result of the use of this switch,
1668   it is necessary to compile in optimizing mode.
1670   .. index:: -gnatN switch
1672   The use of :switch:`-gnatN` activates  inlining optimization
1673   that is performed by the front end of the compiler. This inlining does
1674   not require that the code generation be optimized. Like :switch:`-gnatn`,
1675   the use of this switch generates additional dependencies.
1677   When using a gcc-based back end (in practice this means using any version
1678   of GNAT other than for the JVM, .NET or GNAAMP platforms), then the use of
1679   :switch:`-gnatN` is deprecated, and the use of :switch:`-gnatn` is preferred.
1680   Historically front end inlining was more extensive than the gcc back end
1681   inlining, but that is no longer the case.
1683 * If an object file :file:`O` depends on the proper body of a subunit through
1684   inlining or instantiation, it depends on the parent unit of the subunit.
1685   This means that any modification of the parent unit or one of its subunits
1686   affects the compilation of :file:`O`.
1688 * The object file for a parent unit depends on all its subunit body files.
1690 * The previous two rules meant that for purposes of computing dependencies and
1691   recompilation, a body and all its subunits are treated as an indivisible whole.
1693   These rules are applied transitively: if unit ``A`` |withs|
1694   unit ``B``, whose elaboration calls an inlined procedure in package
1695   ``C``, the object file for unit ``A`` will depend on the body of
1696   ``C``, in file :file:`c.adb`.
1698   The set of dependent files described by these rules includes all the
1699   files on which the unit is semantically dependent, as dictated by the
1700   Ada language standard. However, it is a superset of what the
1701   standard describes, because it includes generic, inline, and subunit
1702   dependencies.
1704   An object file must be recreated by recompiling the corresponding source
1705   file if any of the source files on which it depends are modified. For
1706   example, if the ``make`` utility is used to control compilation,
1707   the rule for an Ada object file must mention all the source files on
1708   which the object file depends, according to the above definition.
1709   The determination of the necessary
1710   recompilations is done automatically when one uses ``gnatmake``.
1712 .. _The_Ada_Library_Information_Files:
1714 The Ada Library Information Files
1715 =================================
1717 .. index:: Ada Library Information files
1719 .. index:: ALI files
1721 Each compilation actually generates two output files. The first of these
1722 is the normal object file that has a :file:`.o` extension. The second is a
1723 text file containing full dependency information. It has the same
1724 name as the source file, but an :file:`.ali` extension.
1725 This file is known as the Ada Library Information (:file:`ALI`) file.
1726 The following information is contained in the :file:`ALI` file.
1728 * Version information (indicates which version of GNAT was used to compile
1729   the unit(s) in question)
1731 * Main program information (including priority and time slice settings,
1732   as well as the wide character encoding used during compilation).
1734 * List of arguments used in the ``gcc`` command for the compilation
1736 * Attributes of the unit, including configuration pragmas used, an indication
1737   of whether the compilation was successful, exception model used etc.
1739 * A list of relevant restrictions applying to the unit (used for consistency)
1740   checking.
1742 * Categorization information (e.g., use of pragma ``Pure``).
1744 * Information on all |withed| units, including presence of
1745   ``Elaborate`` or ``Elaborate_All`` pragmas.
1747 * Information from any ``Linker_Options`` pragmas used in the unit
1749 * Information on the use of ``Body_Version`` or ``Version``
1750   attributes in the unit.
1752 * Dependency information. This is a list of files, together with
1753   time stamp and checksum information. These are files on which
1754   the unit depends in the sense that recompilation is required
1755   if any of these units are modified.
1757 * Cross-reference data. Contains information on all entities referenced
1758   in the unit. Used by tools like ``gnatxref`` and ``gnatfind`` to
1759   provide cross-reference information.
1761 For a full detailed description of the format of the :file:`ALI` file,
1762 see the source of the body of unit ``Lib.Writ``, contained in file
1763 :file:`lib-writ.adb` in the GNAT compiler sources.
1766 .. _Binding_an_Ada_Program:
1768 Binding an Ada Program
1769 ======================
1771 When using languages such as C and C++, once the source files have been
1772 compiled the only remaining step in building an executable program
1773 is linking the object modules together. This means that it is possible to
1774 link an inconsistent version of a program, in which two units have
1775 included different versions of the same header.
1777 The rules of Ada do not permit such an inconsistent program to be built.
1778 For example, if two clients have different versions of the same package,
1779 it is illegal to build a program containing these two clients.
1780 These rules are enforced by the GNAT binder, which also determines an
1781 elaboration order consistent with the Ada rules.
1783 The GNAT binder is run after all the object files for a program have
1784 been created. It is given the name of the main program unit, and from
1785 this it determines the set of units required by the program, by reading the
1786 corresponding ALI files. It generates error messages if the program is
1787 inconsistent or if no valid order of elaboration exists.
1789 If no errors are detected, the binder produces a main program, in Ada by
1790 default, that contains calls to the elaboration procedures of those
1791 compilation unit that require them, followed by
1792 a call to the main program. This Ada program is compiled to generate the
1793 object file for the main program. The name of
1794 the Ada file is :file:`b~xxx`.adb` (with the corresponding spec
1795 :file:`b~xxx`.ads`) where ``xxx`` is the name of the
1796 main program unit.
1798 Finally, the linker is used to build the resulting executable program,
1799 using the object from the main program from the bind step as well as the
1800 object files for the Ada units of the program.
1803 .. _GNAT_and_Libraries:
1805 GNAT and Libraries
1806 ==================
1808 .. index:: Library building and using
1810 This section describes how to build and use libraries with GNAT, and also shows
1811 how to recompile the GNAT run-time library. You should be familiar with the
1812 Project Manager facility (see the *GNAT_Project_Manager* chapter of the
1813 *GPRbuild User's Guide*) before reading this chapter.
1815 .. _Introduction_to_Libraries_in_GNAT:
1817 Introduction to Libraries in GNAT
1818 ---------------------------------
1820 A library is, conceptually, a collection of objects which does not have its
1821 own main thread of execution, but rather provides certain services to the
1822 applications that use it. A library can be either statically linked with the
1823 application, in which case its code is directly included in the application,
1824 or, on platforms that support it, be dynamically linked, in which case
1825 its code is shared by all applications making use of this library.
1827 GNAT supports both types of libraries.
1828 In the static case, the compiled code can be provided in different ways. The
1829 simplest approach is to provide directly the set of objects resulting from
1830 compilation of the library source files. Alternatively, you can group the
1831 objects into an archive using whatever commands are provided by the operating
1832 system. For the latter case, the objects are grouped into a shared library.
1834 In the GNAT environment, a library has three types of components:
1836 *  Source files,
1838 *  :file:`ALI` files (see :ref:`The_Ada_Library_Information_Files`), and
1840 *  Object files, an archive or a shared library.
1842 A GNAT library may expose all its source files, which is useful for
1843 documentation purposes. Alternatively, it may expose only the units needed by
1844 an external user to make use of the library. That is to say, the specs
1845 reflecting the library services along with all the units needed to compile
1846 those specs, which can include generic bodies or any body implementing an
1847 inlined routine. In the case of *stand-alone libraries* those exposed
1848 units are called *interface units* (:ref:`Stand-alone_Ada_Libraries`).
1850 All compilation units comprising an application, including those in a library,
1851 need to be elaborated in an order partially defined by Ada's semantics. GNAT
1852 computes the elaboration order from the :file:`ALI` files and this is why they
1853 constitute a mandatory part of GNAT libraries.
1854 *Stand-alone libraries* are the exception to this rule because a specific
1855 library elaboration routine is produced independently of the application(s)
1856 using the library.
1858 .. _General_Ada_Libraries:
1860 General Ada Libraries
1861 ---------------------
1864 .. _Building_a_library:
1866 Building a library
1867 ^^^^^^^^^^^^^^^^^^
1869 The easiest way to build a library is to use the Project Manager,
1870 which supports a special type of project called a *Library Project*
1871 (see the *Library Projects* section in the *GNAT Project Manager*
1872 chapter of the *GPRbuild User's Guide*).
1874 A project is considered a library project, when two project-level attributes
1875 are defined in it: ``Library_Name`` and ``Library_Dir``. In order to
1876 control different aspects of library configuration, additional optional
1877 project-level attributes can be specified:
1879 * ``Library_Kind``
1880     This attribute controls whether the library is to be static or dynamic
1883 * ``Library_Version``
1884     This attribute specifies the library version; this value is used
1885     during dynamic linking of shared libraries to determine if the currently
1886     installed versions of the binaries are compatible.
1888 * ``Library_Options``
1890 * ``Library_GCC``
1891     These attributes specify additional low-level options to be used during
1892     library generation, and redefine the actual application used to generate
1893     library.
1895 The GNAT Project Manager takes full care of the library maintenance task,
1896 including recompilation of the source files for which objects do not exist
1897 or are not up to date, assembly of the library archive, and installation of
1898 the library (i.e., copying associated source, object and :file:`ALI` files
1899 to the specified location).
1901 Here is a simple library project file:
1903 .. code-block:: gpr
1905        project My_Lib is
1906          for Source_Dirs use ("src1", "src2");
1907          for Object_Dir use "obj";
1908          for Library_Name use "mylib";
1909          for Library_Dir use "lib";
1910          for Library_Kind use "dynamic";
1911        end My_lib;
1913 and the compilation command to build and install the library:
1915 .. code-block:: sh
1917      $ gnatmake -Pmy_lib
1919 It is not entirely trivial to perform manually all the steps required to
1920 produce a library. We recommend that you use the GNAT Project Manager
1921 for this task. In special cases where this is not desired, the necessary
1922 steps are discussed below.
1924 There are various possibilities for compiling the units that make up the
1925 library: for example with a Makefile (:ref:`Using_the_GNU_make_Utility`) or
1926 with a conventional script. For simple libraries, it is also possible to create
1927 a dummy main program which depends upon all the packages that comprise the
1928 interface of the library. This dummy main program can then be given to
1929 ``gnatmake``, which will ensure that all necessary objects are built.
1931 After this task is accomplished, you should follow the standard procedure
1932 of the underlying operating system to produce the static or shared library.
1934 Here is an example of such a dummy program:
1936 .. code-block:: ada
1938        with My_Lib.Service1;
1939        with My_Lib.Service2;
1940        with My_Lib.Service3;
1941        procedure My_Lib_Dummy is
1942        begin
1943           null;
1944        end;
1946 Here are the generic commands that will build an archive or a shared library.
1948 .. code-block:: sh
1950      # compiling the library
1951      $ gnatmake -c my_lib_dummy.adb
1953      # we don't need the dummy object itself
1954      $ rm my_lib_dummy.o my_lib_dummy.ali
1956      # create an archive with the remaining objects
1957      $ ar rc libmy_lib.a *.o
1958      # some systems may require "ranlib" to be run as well
1960      # or create a shared library
1961      $ gcc -shared -o libmy_lib.so *.o
1962      # some systems may require the code to have been compiled with -fPIC
1964      # remove the object files that are now in the library
1965      $ rm *.o
1967      # Make the ALI files read-only so that gnatmake will not try to
1968      # regenerate the objects that are in the library
1969      $ chmod -w *.ali
1971 Please note that the library must have a name of the form :file:`lib{xxx}.a`
1972 or :file:`lib{xxx}.so` (or :file:`lib{xxx}.dll` on Windows) in order to
1973 be accessed by the directive :switch:`-l{xxx}` at link time.
1975 .. _Installing_a_library:
1977 Installing a library
1978 ^^^^^^^^^^^^^^^^^^^^
1980 .. index:: ADA_PROJECT_PATH
1981 .. index:: GPR_PROJECT_PATH
1983 If you use project files, library installation is part of the library build
1984 process (see the *Installing a Library with Project Files* section of the
1985 *GNAT Project Manager* chapter of the *GPRbuild User's Guide*).
1987 When project files are not an option, it is also possible, but not recommended,
1988 to install the library so that the sources needed to use the library are on the
1989 Ada source path and the ALI files & libraries be on the Ada Object path (see
1990 :ref:`Search_Paths_and_the_Run-Time_Library_RTL`. Alternatively, the system
1991 administrator can place general-purpose libraries in the default compiler
1992 paths, by specifying the libraries' location in the configuration files
1993 :file:`ada_source_path` and :file:`ada_object_path`. These configuration files
1994 must be located in the GNAT installation tree at the same place as the gcc spec
1995 file. The location of the gcc spec file can be determined as follows:
1997 .. code-block:: sh
1999      $ gcc -v
2002 The configuration files mentioned above have a simple format: each line
2003 must contain one unique directory name.
2004 Those names are added to the corresponding path
2005 in their order of appearance in the file. The names can be either absolute
2006 or relative; in the latter case, they are relative to where theses files
2007 are located.
2009 The files :file:`ada_source_path` and :file:`ada_object_path` might not be
2010 present in a
2011 GNAT installation, in which case, GNAT will look for its run-time library in
2012 the directories :file:`adainclude` (for the sources) and :file:`adalib` (for the
2013 objects and :file:`ALI` files). When the files exist, the compiler does not
2014 look in :file:`adainclude` and :file:`adalib`, and thus the
2015 :file:`ada_source_path` file
2016 must contain the location for the GNAT run-time sources (which can simply
2017 be :file:`adainclude`). In the same way, the :file:`ada_object_path` file must
2018 contain the location for the GNAT run-time objects (which can simply
2019 be :file:`adalib`).
2021 You can also specify a new default path to the run-time library at compilation
2022 time with the switch :switch:`--RTS=rts-path`. You can thus choose / change
2023 the run-time library you want your program to be compiled with. This switch is
2024 recognized by ``gcc``, ``gnatmake``, ``gnatbind``,
2025 ``gnatls``, ``gnatfind`` and ``gnatxref``.
2027 It is possible to install a library before or after the standard GNAT
2028 library, by reordering the lines in the configuration files. In general, a
2029 library must be installed before the GNAT library if it redefines
2030 any part of it.
2032 .. _Using_a_library:
2034 Using a library
2035 ^^^^^^^^^^^^^^^
2037 Once again, the project facility greatly simplifies the use of
2038 libraries. In this context, using a library is just a matter of adding a
2039 |with| clause in the user project. For instance, to make use of the
2040 library ``My_Lib`` shown in examples in earlier sections, you can
2041 write:
2043 .. code-block:: gpr
2045        with "my_lib";
2046        project My_Proj is
2047          ...
2048        end My_Proj;
2050 Even if you have a third-party, non-Ada library, you can still use GNAT's
2051 Project Manager facility to provide a wrapper for it. For example, the
2052 following project, when |withed| by your main project, will link with the
2053 third-party library :file:`liba.a`:
2055 .. code-block:: gpr
2057        project Liba is
2058           for Externally_Built use "true";
2059           for Source_Files use ();
2060           for Library_Dir use "lib";
2061           for Library_Name use "a";
2062           for Library_Kind use "static";
2063        end Liba;
2065 This is an alternative to the use of ``pragma Linker_Options``. It is
2066 especially interesting in the context of systems with several interdependent
2067 static libraries where finding a proper linker order is not easy and best be
2068 left to the tools having visibility over project dependence information.
2070 In order to use an Ada library manually, you need to make sure that this
2071 library is on both your source and object path
2072 (see :ref:`Search_Paths_and_the_Run-Time_Library_RTL`
2073 and :ref:`Search_Paths_for_gnatbind`). Furthermore, when the objects are grouped
2074 in an archive or a shared library, you need to specify the desired
2075 library at link time.
2077 For example, you can use the library :file:`mylib` installed in
2078 :file:`/dir/my_lib_src` and :file:`/dir/my_lib_obj` with the following commands:
2080 .. code-block:: sh
2082      $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \\
2083        -largs -lmy_lib
2085 This can be expressed more simply:
2087 .. code-block:: sh
2089     $ gnatmake my_appl
2091 when the following conditions are met:
2093 * :file:`/dir/my_lib_src` has been added by the user to the environment
2094   variable :envvar:`ADA_INCLUDE_PATH`, or by the administrator to the file
2095   :file:`ada_source_path`
2097 * :file:`/dir/my_lib_obj` has been added by the user to the environment
2098   variable :envvar:`ADA_OBJECTS_PATH`, or by the administrator to the file
2099   :file:`ada_object_path`
2101 * a pragma ``Linker_Options`` has been added to one of the sources.
2102   For example:
2104   .. code-block:: ada
2106        pragma Linker_Options ("-lmy_lib");
2108 Note that you may also load a library dynamically at
2109 run time given its filename, as illustrated in the GNAT :file:`plugins` example
2110 in the directory :file:`share/examples/gnat/plugins` within the GNAT
2111 install area.
2113 .. _Stand-alone_Ada_Libraries:
2115 Stand-alone Ada Libraries
2116 -------------------------
2118 .. index:: ! Stand-alone libraries
2120 .. _Introduction_to_Stand-alone_Libraries:
2122 Introduction to Stand-alone Libraries
2123 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2125 A Stand-alone Library (abbreviated 'SAL') is a library that contains the
2126 necessary code to
2127 elaborate the Ada units that are included in the library. In contrast with
2128 an ordinary library, which consists of all sources, objects and :file:`ALI`
2129 files of the
2130 library, a SAL may specify a restricted subset of compilation units
2131 to serve as a library interface. In this case, the fully
2132 self-sufficient set of files will normally consist of an objects
2133 archive, the sources of interface units' specs, and the :file:`ALI`
2134 files of interface units.
2135 If an interface spec contains a generic unit or an inlined subprogram,
2136 the body's
2137 source must also be provided; if the units that must be provided in the source
2138 form depend on other units, the source and :file:`ALI` files of those must
2139 also be provided.
2141 The main purpose of a SAL is to minimize the recompilation overhead of client
2142 applications when a new version of the library is installed. Specifically,
2143 if the interface sources have not changed, client applications do not need to
2144 be recompiled. If, furthermore, a SAL is provided in the shared form and its
2145 version, controlled by ``Library_Version`` attribute, is not changed,
2146 then the clients do not need to be relinked.
2148 SALs also allow the library providers to minimize the amount of library source
2149 text exposed to the clients.  Such 'information hiding' might be useful or
2150 necessary for various reasons.
2152 Stand-alone libraries are also well suited to be used in an executable whose
2153 main routine is not written in Ada.
2155 .. _Building_a_Stand-alone_Library:
2157 Building a Stand-alone Library
2158 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2160 GNAT's Project facility provides a simple way of building and installing
2161 stand-alone libraries; see the *Stand-alone Library Projects* section
2162 in the *GNAT Project Manager* chapter of the *GPRbuild User's Guide*.
2163 To be a Stand-alone Library Project, in addition to the two attributes
2164 that make a project a Library Project (``Library_Name`` and
2165 ``Library_Dir``; see the *Library Projects* section in the
2166 *GNAT Project Manager* chapter of the *GPRbuild User's Guide*),
2167 the attribute ``Library_Interface`` must be defined.  For example:
2169 .. code-block:: gpr
2171        for Library_Dir use "lib_dir";
2172        for Library_Name use "dummy";
2173        for Library_Interface use ("int1", "int1.child");
2175 Attribute ``Library_Interface`` has a non-empty string list value,
2176 each string in the list designating a unit contained in an immediate source
2177 of the project file.
2179 When a Stand-alone Library is built, first the binder is invoked to build
2180 a package whose name depends on the library name
2181 (:file:`b~dummy.ads/b` in the example above).
2182 This binder-generated package includes initialization and
2183 finalization procedures whose
2184 names depend on the library name (``dummyinit`` and ``dummyfinal``
2185 in the example
2186 above). The object corresponding to this package is included in the library.
2188 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
2189 calling of these procedures if a static SAL is built, or if a shared SAL
2190 is built
2191 with the project-level attribute ``Library_Auto_Init`` set to
2192 ``"false"``.
2194 For a Stand-Alone Library, only the :file:`ALI` files of the Interface Units
2195 (those that are listed in attribute ``Library_Interface``) are copied to
2196 the Library Directory. As a consequence, only the Interface Units may be
2197 imported from Ada units outside of the library. If other units are imported,
2198 the binding phase will fail.
2200 It is also possible to build an encapsulated library where not only
2201 the code to elaborate and finalize the library is embedded but also
2202 ensuring that the library is linked only against static
2203 libraries. So an encapsulated library only depends on system
2204 libraries, all other code, including the GNAT runtime, is embedded. To
2205 build an encapsulated library the attribute
2206 ``Library_Standalone`` must be set to ``encapsulated``:
2208 .. code-block:: gpr
2210        for Library_Dir use "lib_dir";
2211        for Library_Name use "dummy";
2212        for Library_Kind use "dynamic";
2213        for Library_Interface use ("int1", "int1.child");
2214        for Library_Standalone use "encapsulated";
2216 The default value for this attribute is ``standard`` in which case
2217 a stand-alone library is built.
2219 The attribute ``Library_Src_Dir`` may be specified for a
2220 Stand-Alone Library. ``Library_Src_Dir`` is a simple attribute that has a
2221 single string value. Its value must be the path (absolute or relative to the
2222 project directory) of an existing directory. This directory cannot be the
2223 object directory or one of the source directories, but it can be the same as
2224 the library directory. The sources of the Interface
2225 Units of the library that are needed by an Ada client of the library will be
2226 copied to the designated directory, called the Interface Copy directory.
2227 These sources include the specs of the Interface Units, but they may also
2228 include bodies and subunits, when pragmas ``Inline`` or ``Inline_Always``
2229 are used, or when there is a generic unit in the spec. Before the sources
2230 are copied to the Interface Copy directory, an attempt is made to delete all
2231 files in the Interface Copy directory.
2233 Building stand-alone libraries by hand is somewhat tedious, but for those
2234 occasions when it is necessary here are the steps that you need to perform:
2236 * Compile all library sources.
2238 * Invoke the binder with the switch :switch:`-n` (No Ada main program),
2239   with all the :file:`ALI` files of the interfaces, and
2240   with the switch :switch:`-L` to give specific names to the ``init``
2241   and ``final`` procedures.  For example:
2243   .. code-block:: sh
2245       $ gnatbind -n int1.ali int2.ali -Lsal1
2247 * Compile the binder generated file:
2249   .. code-block:: sh
2251       $ gcc -c b~int2.adb
2253 * Link the dynamic library with all the necessary object files,
2254   indicating to the linker the names of the ``init`` (and possibly
2255   ``final``) procedures for automatic initialization (and finalization).
2256   The built library should be placed in a directory different from
2257   the object directory.
2259 * Copy the ``ALI`` files of the interface to the library directory,
2260   add in this copy an indication that it is an interface to a SAL
2261   (i.e., add a word ``SL`` on the line in the :file:`ALI` file that starts
2262   with letter 'P') and make the modified copy of the :file:`ALI` file
2263   read-only.
2265 Using SALs is not different from using other libraries
2266 (see :ref:`Using_a_library`).
2268 .. _Creating_a_Stand-alone_Library_to_be_used_in_a_non-Ada_context:
2270 Creating a Stand-alone Library to be used in a non-Ada context
2271 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2273 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
2274 a non-Ada context.
2276 The only extra step required is to ensure that library interface subprograms
2277 are compatible with the main program, by means of ``pragma Export``
2278 or ``pragma Convention``.
2280 Here is an example of simple library interface for use with C main program:
2282 .. code-block:: ada
2284        package My_Package is
2286           procedure Do_Something;
2287           pragma Export (C, Do_Something, "do_something");
2289           procedure Do_Something_Else;
2290           pragma Export (C, Do_Something_Else, "do_something_else");
2292        end My_Package;
2294 On the foreign language side, you must provide a 'foreign' view of the
2295 library interface; remember that it should contain elaboration routines in
2296 addition to interface subprograms.
2298 The example below shows the content of :file:`mylib_interface.h` (note
2299 that there is no rule for the naming of this file, any name can be used)
2301 .. code-block:: c
2303        /* the library elaboration procedure */
2304        extern void mylibinit (void);
2306        /* the library finalization procedure */
2307        extern void mylibfinal (void);
2309        /* the interface exported by the library */
2310        extern void do_something (void);
2311        extern void do_something_else (void);
2313 Libraries built as explained above can be used from any program, provided
2314 that the elaboration procedures (named ``mylibinit`` in the previous
2315 example) are called before the library services are used. Any number of
2316 libraries can be used simultaneously, as long as the elaboration
2317 procedure of each library is called.
2319 Below is an example of a C program that uses the ``mylib`` library.
2321 .. code-block:: c
2323        #include "mylib_interface.h"
2325        int
2326        main (void)
2327        {
2328           /* First, elaborate the library before using it */
2329           mylibinit ();
2331           /* Main program, using the library exported entities */
2332           do_something ();
2333           do_something_else ();
2335           /* Library finalization at the end of the program */
2336           mylibfinal ();
2337           return 0;
2338        }
2340 Note that invoking any library finalization procedure generated by
2341 ``gnatbind`` shuts down the Ada run-time environment.
2342 Consequently, the
2343 finalization of all Ada libraries must be performed at the end of the program.
2344 No call to these libraries or to the Ada run-time library should be made
2345 after the finalization phase.
2347 Note also that special care must be taken with multi-tasks
2348 applications. The initialization and finalization routines are not
2349 protected against concurrent access. If such requirement is needed it
2350 must be ensured at the application level using a specific operating
2351 system services like a mutex or a critical-section.
2353 .. _Restrictions_in_Stand-alone_Libraries:
2355 Restrictions in Stand-alone Libraries
2356 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2358 The pragmas listed below should be used with caution inside libraries,
2359 as they can create incompatibilities with other Ada libraries:
2361 * pragma ``Locking_Policy``
2362 * pragma ``Partition_Elaboration_Policy``
2363 * pragma ``Queuing_Policy``
2364 * pragma ``Task_Dispatching_Policy``
2365 * pragma ``Unreserve_All_Interrupts``
2367 When using a library that contains such pragmas, the user must make sure
2368 that all libraries use the same pragmas with the same values. Otherwise,
2369 ``Program_Error`` will
2370 be raised during the elaboration of the conflicting
2371 libraries. The usage of these pragmas and its consequences for the user
2372 should therefore be well documented.
2374 Similarly, the traceback in the exception occurrence mechanism should be
2375 enabled or disabled in a consistent manner across all libraries.
2376 Otherwise, Program_Error will be raised during the elaboration of the
2377 conflicting libraries.
2379 If the ``Version`` or ``Body_Version``
2380 attributes are used inside a library, then you need to
2381 perform a ``gnatbind`` step that specifies all :file:`ALI` files in all
2382 libraries, so that version identifiers can be properly computed.
2383 In practice these attributes are rarely used, so this is unlikely
2384 to be a consideration.
2386 .. _Rebuilding_the_GNAT_Run-Time_Library:
2388 Rebuilding the GNAT Run-Time Library
2389 ------------------------------------
2391 .. index:: GNAT Run-Time Library, rebuilding
2392 .. index:: Building the GNAT Run-Time Library
2393 .. index:: Rebuilding the GNAT Run-Time Library
2394 .. index:: Run-Time Library, rebuilding
2396 It may be useful to recompile the GNAT library in various debugging or
2397 experimentation contexts. A project file called
2398 :file:`libada.gpr` is provided to that effect and can be found in
2399 the directory containing the GNAT library. The location of this
2400 directory depends on the way the GNAT environment has been installed and can
2401 be determined by means of the command:
2403 .. code-block:: sh
2405       $ gnatls -v
2407 The last entry in the source search path usually contains the
2408 gnat library (the :file:`adainclude` directory). This project file contains its
2409 own documentation and in particular the set of instructions needed to rebuild a
2410 new library and to use it.
2412 Note that rebuilding the GNAT Run-Time is only recommended for temporary
2413 experiments or debugging, and is not supported.
2416 .. index:: ! Conditional compilation
2418 .. _Conditional_Compilation:
2420 Conditional Compilation
2421 =======================
2423 This section presents some guidelines for modeling conditional compilation in Ada and describes the
2424 gnatprep preprocessor utility.
2426 .. index:: ! Conditional compilation
2428 .. _Modeling_Conditional_Compilation_in_Ada:
2430 Modeling Conditional Compilation in Ada
2431 ---------------------------------------
2433 It is often necessary to arrange for a single source program
2434 to serve multiple purposes, where it is compiled in different
2435 ways to achieve these different goals. Some examples of the
2436 need for this feature are
2438 * Adapting a program to a different hardware environment
2439 * Adapting a program to a different target architecture
2440 * Turning debugging features on and off
2441 * Arranging for a program to compile with different compilers
2443 In C, or C++, the typical approach would be to use the preprocessor
2444 that is defined as part of the language. The Ada language does not
2445 contain such a feature. This is not an oversight, but rather a very
2446 deliberate design decision, based on the experience that overuse of
2447 the preprocessing features in C and C++ can result in programs that
2448 are extremely difficult to maintain. For example, if we have ten
2449 switches that can be on or off, this means that there are a thousand
2450 separate programs, any one of which might not even be syntactically
2451 correct, and even if syntactically correct, the resulting program
2452 might not work correctly. Testing all combinations can quickly become
2453 impossible.
2455 Nevertheless, the need to tailor programs certainly exists, and in
2456 this section we will discuss how this can
2457 be achieved using Ada in general, and GNAT in particular.
2459 .. _Use_of_Boolean_Constants:
2461 Use of Boolean Constants
2462 ^^^^^^^^^^^^^^^^^^^^^^^^
2464 In the case where the difference is simply which code
2465 sequence is executed, the cleanest solution is to use Boolean
2466 constants to control which code is executed.
2468 .. code-block:: ada
2470       FP_Initialize_Required : constant Boolean := True;
2471       ...
2472       if FP_Initialize_Required then
2473       ...
2474       end if;
2476 Not only will the code inside the ``if`` statement not be executed if
2477 the constant Boolean is ``False``, but it will also be completely
2478 deleted from the program.
2479 However, the code is only deleted after the ``if`` statement
2480 has been checked for syntactic and semantic correctness.
2481 (In contrast, with preprocessors the code is deleted before the
2482 compiler ever gets to see it, so it is not checked until the switch
2483 is turned on.)
2485 .. index:: Preprocessors (contrasted with conditional compilation)
2487 Typically the Boolean constants will be in a separate package,
2488 something like:
2490 .. code-block:: ada
2492        package Config is
2493           FP_Initialize_Required : constant Boolean := True;
2494           Reset_Available        : constant Boolean := False;
2495           ...
2496        end Config;
2498 The ``Config`` package exists in multiple forms for the various targets,
2499 with an appropriate script selecting the version of ``Config`` needed.
2500 Then any other unit requiring conditional compilation can do a |with|
2501 of ``Config`` to make the constants visible.
2503 .. _Debugging_-_A_Special_Case:
2505 Debugging - A Special Case
2506 ^^^^^^^^^^^^^^^^^^^^^^^^^^
2508 A common use of conditional code is to execute statements (for example
2509 dynamic checks, or output of intermediate results) under control of a
2510 debug switch, so that the debugging behavior can be turned on and off.
2511 This can be done using a Boolean constant to control whether the code
2512 is active:
2514 .. code-block:: ada
2516        if Debugging then
2517           Put_Line ("got to the first stage!");
2518        end if;
2522 .. code-block:: ada
2524        if Debugging and then Temperature > 999.0 then
2525           raise Temperature_Crazy;
2526        end if;
2528 .. index:: pragma Assert
2530 Since this is a common case, there are special features to deal with
2531 this in a convenient manner. For the case of tests, Ada 2005 has added
2532 a pragma ``Assert`` that can be used for such tests. This pragma is modeled
2533 on the ``Assert`` pragma that has always been available in GNAT, so this
2534 feature may be used with GNAT even if you are not using Ada 2005 features.
2535 The use of pragma ``Assert`` is described in the
2536 :title:`GNAT_Reference_Manual`, but as an
2537 example, the last test could be written:
2539 .. code-block:: ada
2541        pragma Assert (Temperature <= 999.0, "Temperature Crazy");
2543 or simply
2545 .. code-block:: ada
2547        pragma Assert (Temperature <= 999.0);
2549 In both cases, if assertions are active and the temperature is excessive,
2550 the exception ``Assert_Failure`` will be raised, with the given string in
2551 the first case or a string indicating the location of the pragma in the second
2552 case used as the exception message.
2554 .. index:: pragma Assertion_Policy
2556 You can turn assertions on and off by using the ``Assertion_Policy``
2557 pragma.
2559 .. index:: -gnata switch
2561 This is an Ada 2005 pragma which is implemented in all modes by
2562 GNAT. Alternatively, you can use the :switch:`-gnata` switch
2563 to enable assertions from the command line, which applies to
2564 all versions of Ada.
2566 .. index:: pragma Debug
2568 For the example above with the ``Put_Line``, the GNAT-specific pragma
2569 ``Debug`` can be used:
2571 .. code-block:: ada
2573        pragma Debug (Put_Line ("got to the first stage!"));
2575 If debug pragmas are enabled, the argument, which must be of the form of
2576 a procedure call, is executed (in this case, ``Put_Line`` will be called).
2577 Only one call can be present, but of course a special debugging procedure
2578 containing any code you like can be included in the program and then
2579 called in a pragma ``Debug`` argument as needed.
2581 One advantage of pragma ``Debug`` over the ``if Debugging then``
2582 construct is that pragma ``Debug`` can appear in declarative contexts,
2583 such as at the very beginning of a procedure, before local declarations have
2584 been elaborated.
2586 .. index:: pragma Debug_Policy
2588 Debug pragmas are enabled using either the :switch:`-gnata` switch that also
2589 controls assertions, or with a separate Debug_Policy pragma.
2591 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
2592 in Ada 95 and Ada 83 programs as well), and is analogous to
2593 pragma ``Assertion_Policy`` to control assertions.
2595 ``Assertion_Policy`` and ``Debug_Policy`` are configuration pragmas,
2596 and thus they can appear in :file:`gnat.adc` if you are not using a
2597 project file, or in the file designated to contain configuration pragmas
2598 in a project file.
2599 They then apply to all subsequent compilations. In practice the use of
2600 the :switch:`-gnata` switch is often the most convenient method of controlling
2601 the status of these pragmas.
2603 Note that a pragma is not a statement, so in contexts where a statement
2604 sequence is required, you can't just write a pragma on its own. You have
2605 to add a ``null`` statement.
2607 .. code-block:: ada
2609        if ... then
2610           ... -- some statements
2611        else
2612           pragma Assert (Num_Cases < 10);
2613           null;
2614        end if;
2616 .. _Conditionalizing_Declarations:
2618 Conditionalizing Declarations
2619 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2621 In some cases it may be necessary to conditionalize declarations to meet
2622 different requirements. For example we might want a bit string whose length
2623 is set to meet some hardware message requirement.
2625 This may be possible using declare blocks controlled
2626 by conditional constants:
2628 .. code-block:: ada
2630        if Small_Machine then
2631           declare
2632              X : Bit_String (1 .. 10);
2633           begin
2634              ...
2635           end;
2636        else
2637           declare
2638              X : Large_Bit_String (1 .. 1000);
2639           begin
2640              ...
2641           end;
2642        end if;
2644 Note that in this approach, both declarations are analyzed by the
2645 compiler so this can only be used where both declarations are legal,
2646 even though one of them will not be used.
2648 Another approach is to define integer constants, e.g., ``Bits_Per_Word``,
2649 or Boolean constants, e.g., ``Little_Endian``, and then write declarations
2650 that are parameterized by these constants. For example
2652 .. code-block:: ada
2654        for Rec use
2655          Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
2656        end record;
2658 If ``Bits_Per_Word`` is set to 32, this generates either
2660 .. code-block:: ada
2662        for Rec use
2663          Field1 at 0 range 0 .. 32;
2664        end record;
2666 for the big endian case, or
2668 .. code-block:: ada
2670        for Rec use record
2671            Field1 at 0 range 10 .. 32;
2672        end record;
2674 for the little endian case. Since a powerful subset of Ada expression
2675 notation is usable for creating static constants, clever use of this
2676 feature can often solve quite difficult problems in conditionalizing
2677 compilation (note incidentally that in Ada 95, the little endian
2678 constant was introduced as ``System.Default_Bit_Order``, so you do not
2679 need to define this one yourself).
2681 .. _Use_of_Alternative_Implementations:
2683 Use of Alternative Implementations
2684 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2686 In some cases, none of the approaches described above are adequate. This
2687 can occur for example if the set of declarations required is radically
2688 different for two different configurations.
2690 In this situation, the official Ada way of dealing with conditionalizing
2691 such code is to write separate units for the different cases. As long as
2692 this does not result in excessive duplication of code, this can be done
2693 without creating maintenance problems. The approach is to share common
2694 code as far as possible, and then isolate the code and declarations
2695 that are different. Subunits are often a convenient method for breaking
2696 out a piece of a unit that is to be conditionalized, with separate files
2697 for different versions of the subunit for different targets, where the
2698 build script selects the right one to give to the compiler.
2700 .. index:: Subunits (and conditional compilation)
2702 As an example, consider a situation where a new feature in Ada 2005
2703 allows something to be done in a really nice way. But your code must be able
2704 to compile with an Ada 95 compiler. Conceptually you want to say:
2706 .. code-block:: ada
2708        if Ada_2005 then
2709           ... neat Ada 2005 code
2710        else
2711           ... not quite as neat Ada 95 code
2712        end if;
2714 where ``Ada_2005`` is a Boolean constant.
2716 But this won't work when ``Ada_2005`` is set to ``False``,
2717 since the ``then`` clause will be illegal for an Ada 95 compiler.
2718 (Recall that although such unreachable code would eventually be deleted
2719 by the compiler, it still needs to be legal.  If it uses features
2720 introduced in Ada 2005, it will be illegal in Ada 95.)
2722 So instead we write
2724 .. code-block:: ada
2726        procedure Insert is separate;
2728 Then we have two files for the subunit ``Insert``, with the two sets of
2729 code.
2730 If the package containing this is called ``File_Queries``, then we might
2731 have two files
2733 * :file:`file_queries-insert-2005.adb`
2734 * :file:`file_queries-insert-95.adb`
2736 and the build script renames the appropriate file to :file:`file_queries-insert.adb` and then carries out the compilation.
2738 This can also be done with project files' naming schemes. For example:
2740 .. code-block:: gpr
2742        for body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
2744 Note also that with project files it is desirable to use a different extension
2745 than :file:`ads` / :file:`adb` for alternative versions. Otherwise a naming
2746 conflict may arise through another commonly used feature: to declare as part
2747 of the project a set of directories containing all the sources obeying the
2748 default naming scheme.
2750 The use of alternative units is certainly feasible in all situations,
2751 and for example the Ada part of the GNAT run-time is conditionalized
2752 based on the target architecture using this approach. As a specific example,
2753 consider the implementation of the AST feature in VMS. There is one
2754 spec: :file:`s-asthan.ads` which is the same for all architectures, and three
2755 bodies:
2757 * :file:`s-asthan.adb`
2758     used for all non-VMS operating systems
2760 * :file:`s-asthan-vms-alpha.adb`
2761     used for VMS on the Alpha
2763 * :file:`s-asthan-vms-ia64.adb`
2764     used for VMS on the ia64
2766 The dummy version :file:`s-asthan.adb` simply raises exceptions noting that
2767 this operating system feature is not available, and the two remaining
2768 versions interface with the corresponding versions of VMS to provide
2769 VMS-compatible AST handling. The GNAT build script knows the architecture
2770 and operating system, and automatically selects the right version,
2771 renaming it if necessary to :file:`s-asthan.adb` before the run-time build.
2773 Another style for arranging alternative implementations is through Ada's
2774 access-to-subprogram facility.
2775 In case some functionality is to be conditionally included,
2776 you can declare an access-to-procedure variable ``Ref`` that is initialized
2777 to designate a 'do nothing' procedure, and then invoke ``Ref.all``
2778 when appropriate.
2779 In some library package, set ``Ref`` to ``Proc'Access`` for some
2780 procedure ``Proc`` that performs the relevant processing.
2781 The initialization only occurs if the library package is included in the
2782 program.
2783 The same idea can also be implemented using tagged types and dispatching
2784 calls.
2786 .. _Preprocessing:
2788 Preprocessing
2789 ^^^^^^^^^^^^^
2791 .. index:: Preprocessing
2793 Although it is quite possible to conditionalize code without the use of
2794 C-style preprocessing, as described earlier in this section, it is
2795 nevertheless convenient in some cases to use the C approach. Moreover,
2796 older Ada compilers have often provided some preprocessing capability,
2797 so legacy code may depend on this approach, even though it is not
2798 standard.
2800 To accommodate such use, GNAT provides a preprocessor (modeled to a large
2801 extent on the various preprocessors that have been used
2802 with legacy code on other compilers, to enable easier transition).
2804 .. index:: gnatprep
2806 The preprocessor may be used in two separate modes. It can be used quite
2807 separately from the compiler, to generate a separate output source file
2808 that is then fed to the compiler as a separate step. This is the
2809 ``gnatprep`` utility, whose use is fully described in
2810 :ref:`Preprocessing_with_gnatprep`.
2812 The preprocessing language allows such constructs as
2814 .. code-block:: c
2816        #if DEBUG or else (PRIORITY > 4) then
2817           sequence of declarations
2818        #else
2819           completely different sequence of declarations
2820        #end if;
2822 The values of the symbols ``DEBUG`` and ``PRIORITY`` can be
2823 defined either on the command line or in a separate file.
2825 The other way of running the preprocessor is even closer to the C style and
2826 often more convenient. In this approach the preprocessing is integrated into
2827 the compilation process. The compiler is given the preprocessor input which
2828 includes ``#if`` lines etc, and then the compiler carries out the
2829 preprocessing internally and processes the resulting output.
2830 For more details on this approach, see :ref:`Integrated_Preprocessing`.
2832 .. _Preprocessing_with_gnatprep:
2834 Preprocessing with ``gnatprep``
2835 -------------------------------
2837 .. index:: ! gnatprep
2838 .. index:: Preprocessing (gnatprep)
2840 This section discusses how to use GNAT's ``gnatprep`` utility for simple
2841 preprocessing.
2842 Although designed for use with GNAT, ``gnatprep`` does not depend on any
2843 special GNAT features.
2844 For further discussion of conditional compilation in general, see
2845 :ref:`Conditional_Compilation`.
2847 .. _Preprocessing_Symbols:
2849 Preprocessing Symbols
2850 ^^^^^^^^^^^^^^^^^^^^^
2852 Preprocessing symbols are defined in *definition files* and referenced in the
2853 sources to be preprocessed. A preprocessing symbol is an identifier, following
2854 normal Ada (case-insensitive) rules for its syntax, with the restriction that
2855 all characters need to be in the ASCII set (no accented letters).
2857 .. _Using_gnatprep:
2859 Using ``gnatprep``
2860 ^^^^^^^^^^^^^^^^^^
2862 To call ``gnatprep`` use:
2864 .. code-block:: sh
2866     $ gnatprep [ switches ] infile outfile [ deffile ]
2868 where
2870 * *switches*
2871     is an optional sequence of switches as described in the next section.
2873 * *infile*
2874     is the full name of the input file, which is an Ada source
2875     file containing preprocessor directives.
2877 * *outfile*
2878     is the full name of the output file, which is an Ada source
2879     in standard Ada form. When used with GNAT, this file name will
2880     normally have an ``ads`` or ``adb`` suffix.
2882 * ``deffile``
2883     is the full name of a text file containing definitions of
2884     preprocessing symbols to be referenced by the preprocessor. This argument is
2885     optional, and can be replaced by the use of the :switch:`-D` switch.
2888 .. _Switches_for_gnatprep:
2890 Switches for ``gnatprep``
2891 ^^^^^^^^^^^^^^^^^^^^^^^^^
2893 .. index:: --version (gnatprep)
2895 :switch:`--version`
2896   Display Copyright and version, then exit disregarding all other options.
2898 .. index:: --help (gnatprep)
2900 :switch:`--help`
2901   If :switch:`--version` was not used, display usage and then exit disregarding
2902   all other options.
2904 .. index:: -b (gnatprep)
2906 :switch:`-b`
2907   Causes both preprocessor lines and the lines deleted by
2908   preprocessing to be replaced by blank lines in the output source file,
2909   preserving line numbers in the output file.
2911 .. index:: -c (gnatprep)
2913 :switch:`-c`
2914   Causes both preprocessor lines and the lines deleted
2915   by preprocessing to be retained in the output source as comments marked
2916   with the special string ``"--! "``. This option will result in line numbers
2917   being preserved in the output file.
2919 .. index:: -C (gnatprep)
2921 :switch:`-C`
2922   Causes comments to be scanned. Normally comments are ignored by gnatprep.
2923   If this option is specified, then comments are scanned and any $symbol
2924   substitutions performed as in program text. This is particularly useful
2925   when structured comments are used (e.g., for programs written in a
2926   pre-2014 version of the SPARK Ada subset). Note that this switch is not
2927   available when  doing integrated preprocessing (it would be useless in
2928   this context since comments are ignored by the compiler in any case).
2930 .. index:: -D (gnatprep)
2932 :switch:`-D{symbol}[={value}]`
2933   Defines a new preprocessing symbol with the specified value. If no value is given
2934   on the command line, then symbol is considered to be ``True``. This switch
2935   can be used in place of a definition file.
2937 .. index:: -r (gnatprep)
2939 :switch:`-r`
2940   Causes a ``Source_Reference`` pragma to be generated that
2941   references the original input file, so that error messages will use
2942   the file name of this original file. The use of this switch implies
2943   that preprocessor lines are not to be removed from the file, so its
2944   use will force ``-b`` mode if ``-c``
2945   has not been specified explicitly.
2947   Note that if the file to be preprocessed contains multiple units, then
2948   it will be necessary to ``gnatchop`` the output file from
2949   ``gnatprep``. If a ``Source_Reference`` pragma is present
2950   in the preprocessed file, it will be respected by
2951   ``gnatchop -r``
2952   so that the final chopped files will correctly refer to the original
2953   input source file for ``gnatprep``.
2955 .. index:: -s (gnatprep)
2957 :switch:`-s`
2958   Causes a sorted list of symbol names and values to be
2959   listed on the standard output file.
2961 .. index:: -T (gnatprep)
2963 :switch:`-T`
2964   Use LF as line terminators when writing files. By default the line terminator
2965   of the host (LF under unix, CR/LF under Windows) is used.
2967 .. index:: -u (gnatprep)
2969 :switch:`-u`
2970   Causes undefined symbols to be treated as having the value FALSE in the context
2971   of a preprocessor test. In the absence of this option, an undefined symbol in
2972   a ``#if`` or ``#elsif`` test will be treated as an error.
2974 .. index:: -v (gnatprep)
2976 :switch:`-v`
2977   Verbose mode: generates more output about work done.
2980 Note: if neither :switch:`-b` nor :switch:`-c` is present,
2981 then preprocessor lines and
2982 deleted lines are completely removed from the output, unless -r is
2983 specified, in which case -b is assumed.
2986 .. _Form_of_Definitions_File:
2988 Form of Definitions File
2989 ^^^^^^^^^^^^^^^^^^^^^^^^
2991 The definitions file contains lines of the form::
2993       symbol := value
2995 where ``symbol`` is a preprocessing symbol, and ``value`` is one of the following:
2997 *  Empty, corresponding to a null substitution,
2998 *  A string literal using normal Ada syntax, or
2999 *  Any sequence of characters from the set {letters, digits, period, underline}.
3001 Comment lines may also appear in the definitions file, starting with
3002 the usual ``--``,
3003 and comments may be added to the definitions lines.
3006 .. _Form_of_Input_Text_for_gnatprep:
3008 Form of Input Text for ``gnatprep``
3009 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3011 The input text may contain preprocessor conditional inclusion lines,
3012 as well as general symbol substitution sequences.
3014 The preprocessor conditional inclusion commands have the form:
3016 .. code-block:: c
3018        #if <expression> [then]
3019           lines
3020        #elsif <expression> [then]
3021           lines
3022        #elsif <expression> [then]
3023           lines
3024        ...
3025        #else
3026           lines
3027        #end if;
3029 In this example, <expression> is defined by the following grammar::
3031        <expression> ::=  <symbol>
3032        <expression> ::=  <symbol> = "<value>"
3033        <expression> ::=  <symbol> = <symbol>
3034        <expression> ::=  <symbol> = <integer>
3035        <expression> ::=  <symbol> > <integer>
3036        <expression> ::=  <symbol> >= <integer>
3037        <expression> ::=  <symbol> < <integer>
3038        <expression> ::=  <symbol> <= <integer>
3039        <expression> ::=  <symbol> 'Defined
3040        <expression> ::=  not <expression>
3041        <expression> ::=  <expression> and <expression>
3042        <expression> ::=  <expression> or <expression>
3043        <expression> ::=  <expression> and then <expression>
3044        <expression> ::=  <expression> or else <expression>
3045        <expression> ::=  ( <expression> )
3047 Note the following restriction: it is not allowed to have "and" or "or"
3048 following "not" in the same expression without parentheses. For example, this
3049 is not allowed:
3051 .. code-block:: ada
3053        not X or Y
3055 This can be expressed instead as one of the following forms:
3057 .. code-block:: ada
3059      (not X) or Y
3060      not (X or Y)
3062 For the first test (<expression> ::= <symbol>) the symbol must have
3063 either the value true or false, that is to say the right-hand of the
3064 symbol definition must be one of the (case-insensitive) literals
3065 ``True`` or ``False``. If the value is true, then the
3066 corresponding lines are included, and if the value is false, they are
3067 excluded.
3069 When comparing a symbol to an integer, the integer is any non negative
3070 literal integer as defined in the Ada Reference Manual, such as 3, 16#FF# or
3071 2#11#. The symbol value must also be a non negative integer. Integer values
3072 in the range 0 .. 2**31-1 are supported.
3074 The test (<expression> ::= <symbol>'Defined) is true only if
3075 the symbol has been defined in the definition file or by a :switch:`-D`
3076 switch on the command line. Otherwise, the test is false.
3078 The equality tests are case insensitive, as are all the preprocessor lines.
3080 If the symbol referenced is not defined in the symbol definitions file,
3081 then the effect depends on whether or not switch :switch:`-u`
3082 is specified. If so, then the symbol is treated as if it had the value
3083 false and the test fails. If this switch is not specified, then
3084 it is an error to reference an undefined symbol. It is also an error to
3085 reference a symbol that is defined with a value other than ``True``
3086 or ``False``.
3088 The use of the ``not`` operator inverts the sense of this logical test.
3089 The ``not`` operator cannot be combined with the ``or`` or ``and``
3090 operators, without parentheses. For example, "if not X or Y then" is not
3091 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
3093 The ``then`` keyword is optional as shown
3095 The ``#`` must be the first non-blank character on a line, but
3096 otherwise the format is free form. Spaces or tabs may appear between
3097 the ``#`` and the keyword. The keywords and the symbols are case
3098 insensitive as in normal Ada code. Comments may be used on a
3099 preprocessor line, but other than that, no other tokens may appear on a
3100 preprocessor line. Any number of ``elsif`` clauses can be present,
3101 including none at all. The ``else`` is optional, as in Ada.
3103 The ``#`` marking the start of a preprocessor line must be the first
3104 non-blank character on the line, i.e., it must be preceded only by
3105 spaces or horizontal tabs.
3107 Symbol substitution outside of preprocessor lines is obtained by using
3108 the sequence::
3110       $symbol
3112 anywhere within a source line, except in a comment or within a
3113 string literal. The identifier
3114 following the ``$`` must match one of the symbols defined in the symbol
3115 definition file, and the result is to substitute the value of the
3116 symbol in place of ``$symbol`` in the output file.
3118 Note that although the substitution of strings within a string literal
3119 is not possible, it is possible to have a symbol whose defined value is
3120 a string literal. So instead of setting XYZ to ``hello`` and writing:
3122 .. code-block:: ada
3124      Header : String := "$XYZ";
3126 you should set XYZ to ``"hello"`` and write:
3128 .. code-block:: ada
3130      Header : String := $XYZ;
3132 and then the substitution will occur as desired.
3135 .. _Integrated_Preprocessing:
3137 Integrated Preprocessing
3138 ------------------------
3140 As noted above, a file to be preprocessed consists of Ada source code
3141 in which preprocessing lines have been inserted. However,
3142 instead of using ``gnatprep`` to explicitly preprocess a file as a separate
3143 step before compilation, you can carry out the preprocessing implicitly
3144 as part of compilation. Such *integrated preprocessing*, which is the common
3145 style with C, is performed when either or both of the following switches
3146 are passed to the compiler:
3148    *   :switch:`-gnatep`, which specifies the *preprocessor data file*.
3149        This file dictates how the source files will be preprocessed (e.g., which
3150        symbol definition files apply to which sources).
3152    *   :switch:`-gnateD`, which defines values for preprocessing symbols.
3154 Integrated preprocessing applies only to Ada source files, it is
3155 not available for configuration pragma files.
3157 With integrated preprocessing, the output from the preprocessor is not,
3158 by default, written to any external file. Instead it is passed
3159 internally to the compiler. To preserve the result of
3160 preprocessing in a file, either run ``gnatprep``
3161 in standalone mode or else supply the :switch:`-gnateG` switch
3162 (described below) to the compiler.
3164 When using project files:
3166    *    the builder switch :switch:`-x` should be used if any Ada source is
3167         compiled with :switch:`gnatep=`, so that the compiler finds the
3168         *preprocessor data file*.
3170    *    the preprocessing data file and the symbol definition files should be
3171         located in the source directories of the project.
3173 Note that the ``gnatmake`` switch :switch:`-m` will almost
3174 always trigger recompilation for sources that are preprocessed,
3175 because ``gnatmake`` cannot compute the checksum of the source after
3176 preprocessing.
3178 The actual preprocessing function is described in detail in
3179 :ref:`Preprocessing_with_gnatprep`. This section explains the switches
3180 that relate to integrated preprocessing.
3182 .. index:: -gnatep (gcc)
3184 :switch:`-gnatep={preprocessor_data_file}`
3185   This switch specifies the file name (without directory
3186   information) of the preprocessor data file. Either place this file
3187   in one of the source directories, or, when using project
3188   files, reference the project file's directory via the
3189   ``project_name'Project_Dir`` project attribute; e.g:
3191      .. code-block:: gpr
3193          project Prj is
3194             package Compiler is
3195                for Switches ("Ada") use
3196                  ("-gnatep=" & Prj'Project_Dir & "prep.def");
3197             end Compiler;
3198          end Prj;
3200   A preprocessor data file is a text file that contains *preprocessor
3201   control lines*.  A preprocessor control line directs the preprocessing of
3202   either a particular source file, or, analogous to ``others`` in Ada,
3203   all sources not specified elsewhere in  the preprocessor data file.
3204   A preprocessor control line
3205   can optionally identify a *definition file* that assigns values to
3206   preprocessor symbols, as well as a list of switches that relate to
3207   preprocessing.
3208   Empty lines and comments (using Ada syntax) are also permitted, with no
3209   semantic effect.
3211   Here's an example of a preprocessor data file:
3213     .. code-block:: ada
3215         "toto.adb"  "prep.def" -u
3216         --  Preprocess toto.adb, using definition file prep.def
3217         --  Undefined symbols are treated as False
3219         * -c -DVERSION=V101
3220         --  Preprocess all other sources without using a definition file
3221         --  Suppressed lined are commented
3222         --  Symbol VERSION has the value V101
3224         "tata.adb" "prep2.def" -s
3225         --  Preprocess tata.adb, using definition file prep2.def
3226         --  List all symbols with their values
3228   A preprocessor control line has the following syntax:
3230     ::
3232         <preprocessor_control_line> ::=
3233            <preprocessor_input> [ <definition_file_name> ] { <switch> }
3235         <preprocessor_input> ::= <source_file_name> | '*'
3237         <definition_file_name> ::= <string_literal>
3239         <source_file_name> := <string_literal>
3241         <switch> := (See below for list)
3243   Thus  each preprocessor control line starts with either a literal string or
3244   the character '*':
3246   *  A literal string is the file name (without directory information) of the source
3247      file that will be input to the preprocessor.
3249   *  The character '*' is a wild-card indicator; the additional parameters on the line
3250      indicate the preprocessing for all the sources
3251      that are not specified explicitly on other lines (the order of the lines is not
3252      significant).
3254   It is an error to have two lines with the same file name or two
3255   lines starting with the character '*'.
3257   After the file name or '*', an optional literal string specifies the name of
3258   the definition file to be used for preprocessing
3259   (:ref:`Form_of_Definitions_File`). The definition files are found by the
3260   compiler in one of the source directories. In some cases, when compiling
3261   a source in a directory other than the current directory, if the definition
3262   file is in the current directory, it may be necessary to add the current
3263   directory as a source directory through the :switch:`-I` switch; otherwise
3264   the compiler would not find the definition file.
3266   Finally, switches similar to those of ``gnatprep`` may optionally appear:
3268   :switch:`-b`
3269     Causes both preprocessor lines and the lines deleted by
3270     preprocessing to be replaced by blank lines, preserving the line number.
3271     This switch is always implied; however, if specified after :switch:`-c`
3272     it cancels the effect of :switch:`-c`.
3275   :switch:`-c`
3276     Causes both preprocessor lines and the lines deleted
3277     by preprocessing to be retained as comments marked
3278     with the special string '`--!`'.
3281   :switch:`-D{symbol}={new_value}`
3282     Define or redefine ``symbol`` to have ``new_value`` as its value.
3283     The permitted form for ``symbol`` is either an Ada identifier, or any Ada reserved word
3284     aside from ``if``,
3285     ``else``, ``elsif``, ``end``, ``and``, ``or`` and ``then``.
3286     The permitted form for ``new_value`` is a literal string, an Ada identifier or any Ada reserved
3287     word. A symbol declared with this switch replaces a symbol with the
3288     same name defined in a definition file.
3291   :switch:`-s`
3292     Causes a sorted list of symbol names and values to be
3293     listed on the standard output file.
3296   :switch:`-u`
3297     Causes undefined symbols to be treated as having the value ``FALSE``
3298     in the context
3299     of a preprocessor test. In the absence of this option, an undefined symbol in
3300     a ``#if`` or ``#elsif`` test will be treated as an error.
3303 .. index:: -gnateD (gcc)
3305 :switch:`-gnateD{symbol}[={new_value}]`
3306   Define or redefine ``symbol`` to have ``new_value`` as its value. If no value
3307   is supplied, then the value of ``symbol`` is ``True``.
3308   The form of ``symbol`` is an identifier, following normal Ada (case-insensitive)
3309   rules for its syntax, and ``new_value`` is either an arbitrary string between double
3310   quotes or any sequence (including an empty sequence) of characters from the
3311   set (letters, digits, period, underline).
3312   Ada reserved words may be used as symbols, with the exceptions of ``if``,
3313   ``else``, ``elsif``, ``end``, ``and``, ``or`` and ``then``.
3315   Examples:
3317     ::
3319         -gnateDToto=Tata
3320         -gnateDFoo
3321         -gnateDFoo=\"Foo-Bar\"
3323   A symbol declared with this switch on the command line replaces a
3324   symbol with the same name either in a definition file or specified with a
3325   switch :switch:`-D` in the preprocessor data file.
3327   This switch is similar to switch :switch:`-D` of ``gnatprep``.
3330 :switch:`-gnateG`
3331   When integrated preprocessing is performed on source file :file:`filename.extension`,
3332   create or overwrite :file:`filename.extension.prep` to contain
3333   the result of the preprocessing.
3334   For example if the source file is :file:`foo.adb` then
3335   the output file will be :file:`foo.adb.prep`.
3338 .. _Mixed_Language_Programming:
3340 Mixed Language Programming
3341 ==========================
3343 .. index:: Mixed Language Programming
3345 This section describes how to develop a mixed-language program,
3346 with a focus on combining Ada with C or C++.
3348 .. _Interfacing_to_C:
3350 Interfacing to C
3351 ----------------
3353 Interfacing Ada with a foreign language such as C involves using
3354 compiler directives to import and/or export entity definitions in each
3355 language -- using ``extern`` statements in C, for instance, and the
3356 ``Import``, ``Export``, and ``Convention`` pragmas in Ada.
3357 A full treatment of these topics is provided in Appendix B, section 1
3358 of the Ada Reference Manual.
3360 There are two ways to build a program using GNAT that contains some Ada
3361 sources and some foreign language sources, depending on whether or not
3362 the main subprogram is written in Ada.  Here is a source example with
3363 the main subprogram in Ada:
3365 .. code-block:: c
3367     /* file1.c */
3368     #include <stdio.h>
3370     void print_num (int num)
3371     {
3372       printf ("num is %d.\\n", num);
3373       return;
3374     }
3376 .. code-block:: c
3378     /* file2.c */
3380     /* num_from_Ada is declared in my_main.adb */
3381     extern int num_from_Ada;
3383     int get_num (void)
3384     {
3385       return num_from_Ada;
3386     }
3388 .. code-block:: ada
3390     --  my_main.adb
3391     procedure My_Main is
3393        --  Declare then export an Integer entity called num_from_Ada
3394        My_Num : Integer := 10;
3395        pragma Export (C, My_Num, "num_from_Ada");
3397        --  Declare an Ada function spec for Get_Num, then use
3398        --  C function get_num for the implementation.
3399        function Get_Num return Integer;
3400        pragma Import (C, Get_Num, "get_num");
3402        --  Declare an Ada procedure spec for Print_Num, then use
3403        --  C function print_num for the implementation.
3404        procedure Print_Num (Num : Integer);
3405        pragma Import (C, Print_Num, "print_num");
3407     begin
3408        Print_Num (Get_Num);
3409     end My_Main;
3411 To build this example:
3413 * First compile the foreign language files to
3414   generate object files:
3416   .. code-block:: sh
3418       $ gcc -c file1.c
3419       $ gcc -c file2.c
3421 * Then, compile the Ada units to produce a set of object files and ALI
3422   files:
3424   .. code-block:: sh
3426       $ gnatmake -c my_main.adb
3428 * Run the Ada binder on the Ada main program:
3430   .. code-block:: sh
3432       $ gnatbind my_main.ali
3434 * Link the Ada main program, the Ada objects and the other language
3435   objects:
3437   .. code-block:: sh
3439       $ gnatlink my_main.ali file1.o file2.o
3441 The last three steps can be grouped in a single command:
3443 .. code-block:: sh
3445    $ gnatmake my_main.adb -largs file1.o file2.o
3448 .. index:: Binder output file
3450 If the main program is in a language other than Ada, then you may have
3451 more than one entry point into the Ada subsystem. You must use a special
3452 binder option to generate callable routines that initialize and
3453 finalize the Ada units (:ref:`Binding_with_Non-Ada_Main_Programs`).
3454 Calls to the initialization and finalization routines must be inserted
3455 in the main program, or some other appropriate point in the code. The
3456 call to initialize the Ada units must occur before the first Ada
3457 subprogram is called, and the call to finalize the Ada units must occur
3458 after the last Ada subprogram returns. The binder will place the
3459 initialization and finalization subprograms into the
3460 :file:`b~xxx.adb` file where they can be accessed by your C
3461 sources.  To illustrate, we have the following example:
3463 .. code-block:: c
3465      /* main.c */
3466      extern void adainit (void);
3467      extern void adafinal (void);
3468      extern int add (int, int);
3469      extern int sub (int, int);
3471      int main (int argc, char *argv[])
3472      {
3473         int a = 21, b = 7;
3475         adainit();
3477         /* Should print "21 + 7 = 28" */
3478         printf ("%d + %d = %d\\n", a, b, add (a, b));
3480         /* Should print "21 - 7 = 14" */
3481         printf ("%d - %d = %d\\n", a, b, sub (a, b));
3483         adafinal();
3484      }
3486 .. code-block:: ada
3488      --  unit1.ads
3489      package Unit1 is
3490         function Add (A, B : Integer) return Integer;
3491         pragma Export (C, Add, "add");
3492      end Unit1;
3494 .. code-block:: ada
3496      --  unit1.adb
3497      package body Unit1 is
3498         function Add (A, B : Integer) return Integer is
3499         begin
3500            return A + B;
3501         end Add;
3502      end Unit1;
3504 .. code-block:: ada
3506      --  unit2.ads
3507      package Unit2 is
3508         function Sub (A, B : Integer) return Integer;
3509         pragma Export (C, Sub, "sub");
3510      end Unit2;
3512 .. code-block:: ada
3514      --  unit2.adb
3515      package body Unit2 is
3516         function Sub (A, B : Integer) return Integer is
3517         begin
3518            return A - B;
3519         end Sub;
3520      end Unit2;
3522 The build procedure for this application is similar to the last
3523 example's:
3525 * First, compile the foreign language files to generate object files:
3527   .. code-block:: sh
3529       $ gcc -c main.c
3532 * Next, compile the Ada units to produce a set of object files and ALI
3533   files:
3535   .. code-block:: sh
3537       $ gnatmake -c unit1.adb
3538       $ gnatmake -c unit2.adb
3540 * Run the Ada binder on every generated ALI file.  Make sure to use the
3541   :switch:`-n` option to specify a foreign main program:
3543   .. code-block:: sh
3545       $ gnatbind -n unit1.ali unit2.ali
3547 * Link the Ada main program, the Ada objects and the foreign language
3548   objects. You need only list the last ALI file here:
3550   .. code-block:: sh
3552       $ gnatlink unit2.ali main.o -o exec_file
3554   This procedure yields a binary executable called :file:`exec_file`.
3556 Depending on the circumstances (for example when your non-Ada main object
3557 does not provide symbol ``main``), you may also need to instruct the
3558 GNAT linker not to include the standard startup objects by passing the
3559 :switch:`-nostartfiles` switch to ``gnatlink``.
3561 .. _Calling_Conventions:
3563 Calling Conventions
3564 -------------------
3566 .. index:: Foreign Languages
3568 .. index:: Calling Conventions
3570 GNAT follows standard calling sequence conventions and will thus interface
3571 to any other language that also follows these conventions. The following
3572 Convention identifiers are recognized by GNAT:
3575 .. index:: Interfacing to Ada
3577 .. index:: Other Ada compilers
3579 .. index:: Convention Ada
3581 ``Ada``
3582   This indicates that the standard Ada calling sequence will be
3583   used and all Ada data items may be passed without any limitations in the
3584   case where GNAT is used to generate both the caller and callee. It is also
3585   possible to mix GNAT generated code and code generated by another Ada
3586   compiler. In this case, the data types should be restricted to simple
3587   cases, including primitive types. Whether complex data types can be passed
3588   depends on the situation. Probably it is safe to pass simple arrays, such
3589   as arrays of integers or floats. Records may or may not work, depending
3590   on whether both compilers lay them out identically. Complex structures
3591   involving variant records, access parameters, tasks, or protected types,
3592   are unlikely to be able to be passed.
3594   Note that in the case of GNAT running
3595   on a platform that supports HP Ada 83, a higher degree of compatibility
3596   can be guaranteed, and in particular records are laid out in an identical
3597   manner in the two compilers. Note also that if output from two different
3598   compilers is mixed, the program is responsible for dealing with elaboration
3599   issues. Probably the safest approach is to write the main program in the
3600   version of Ada other than GNAT, so that it takes care of its own elaboration
3601   requirements, and then call the GNAT-generated adainit procedure to ensure
3602   elaboration of the GNAT components. Consult the documentation of the other
3603   Ada compiler for further details on elaboration.
3605   However, it is not possible to mix the tasking run time of GNAT and
3606   HP Ada 83, All the tasking operations must either be entirely within
3607   GNAT compiled sections of the program, or entirely within HP Ada 83
3608   compiled sections of the program.
3610 .. index:: Interfacing to Assembly
3612 .. index:: Convention Assembler
3615 ``Assembler``
3616   Specifies assembler as the convention. In practice this has the
3617   same effect as convention Ada (but is not equivalent in the sense of being
3618   considered the same convention).
3620 .. index:: Convention Asm
3622 .. index:: Asm
3624 ``Asm``
3625   Equivalent to Assembler.
3627   .. index:: Interfacing to COBOL
3629   .. index:: Convention COBOL
3631 .. index:: COBOL
3633 ``COBOL``
3634   Data will be passed according to the conventions described
3635   in section B.4 of the Ada Reference Manual.
3637 .. index:: C
3638 .. index:: Interfacing to C
3640 .. index:: Convention C
3643 ``C``
3644   Data will be passed according to the conventions described
3645   in section B.3 of the Ada Reference Manual.
3647   A note on interfacing to a C 'varargs' function:
3649     .. index:: C varargs function
3650     .. index:: Interfacing to C varargs function
3651     .. index:: varargs function interfaces
3653     In C, ``varargs`` allows a function to take a variable number of
3654     arguments. There is no direct equivalent in this to Ada. One
3655     approach that can be used is to create a C wrapper for each
3656     different profile and then interface to this C wrapper. For
3657     example, to print an ``int`` value using ``printf``,
3658     create a C function ``printfi`` that takes two arguments, a
3659     pointer to a string and an int, and calls ``printf``.
3660     Then in the Ada program, use pragma ``Import`` to
3661     interface to ``printfi``.
3663     It may work on some platforms to directly interface to
3664     a ``varargs`` function by providing a specific Ada profile
3665     for a particular call. However, this does not work on
3666     all platforms, since there is no guarantee that the
3667     calling sequence for a two argument normal C function
3668     is the same as for calling a ``varargs`` C function with
3669     the same two arguments.
3671 .. index:: Convention Default
3673 .. index:: Default
3675 ``Default``
3676   Equivalent to C.
3678 .. index:: Convention External
3680 .. index:: External
3682 ``External``
3683   Equivalent to C.
3685 .. index:: C++
3686 .. index:: Interfacing to C++
3688 .. index:: Convention C++
3691 ``C_Plus_Plus`` (or ``CPP``)
3692   This stands for C++. For most purposes this is identical to C.
3693   See the separate description of the specialized GNAT pragmas relating to
3694   C++ interfacing for further details.
3696 .. index:: Fortran
3697 .. index:: Interfacing to Fortran
3698 .. index:: Convention Fortran
3701 ``Fortran``
3702   Data will be passed according to the conventions described
3703   in section B.5 of the Ada Reference Manual.
3706 ``Intrinsic``
3707   This applies to an intrinsic operation, as defined in the Ada
3708   Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
3709   this means that the body of the subprogram is provided by the compiler itself,
3710   usually by means of an efficient code sequence, and that the user does not
3711   supply an explicit body for it. In an application program, the pragma may
3712   be applied to the following sets of names:
3715   * Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_Arithmetic.
3716     The corresponding subprogram declaration must have
3717     two formal parameters. The
3718     first one must be a signed integer type or a modular type with a binary
3719     modulus, and the second parameter must be of type Natural.
3720     The return type must be the same as the type of the first argument. The size
3721     of this type can only be 8, 16, 32, or 64.
3724   * Binary arithmetic operators: '+', '-', '*', '/'.
3725     The corresponding operator declaration must have parameters and result type
3726     that have the same root numeric type (for example, all three are long_float
3727     types). This simplifies the definition of operations that use type checking
3728     to perform dimensional checks:
3731   .. code-block:: ada
3733       type Distance is new Long_Float;
3734       type Time     is new Long_Float;
3735       type Velocity is new Long_Float;
3736       function "/" (D : Distance; T : Time)
3737         return Velocity;
3738       pragma Import (Intrinsic, "/");
3740     This common idiom is often programmed with a generic definition and an
3741     explicit body. The pragma makes it simpler to introduce such declarations.
3742     It incurs no overhead in compilation time or code size, because it is
3743     implemented as a single machine instruction.
3746   * General subprogram entities. This is used  to bind an Ada subprogram
3747     declaration to
3748     a compiler builtin by name with back-ends where such interfaces are
3749     available. A typical example is the set of ``__builtin`` functions
3750     exposed by the GCC back-end, as in the following example:
3753     .. code-block:: ada
3755          function builtin_sqrt (F : Float) return Float;
3756          pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
3758     Most of the GCC builtins are accessible this way, and as for other
3759     import conventions (e.g. C), it is the user's responsibility to ensure
3760     that the Ada subprogram profile matches the underlying builtin
3761     expectations.
3763 .. index:: Stdcall
3764 .. index:: Convention Stdcall
3766 ``Stdcall``
3767   This is relevant only to Windows implementations of GNAT,
3768   and specifies that the ``Stdcall`` calling sequence will be used,
3769   as defined by the NT API. Nevertheless, to ease building
3770   cross-platform bindings this convention will be handled as a ``C`` calling
3771   convention on non-Windows platforms.
3773 .. index:: DLL
3774 .. index:: Convention DLL
3777 ``DLL``
3778   This is equivalent to ``Stdcall``.
3780 .. index:: Win32
3781 .. index:: Convention Win32
3784 ``Win32``
3785   This is equivalent to ``Stdcall``.
3787 .. index:: Stubbed
3788 .. index:: Convention Stubbed
3791 ``Stubbed``
3792   This is a special convention that indicates that the compiler
3793   should provide a stub body that raises ``Program_Error``.
3795 GNAT additionally provides a useful pragma ``Convention_Identifier``
3796 that can be used to parameterize conventions and allow additional synonyms
3797 to be specified. For example if you have legacy code in which the convention
3798 identifier Fortran77 was used for Fortran, you can use the configuration
3799 pragma:
3801 .. code-block:: ada
3803      pragma Convention_Identifier (Fortran77, Fortran);
3805 And from now on the identifier Fortran77 may be used as a convention
3806 identifier (for example in an ``Import`` pragma) with the same
3807 meaning as Fortran.
3810 .. _Building_Mixed_Ada_and_C++_Programs:
3812 Building Mixed Ada and C++ Programs
3813 -----------------------------------
3815 A programmer inexperienced with mixed-language development may find that
3816 building an application containing both Ada and C++ code can be a
3817 challenge.  This section gives a few hints that should make this task easier.
3819 .. _Interfacing_to_C++:
3821 Interfacing to C++
3822 ^^^^^^^^^^^^^^^^^^
3824 GNAT supports interfacing with the G++ compiler (or any C++ compiler
3825 generating code that is compatible with the G++ Application Binary
3826 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
3828 Interfacing can be done at 3 levels: simple data, subprograms, and
3829 classes. In the first two cases, GNAT offers a specific ``Convention C_Plus_Plus``
3830 (or ``CPP``) that behaves exactly like ``Convention C``.
3831 Usually, C++ mangles the names of subprograms. To generate proper mangled
3832 names automatically, see :ref:`Generating_Ada_Bindings_for_C_and_C++_headers`).
3833 This problem can also be addressed manually in two ways:
3835 * by modifying the C++ code in order to force a C convention using
3836   the ``extern "C"`` syntax.
3838 * by figuring out the mangled name (using e.g. ``nm``) and using it as the
3839   Link_Name argument of the pragma import.
3841 Interfacing at the class level can be achieved by using the GNAT specific
3842 pragmas such as ``CPP_Constructor``.  See the :title:`GNAT_Reference_Manual` for additional information.
3844 .. _Linking_a_Mixed_C++_and_Ada_Program:
3846 Linking a Mixed C++ & Ada Program
3847 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3849 Usually the linker of the C++ development system must be used to link
3850 mixed applications because most C++ systems will resolve elaboration
3851 issues (such as calling constructors on global class instances)
3852 transparently during the link phase. GNAT has been adapted to ease the
3853 use of a foreign linker for the last phase. Three cases can be
3854 considered:
3857 * Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3858   The C++ linker can simply be called by using the C++ specific driver
3859   called ``g++``.
3861   Note that if the C++ code uses inline functions, you will need to
3862   compile your C++ code with the :switch:`-fkeep-inline-functions` switch in
3863   order to provide an existing function implementation that the Ada code can
3864   link with.
3866   .. code-block:: sh
3868     $ g++ -c -fkeep-inline-functions file1.C
3869     $ g++ -c -fkeep-inline-functions file2.C
3870     $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
3873 * Using GNAT and G++ from two different GCC installations: If both
3874   compilers are on the :envvar`PATH`, the previous method may be used. It is
3875   important to note that environment variables such as
3876   :envvar:`C_INCLUDE_PATH`, :envvar:`GCC_EXEC_PREFIX`,
3877   :envvar:`BINUTILS_ROOT`, and
3878   :envvar:`GCC_ROOT` will affect both compilers
3879   at the same time and may make one of the two compilers operate
3880   improperly if set during invocation of the wrong compiler.  It is also
3881   very important that the linker uses the proper :file:`libgcc.a` GCC
3882   library -- that is, the one from the C++ compiler installation. The
3883   implicit link command as suggested in the ``gnatmake`` command
3884   from the former example can be replaced by an explicit link command with
3885   the full-verbosity option in order to verify which library is used:
3887   .. code-block:: sh
3889     $ gnatbind ada_unit
3890     $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3892   If there is a problem due to interfering environment variables, it can
3893   be worked around by using an intermediate script. The following example
3894   shows the proper script to use when GNAT has not been installed at its
3895   default location and g++ has been installed at its default location:
3897   .. code-block:: sh
3899     $ cat ./my_script
3900     #!/bin/sh
3901     unset BINUTILS_ROOT
3902     unset GCC_ROOT
3903     c++ $*
3904     $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3907 * Using a non-GNU C++ compiler: The commands previously described can be
3908   used to insure that the C++ linker is used. Nonetheless, you need to add
3909   a few more parameters to the link command line, depending on the exception
3910   mechanism used.
3912   If the ``setjmp`` / ``longjmp`` exception mechanism is used, only the paths
3913   to the ``libgcc`` libraries are required:
3915   .. code-block:: sh
3917     $ cat ./my_script
3918     #!/bin/sh
3919     CC $* gcc -print-file-name=libgcc.a gcc -print-file-name=libgcc_eh.a
3920     $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3923   where CC is the name of the non-GNU C++ compiler.
3925   If the "zero cost" exception mechanism is used, and the platform
3926   supports automatic registration of exception tables (e.g., Solaris),
3927   paths to more objects are required:
3929   .. code-block:: sh
3931     $ cat ./my_script
3932     #!/bin/sh
3933     CC gcc -print-file-name=crtbegin.o $* \\
3934     gcc -print-file-name=libgcc.a gcc -print-file-name=libgcc_eh.a \\
3935     gcc -print-file-name=crtend.o
3936     $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3939   If the "zero cost exception" mechanism is used, and the platform
3940   doesn't support automatic registration of exception tables (e.g., HP-UX
3941   or AIX), the simple approach described above will not work and
3942   a pre-linking phase using GNAT will be necessary.
3945 Another alternative is to use the :command:`gprbuild` multi-language builder
3946 which has a large knowledge base and knows how to link Ada and C++ code
3947 together automatically in most cases.
3949 .. _A_Simple_Example:
3951 A Simple Example
3952 ^^^^^^^^^^^^^^^^
3954 The following example, provided as part of the GNAT examples, shows how
3955 to achieve procedural interfacing between Ada and C++ in both
3956 directions. The C++ class A has two methods. The first method is exported
3957 to Ada by the means of an extern C wrapper function. The second method
3958 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3959 a limited record with a layout comparable to the C++ class. The Ada
3960 subprogram, in turn, calls the C++ method. So, starting from the C++
3961 main program, the process passes back and forth between the two
3962 languages.
3964 Here are the compilation commands:
3966 .. code-block:: sh
3968      $ gnatmake -c simple_cpp_interface
3969      $ g++ -c cpp_main.C
3970      $ g++ -c ex7.C
3971      $ gnatbind -n simple_cpp_interface
3972      $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++ -lstdc++ ex7.o cpp_main.o
3974 Here are the corresponding sources:
3976 .. code-block:: cpp
3978      //cpp_main.C
3980      #include "ex7.h"
3982      extern "C" {
3983        void adainit (void);
3984        void adafinal (void);
3985        void method1 (A *t);
3986      }
3988      void method1 (A *t)
3989      {
3990        t->method1 ();
3991      }
3993      int main ()
3994      {
3995        A obj;
3996        adainit ();
3997        obj.method2 (3030);
3998        adafinal ();
3999      }
4001 .. code-block:: cpp
4003      //ex7.h
4005      class Origin {
4006       public:
4007        int o_value;
4008      };
4009      class A : public Origin {
4010       public:
4011        void method1 (void);
4012        void method2 (int v);
4013        A();
4014        int   a_value;
4015      };
4017 .. code-block:: cpp
4019      //ex7.C
4021      #include "ex7.h"
4022      #include <stdio.h>
4024      extern "C" { void ada_method2 (A *t, int v);}
4026      void A::method1 (void)
4027      {
4028        a_value = 2020;
4029        printf ("in A::method1, a_value = %d \\n",a_value);
4030      }
4032      void A::method2 (int v)
4033      {
4034         ada_method2 (this, v);
4035         printf ("in A::method2, a_value = %d \\n",a_value);
4036      }
4038      A::A(void)
4039      {
4040         a_value = 1010;
4041        printf ("in A::A, a_value = %d \\n",a_value);
4042      }
4044 .. code-block:: ada
4046      -- simple_cpp_interface.ads
4047      with System;
4048      package Simple_Cpp_Interface is
4049         type A is limited
4050            record
4051               Vptr    : System.Address;
4052               O_Value : Integer;
4053               A_Value : Integer;
4054            end record;
4055         pragma Convention (C, A);
4057         procedure Method1 (This : in out A);
4058         pragma Import (C, Method1);
4060         procedure Ada_Method2 (This : in out A; V : Integer);
4061         pragma Export (C, Ada_Method2);
4063      end Simple_Cpp_Interface;
4065 .. code-block:: ada
4067      -- simple_cpp_interface.adb
4068      package body Simple_Cpp_Interface is
4070         procedure Ada_Method2 (This : in out A; V : Integer) is
4071         begin
4072            Method1 (This);
4073            This.A_Value := V;
4074         end Ada_Method2;
4076      end Simple_Cpp_Interface;
4079 .. _Interfacing_with_C++_constructors:
4081 Interfacing with C++ constructors
4082 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4084 In order to interface with C++ constructors GNAT provides the
4085 ``pragma CPP_Constructor`` (see the :title:`GNAT_Reference_Manual`
4086 for additional information).
4087 In this section we present some common uses of C++ constructors
4088 in mixed-languages programs in GNAT.
4090 Let us assume that we need to interface with the following
4091 C++ class:
4093 .. code-block:: cpp
4095      class Root {
4096      public:
4097        int  a_value;
4098        int  b_value;
4099        virtual int Get_Value ();
4100        Root();              // Default constructor
4101        Root(int v);         // 1st non-default constructor
4102        Root(int v, int w);  // 2nd non-default constructor
4103      };
4105 For this purpose we can write the following package spec (further
4106 information on how to build this spec is available in
4107 :ref:`Interfacing_with_C++_at_the_Class_Level` and
4108 :ref:`Generating_Ada_Bindings_for_C_and_C++_headers`).
4110 .. code-block:: ada
4112      with Interfaces.C; use Interfaces.C;
4113      package Pkg_Root is
4114        type Root is tagged limited record
4115           A_Value : int;
4116           B_Value : int;
4117        end record;
4118        pragma Import (CPP, Root);
4120        function Get_Value (Obj : Root) return int;
4121        pragma Import (CPP, Get_Value);
4123        function Constructor return Root;
4124        pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
4126        function Constructor (v : Integer) return Root;
4127        pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
4129        function Constructor (v, w : Integer) return Root;
4130        pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
4131      end Pkg_Root;
4133 On the Ada side the constructor is represented by a function (whose
4134 name is arbitrary) that returns the classwide type corresponding to
4135 the imported C++ class. Although the constructor is described as a
4136 function, it is typically a procedure with an extra implicit argument
4137 (the object being initialized) at the implementation level. GNAT
4138 issues the appropriate call, whatever it is, to get the object
4139 properly initialized.
4141 Constructors can only appear in the following contexts:
4143 * On the right side of an initialization of an object of type ``T``.
4144 * On the right side of an initialization of a record component of type ``T``.
4145 * In an Ada 2005 limited aggregate.
4146 * In an Ada 2005 nested limited aggregate.
4147 * In an Ada 2005 limited aggregate that initializes an object built in
4148   place by an extended return statement.
4150 In a declaration of an object whose type is a class imported from C++,
4151 either the default C++ constructor is implicitly called by GNAT, or
4152 else the required C++ constructor must be explicitly called in the
4153 expression that initializes the object. For example:
4155 .. code-block:: ada
4157      Obj1 : Root;
4158      Obj2 : Root := Constructor;
4159      Obj3 : Root := Constructor (v => 10);
4160      Obj4 : Root := Constructor (30, 40);
4162 The first two declarations are equivalent: in both cases the default C++
4163 constructor is invoked (in the former case the call to the constructor is
4164 implicit, and in the latter case the call is explicit in the object
4165 declaration). ``Obj3`` is initialized by the C++ non-default constructor
4166 that takes an integer argument, and ``Obj4`` is initialized by the
4167 non-default C++ constructor that takes two integers.
4169 Let us derive the imported C++ class in the Ada side. For example:
4171 .. code-block:: ada
4173      type DT is new Root with record
4174         C_Value : Natural := 2009;
4175      end record;
4177 In this case the components DT inherited from the C++ side must be
4178 initialized by a C++ constructor, and the additional Ada components
4179 of type DT are initialized by GNAT. The initialization of such an
4180 object is done either by default, or by means of a function returning
4181 an aggregate of type DT, or by means of an extension aggregate.
4183 .. code-block:: ada
4185      Obj5 : DT;
4186      Obj6 : DT := Function_Returning_DT (50);
4187      Obj7 : DT := (Constructor (30,40) with C_Value => 50);
4189 The declaration of ``Obj5`` invokes the default constructors: the
4190 C++ default constructor of the parent type takes care of the initialization
4191 of the components inherited from Root, and GNAT takes care of the default
4192 initialization of the additional Ada components of type DT (that is,
4193 ``C_Value`` is initialized to value 2009). The order of invocation of
4194 the constructors is consistent with the order of elaboration required by
4195 Ada and C++. That is, the constructor of the parent type is always called
4196 before the constructor of the derived type.
4198 Let us now consider a record that has components whose type is imported
4199 from C++. For example:
4201 .. code-block:: ada
4203      type Rec1 is limited record
4204         Data1 : Root := Constructor (10);
4205         Value : Natural := 1000;
4206      end record;
4208      type Rec2 (D : Integer := 20) is limited record
4209         Rec   : Rec1;
4210         Data2 : Root := Constructor (D, 30);
4211      end record;
4213 The initialization of an object of type ``Rec2`` will call the
4214 non-default C++ constructors specified for the imported components.
4215 For example:
4217 .. code-block:: ada
4219      Obj8 : Rec2 (40);
4221 Using Ada 2005 we can use limited aggregates to initialize an object
4222 invoking C++ constructors that differ from those specified in the type
4223 declarations. For example:
4225 .. code-block:: ada
4227      Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
4228                              others => <>),
4229                      others => <>);
4231 The above declaration uses an Ada 2005 limited aggregate to
4232 initialize ``Obj9``, and the C++ constructor that has two integer
4233 arguments is invoked to initialize the ``Data1`` component instead
4234 of the constructor specified in the declaration of type ``Rec1``. In
4235 Ada 2005 the box in the aggregate indicates that unspecified components
4236 are initialized using the expression (if any) available in the component
4237 declaration. That is, in this case discriminant ``D`` is initialized
4238 to value ``20``, ``Value`` is initialized to value 1000, and the
4239 non-default C++ constructor that handles two integers takes care of
4240 initializing component ``Data2`` with values ``20,30``.
4242 In Ada 2005 we can use the extended return statement to build the Ada
4243 equivalent to C++ non-default constructors. For example:
4245 .. code-block:: ada
4247      function Constructor (V : Integer) return Rec2 is
4248      begin
4249         return Obj : Rec2 := (Rec => (Data1  => Constructor (V, 20),
4250                                       others => <>),
4251                               others => <>) do
4252            --  Further actions required for construction of
4253            --  objects of type Rec2
4254            ...
4255         end record;
4256      end Constructor;
4258 In this example the extended return statement construct is used to
4259 build in place the returned object whose components are initialized
4260 by means of a limited aggregate. Any further action associated with
4261 the constructor can be placed inside the construct.
4263 .. _Interfacing_with_C++_at_the_Class_Level:
4265 Interfacing with C++ at the Class Level
4266 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4268 In this section we demonstrate the GNAT features for interfacing with
4269 C++ by means of an example making use of Ada 2005 abstract interface
4270 types. This example consists of a classification of animals; classes
4271 have been used to model our main classification of animals, and
4272 interfaces provide support for the management of secondary
4273 classifications. We first demonstrate a case in which the types and
4274 constructors are defined on the C++ side and imported from the Ada
4275 side, and latter the reverse case.
4277 The root of our derivation will be the ``Animal`` class, with a
4278 single private attribute (the ``Age`` of the animal), a constructor,
4279 and two public primitives to set and get the value of this attribute.
4281 .. code-block:: cpp
4283      class Animal {
4284       public:
4285         virtual void Set_Age (int New_Age);
4286         virtual int Age ();
4287         Animal() {Age_Count = 0;};
4288       private:
4289         int Age_Count;
4290      };
4292 Abstract interface types are defined in C++ by means of classes with pure
4293 virtual functions and no data members. In our example we will use two
4294 interfaces that provide support for the common management of ``Carnivore``
4295 and ``Domestic`` animals:
4297 .. code-block:: cpp
4299      class Carnivore {
4300      public:
4301         virtual int Number_Of_Teeth () = 0;
4302      };
4304      class Domestic {
4305      public:
4306         virtual void Set_Owner (char* Name) = 0;
4307      };
4309 Using these declarations, we can now say that a ``Dog`` is an animal that is
4310 both Carnivore and Domestic, that is:
4312 .. code-block:: cpp
4314      class Dog : Animal, Carnivore, Domestic {
4315       public:
4316         virtual int  Number_Of_Teeth ();
4317         virtual void Set_Owner (char* Name);
4319         Dog(); // Constructor
4320       private:
4321         int  Tooth_Count;
4322         char *Owner;
4323      };
4325 In the following examples we will assume that the previous declarations are
4326 located in a file named :file:`animals.h`. The following package demonstrates
4327 how to import these C++ declarations from the Ada side:
4329 .. code-block:: ada
4331      with Interfaces.C.Strings; use Interfaces.C.Strings;
4332      package Animals is
4333        type Carnivore is limited interface;
4334        pragma Convention (C_Plus_Plus, Carnivore);
4335        function Number_Of_Teeth (X : Carnivore)
4336           return Natural is abstract;
4338        type Domestic is limited interface;
4339        pragma Convention (C_Plus_Plus, Domestic);
4340        procedure Set_Owner
4341          (X    : in out Domestic;
4342           Name : Chars_Ptr) is abstract;
4344        type Animal is tagged limited record
4345          Age : Natural;
4346        end record;
4347        pragma Import (C_Plus_Plus, Animal);
4349        procedure Set_Age (X : in out Animal; Age : Integer);
4350        pragma Import (C_Plus_Plus, Set_Age);
4352        function Age (X : Animal) return Integer;
4353        pragma Import (C_Plus_Plus, Age);
4355        function New_Animal return Animal;
4356        pragma CPP_Constructor (New_Animal);
4357        pragma Import (CPP, New_Animal, "_ZN6AnimalC1Ev");
4359        type Dog is new Animal and Carnivore and Domestic with record
4360          Tooth_Count : Natural;
4361          Owner       : Chars_Ptr;
4362        end record;
4363        pragma Import (C_Plus_Plus, Dog);
4365        function Number_Of_Teeth (A : Dog) return Natural;
4366        pragma Import (C_Plus_Plus, Number_Of_Teeth);
4368        procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
4369        pragma Import (C_Plus_Plus, Set_Owner);
4371        function New_Dog return Dog;
4372        pragma CPP_Constructor (New_Dog);
4373        pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
4374      end Animals;
4376 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
4377 interfacing with these C++ classes is easy. The only requirement is that all
4378 the primitives and components must be declared exactly in the same order in
4379 the two languages.
4381 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
4382 means of a ``pragma Convention (C_Plus_Plus)``, the convention used to pass
4383 the arguments to the called primitives will be the same as for C++. For the
4384 imported classes we use ``pragma Import`` with convention ``C_Plus_Plus``
4385 to indicate that they have been defined on the C++ side; this is required
4386 because the dispatch table associated with these tagged types will be built
4387 in the C++ side and therefore will not contain the predefined Ada primitives
4388 which Ada would otherwise expect.
4390 As the reader can see there is no need to indicate the C++ mangled names
4391 associated with each subprogram because it is assumed that all the calls to
4392 these primitives will be dispatching calls. The only exception is the
4393 constructor, which must be registered with the compiler by means of
4394 ``pragma CPP_Constructor`` and needs to provide its associated C++
4395 mangled name because the Ada compiler generates direct calls to it.
4397 With the above packages we can now declare objects of type Dog on the Ada side
4398 and dispatch calls to the corresponding subprograms on the C++ side. We can
4399 also extend the tagged type Dog with further fields and primitives, and
4400 override some of its C++ primitives on the Ada side. For example, here we have
4401 a type derivation defined on the Ada side that inherits all the dispatching
4402 primitives of the ancestor from the C++ side.
4404 .. code-block:: ada
4406      with Animals; use Animals;
4407      package Vaccinated_Animals is
4408        type Vaccinated_Dog is new Dog with null record;
4409        function Vaccination_Expired (A : Vaccinated_Dog) return Boolean;
4410      end Vaccinated_Animals;
4412 It is important to note that, because of the ABI compatibility, the programmer
4413 does not need to add any further information to indicate either the object
4414 layout or the dispatch table entry associated with each dispatching operation.
4416 Now let us define all the types and constructors on the Ada side and export
4417 them to C++, using the same hierarchy of our previous example:
4419 .. code-block:: ada
4421      with Interfaces.C.Strings;
4422      use Interfaces.C.Strings;
4423      package Animals is
4424        type Carnivore is limited interface;
4425        pragma Convention (C_Plus_Plus, Carnivore);
4426        function Number_Of_Teeth (X : Carnivore)
4427           return Natural is abstract;
4429        type Domestic is limited interface;
4430        pragma Convention (C_Plus_Plus, Domestic);
4431        procedure Set_Owner
4432          (X    : in out Domestic;
4433           Name : Chars_Ptr) is abstract;
4435        type Animal is tagged record
4436          Age : Natural;
4437        end record;
4438        pragma Convention (C_Plus_Plus, Animal);
4440        procedure Set_Age (X : in out Animal; Age : Integer);
4441        pragma Export (C_Plus_Plus, Set_Age);
4443        function Age (X : Animal) return Integer;
4444        pragma Export (C_Plus_Plus, Age);
4446        function New_Animal return Animal'Class;
4447        pragma Export (C_Plus_Plus, New_Animal);
4449        type Dog is new Animal and Carnivore and Domestic with record
4450          Tooth_Count : Natural;
4451          Owner       : String (1 .. 30);
4452        end record;
4453        pragma Convention (C_Plus_Plus, Dog);
4455        function Number_Of_Teeth (A : Dog) return Natural;
4456        pragma Export (C_Plus_Plus, Number_Of_Teeth);
4458        procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
4459        pragma Export (C_Plus_Plus, Set_Owner);
4461        function New_Dog return Dog'Class;
4462        pragma Export (C_Plus_Plus, New_Dog);
4463      end Animals;
4465 Compared with our previous example the only differences are the use of
4466 ``pragma Convention`` (instead of ``pragma Import``), and the use of
4467 ``pragma Export`` to indicate to the GNAT compiler that the primitives will
4468 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
4469 nothing else to be done; as explained above, the only requirement is that all
4470 the primitives and components are declared in exactly the same order.
4472 For completeness, let us see a brief C++ main program that uses the
4473 declarations available in :file:`animals.h` (presented in our first example) to
4474 import and use the declarations from the Ada side, properly initializing and
4475 finalizing the Ada run-time system along the way:
4477 .. code-block:: cpp
4479      #include "animals.h"
4480      #include <iostream>
4481      using namespace std;
4483      void Check_Carnivore (Carnivore *obj) {...}
4484      void Check_Domestic (Domestic *obj)   {...}
4485      void Check_Animal (Animal *obj)       {...}
4486      void Check_Dog (Dog *obj)             {...}
4488      extern "C" {
4489        void adainit (void);
4490        void adafinal (void);
4491        Dog* new_dog ();
4492      }
4494      void test ()
4495      {
4496        Dog *obj = new_dog();  // Ada constructor
4497        Check_Carnivore (obj); // Check secondary DT
4498        Check_Domestic (obj);  // Check secondary DT
4499        Check_Animal (obj);    // Check primary DT
4500        Check_Dog (obj);       // Check primary DT
4501      }
4503      int main ()
4504      {
4505        adainit ();  test();  adafinal ();
4506        return 0;
4507      }
4509 .. _Generating_Ada_Bindings_for_C_and_C++_headers:
4511 Generating Ada Bindings for C and C++ headers
4512 ---------------------------------------------
4514 .. index:: Binding generation (for C and C++ headers)
4515 .. index:: C headers (binding generation)
4516 .. index:: C++ headers (binding generation)
4518 GNAT includes a binding generator for C and C++ headers which is
4519 intended to do 95% of the tedious work of generating Ada specs from C
4520 or C++ header files.
4522 Note that this capability is not intended to generate 100% correct Ada specs,
4523 and will is some cases require manual adjustments, although it can often
4524 be used out of the box in practice.
4526 Some of the known limitations include:
4528 * only very simple character constant macros are translated into Ada
4529   constants. Function macros (macros with arguments) are partially translated
4530   as comments, to be completed manually if needed.
4531 * some extensions (e.g. vector types) are not supported
4532 * pointers to pointers or complex structures are mapped to System.Address
4533 * identifiers with identical name (except casing) will generate compilation
4534   errors (e.g. ``shm_get`` vs ``SHM_GET``).
4536 The code is generated using Ada 2012 syntax, which makes it easier to interface
4537 with other languages. In most cases you can still use the generated binding
4538 even if your code is compiled using earlier versions of Ada (e.g. ``-gnat95``).
4540 .. _Running_the_binding_generator:
4542 Running the Binding Generator
4543 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4545 The binding generator is part of the ``gcc`` compiler and can be
4546 invoked via the :switch:`-fdump-ada-spec` switch, which will generate Ada
4547 spec files for the header files specified on the command line, and all
4548 header files needed by these files transitively. For example:
4550 .. code-block:: sh
4552       $ g++ -c -fdump-ada-spec -C /usr/include/time.h
4553       $ gcc -c *.ads
4555 will generate, under GNU/Linux, the following files: :file:`time_h.ads`,
4556 :file:`bits_time_h.ads`, :file:`stddef_h.ads`, :file:`bits_types_h.ads` which
4557 correspond to the files :file:`/usr/include/time.h`,
4558 :file:`/usr/include/bits/time.h`, etc..., and will then compile these Ada specs
4559 in Ada 2005 mode.
4561 The :switch:`-C` switch tells ``gcc`` to extract comments from headers,
4562 and will attempt to generate corresponding Ada comments.
4564 If you want to generate a single Ada file and not the transitive closure, you
4565 can use instead the :switch:`-fdump-ada-spec-slim` switch.
4567 You can optionally specify a parent unit, of which all generated units will
4568 be children, using :switch:`-fada-spec-parent={unit}`.
4570 Note that we recommend when possible to use the *g++* driver to
4571 generate bindings, even for most C headers, since this will in general
4572 generate better Ada specs. For generating bindings for C++ headers, it is
4573 mandatory to use the *g++* command, or *gcc -x c++* which
4574 is equivalent in this case. If *g++* cannot work on your C headers
4575 because of incompatibilities between C and C++, then you can fallback to
4576 ``gcc`` instead.
4578 For an example of better bindings generated from the C++ front-end,
4579 the name of the parameters (when available) are actually ignored by the C
4580 front-end. Consider the following C header:
4582 .. code-block:: c
4584      extern void foo (int variable);
4586 with the C front-end, ``variable`` is ignored, and the above is handled as:
4588 .. code-block:: c
4590      extern void foo (int);
4592 generating a generic:
4594 .. code-block:: ada
4596      procedure foo (param1 : int);
4598 with the C++ front-end, the name is available, and we generate:
4600 .. code-block:: ada
4602      procedure foo (variable : int);
4604 In some cases, the generated bindings will be more complete or more meaningful
4605 when defining some macros, which you can do via the :switch:`-D` switch. This
4606 is for example the case with :file:`Xlib.h` under GNU/Linux:
4608 .. code-block:: sh
4610       $ g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
4612 The above will generate more complete bindings than a straight call without
4613 the :switch:`-DXLIB_ILLEGAL_ACCESS` switch.
4615 In other cases, it is not possible to parse a header file in a stand-alone
4616 manner, because other include files need to be included first. In this
4617 case, the solution is to create a small header file including the needed
4618 ``#include`` and possible ``#define`` directives. For example, to
4619 generate Ada bindings for :file:`readline/readline.h`, you need to first
4620 include :file:`stdio.h`, so you can create a file with the following two
4621 lines in e.g. :file:`readline1.h`:
4623 .. code-block:: cpp
4625       #include <stdio.h>
4626       #include <readline/readline.h>
4628 and then generate Ada bindings from this file:
4630 .. code-block:: sh
4632       $ g++ -c -fdump-ada-spec readline1.h
4635 .. _Generating_bindings_for_C++_headers:
4637 Generating Bindings for C++ Headers
4638 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4640 Generating bindings for C++ headers is done using the same options, always
4641 with the *g++* compiler. Note that generating Ada spec from C++ headers is a
4642 much more complex job and support for C++ headers is much more limited that
4643 support for C headers. As a result, you will need to modify the resulting
4644 bindings by hand more extensively when using C++ headers.
4646 In this mode, C++ classes will be mapped to Ada tagged types, constructors
4647 will be mapped using the ``CPP_Constructor`` pragma, and when possible,
4648 multiple inheritance of abstract classes will be mapped to Ada interfaces
4649 (see the *Interfacing to C++* section in the :title:`GNAT Reference Manual`
4650 for additional information on interfacing to C++).
4652 For example, given the following C++ header file:
4654 .. code-block:: cpp
4656        class Carnivore {
4657        public:
4658           virtual int Number_Of_Teeth () = 0;
4659        };
4661        class Domestic {
4662        public:
4663           virtual void Set_Owner (char* Name) = 0;
4664        };
4666        class Animal {
4667        public:
4668          int Age_Count;
4669          virtual void Set_Age (int New_Age);
4670        };
4672        class Dog : Animal, Carnivore, Domestic {
4673         public:
4674          int  Tooth_Count;
4675          char *Owner;
4677          virtual int  Number_Of_Teeth ();
4678          virtual void Set_Owner (char* Name);
4680          Dog();
4681        };
4683 The corresponding Ada code is generated:
4685 .. code-block:: ada
4687          package Class_Carnivore is
4688            type Carnivore is limited interface;
4689            pragma Import (CPP, Carnivore);
4691            function Number_Of_Teeth (this : access Carnivore) return int is abstract;
4692          end;
4693          use Class_Carnivore;
4695          package Class_Domestic is
4696            type Domestic is limited interface;
4697            pragma Import (CPP, Domestic);
4699            procedure Set_Owner
4700              (this : access Domestic;
4701               Name : Interfaces.C.Strings.chars_ptr) is abstract;
4702          end;
4703          use Class_Domestic;
4705          package Class_Animal is
4706            type Animal is tagged limited record
4707              Age_Count : aliased int;
4708            end record;
4709            pragma Import (CPP, Animal);
4711            procedure Set_Age (this : access Animal; New_Age : int);
4712            pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
4713          end;
4714          use Class_Animal;
4716          package Class_Dog is
4717            type Dog is new Animal and Carnivore and Domestic with record
4718              Tooth_Count : aliased int;
4719              Owner : Interfaces.C.Strings.chars_ptr;
4720            end record;
4721            pragma Import (CPP, Dog);
4723            function Number_Of_Teeth (this : access Dog) return int;
4724            pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
4726            procedure Set_Owner
4727              (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
4728            pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
4730            function New_Dog return Dog;
4731            pragma CPP_Constructor (New_Dog);
4732            pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
4733          end;
4734          use Class_Dog;
4737 .. _Switches_for_Ada_Binding_Generation:
4739 Switches
4740 ^^^^^^^^
4742 .. index:: -fdump-ada-spec (gcc)
4744 :switch:`-fdump-ada-spec`
4745   Generate Ada spec files for the given header files transitively (including
4746   all header files that these headers depend upon).
4748 .. index:: -fdump-ada-spec-slim (gcc)
4750 :switch:`-fdump-ada-spec-slim`
4751   Generate Ada spec files for the header files specified on the command line
4752   only.
4754 .. index:: -fada-spec-parent (gcc)
4756 :switch:`-fada-spec-parent={unit}`
4757   Specifies that all files generated by :switch:`-fdump-ada-spec` are
4758   to be child units of the specified parent unit.
4760 .. index:: -C (gcc)
4762 :switch:`-C`
4763   Extract comments from headers and generate Ada comments in the Ada spec files.
4765 .. _Generating_C_Headers_for_Ada_Specifications:
4767 Generating C Headers for Ada Specifications
4768 -------------------------------------------
4770 .. index:: Binding generation (for Ada specs)
4771 .. index:: C headers (binding generation)
4773 GNAT includes a C header generator for Ada specifications which supports
4774 Ada types that have a direct mapping to C types. This includes in particular
4775 support for:
4777 * Scalar types
4778 * Constrained arrays
4779 * Records (untagged)
4780 * Composition of the above types
4781 * Constant declarations
4782 * Object declarations
4783 * Subprogram declarations
4785 Running the C Header Generator
4786 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4788 The C header generator is part of the GNAT compiler and can be invoked via
4789 the :switch:`-gnatceg` combination of switches, which will generate a :file:`.h`
4790 file corresponding to the given input file (Ada spec or body). Note that
4791 only spec files are processed in any case, so giving a spec or a body file
4792 as input is equivalent. For example:
4794 .. code-block:: sh
4796    $ gcc -c -gnatceg pack1.ads
4798 will generate a self-contained file called :file:`pack1.h` including
4799 common definitions from the Ada Standard package, followed by the
4800 definitions included in :file:`pack1.ads`, as well as all the other units
4801 withed by this file.
4803 For instance, given the following Ada files:
4805 .. code-block:: ada
4807    package Pack2 is
4808       type Int is range 1 .. 10;
4809    end Pack2;
4811 .. code-block:: ada
4813    with Pack2;
4815    package Pack1 is
4816       type Rec is record
4817          Field1, Field2 : Pack2.Int;
4818       end record;
4820       Global : Rec := (1, 2);
4822       procedure Proc1 (R : Rec);
4823       procedure Proc2 (R : in out Rec);
4824    end Pack1;
4826 The above ``gcc`` command will generate the following :file:`pack1.h` file:
4828 .. code-block:: c
4830    /* Standard definitions skipped */
4831    #ifndef PACK2_ADS
4832    #define PACK2_ADS
4833    typedef short_short_integer pack2__TintB;
4834    typedef pack2__TintB pack2__int;
4835    #endif /* PACK2_ADS */
4837    #ifndef PACK1_ADS
4838    #define PACK1_ADS
4839    typedef struct _pack1__rec {
4840      pack2__int field1;
4841      pack2__int field2;
4842    } pack1__rec;
4843    extern pack1__rec pack1__global;
4844    extern void pack1__proc1(const pack1__rec r);
4845    extern void pack1__proc2(pack1__rec *r);
4846    #endif /* PACK1_ADS */
4848 You can then ``include`` :file:`pack1.h` from a C source file and use the types,
4849 call subprograms, reference objects, and constants.
4851 .. _GNAT_and_Other_Compilation_Models:
4853 GNAT and Other Compilation Models
4854 =================================
4856 This section compares the GNAT model with the approaches taken in
4857 other environents, first the C/C++ model and then the mechanism that
4858 has been used in other Ada systems, in particular those traditionally
4859 used for Ada 83.
4861 .. _Comparison_between_GNAT_and_C/C++_Compilation_Models:
4863 Comparison between GNAT and C/C++ Compilation Models
4864 ----------------------------------------------------
4866 The GNAT model of compilation is close to the C and C++ models. You can
4867 think of Ada specs as corresponding to header files in C. As in C, you
4868 don't need to compile specs; they are compiled when they are used. The
4869 Ada |with| is similar in effect to the ``#include`` of a C
4870 header.
4872 One notable difference is that, in Ada, you may compile specs separately
4873 to check them for semantic and syntactic accuracy. This is not always
4874 possible with C headers because they are fragments of programs that have
4875 less specific syntactic or semantic rules.
4877 The other major difference is the requirement for running the binder,
4878 which performs two important functions. First, it checks for
4879 consistency. In C or C++, the only defense against assembling
4880 inconsistent programs lies outside the compiler, in a makefile, for
4881 example. The binder satisfies the Ada requirement that it be impossible
4882 to construct an inconsistent program when the compiler is used in normal
4883 mode.
4885 .. index:: Elaboration order control
4887 The other important function of the binder is to deal with elaboration
4888 issues. There are also elaboration issues in C++ that are handled
4889 automatically. This automatic handling has the advantage of being
4890 simpler to use, but the C++ programmer has no control over elaboration.
4891 Where ``gnatbind`` might complain there was no valid order of
4892 elaboration, a C++ compiler would simply construct a program that
4893 malfunctioned at run time.
4895 .. _Comparison_between_GNAT_and_Conventional_Ada_Library_Models:
4897 Comparison between GNAT and Conventional Ada Library Models
4898 -----------------------------------------------------------
4900 This section is intended for Ada programmers who have
4901 used an Ada compiler implementing the traditional Ada library
4902 model, as described in the Ada Reference Manual.
4904 .. index:: GNAT library
4906 In GNAT, there is no 'library' in the normal sense. Instead, the set of
4907 source files themselves acts as the library. Compiling Ada programs does
4908 not generate any centralized information, but rather an object file and
4909 a ALI file, which are of interest only to the binder and linker.
4910 In a traditional system, the compiler reads information not only from
4911 the source file being compiled, but also from the centralized library.
4912 This means that the effect of a compilation depends on what has been
4913 previously compiled. In particular:
4915 * When a unit is |withed|, the unit seen by the compiler corresponds
4916   to the version of the unit most recently compiled into the library.
4918 * Inlining is effective only if the necessary body has already been
4919   compiled into the library.
4921 * Compiling a unit may obsolete other units in the library.
4923 In GNAT, compiling one unit never affects the compilation of any other
4924 units because the compiler reads only source files. Only changes to source
4925 files can affect the results of a compilation. In particular:
4927 * When a unit is |withed|, the unit seen by the compiler corresponds
4928   to the source version of the unit that is currently accessible to the
4929   compiler.
4931   .. index:: Inlining
4933 * Inlining requires the appropriate source files for the package or
4934   subprogram bodies to be available to the compiler. Inlining is always
4935   effective, independent of the order in which units are compiled.
4937 * Compiling a unit never affects any other compilations. The editing of
4938   sources may cause previous compilations to be out of date if they
4939   depended on the source file being modified.
4941 The most important result of these differences is that order of compilation
4942 is never significant in GNAT. There is no situation in which one is
4943 required to do one compilation before another. What shows up as order of
4944 compilation requirements in the traditional Ada library becomes, in
4945 GNAT, simple source dependencies; in other words, there is only a set
4946 of rules saying what source files must be present when a file is
4947 compiled.
4950 .. _Using_GNAT_Files_with_External_Tools:
4952 Using GNAT Files with External Tools
4953 ====================================
4955 This section explains how files that are produced by GNAT may be
4956 used with tools designed for other languages.
4959 .. _Using_Other_Utility_Programs_with_GNAT:
4961 Using Other Utility Programs with GNAT
4962 --------------------------------------
4964 The object files generated by GNAT are in standard system format and in
4965 particular the debugging information uses this format. This means
4966 programs generated by GNAT can be used with existing utilities that
4967 depend on these formats.
4969 In general, any utility program that works with C will also often work with
4970 Ada programs generated by GNAT. This includes software utilities such as
4971 gprof (a profiling program), gdb (the FSF debugger), and utilities such
4972 as Purify.
4975 .. _The_External_Symbol_Naming_Scheme_of_GNAT:
4977 The External Symbol Naming Scheme of GNAT
4978 -----------------------------------------
4980 In order to interpret the output from GNAT, when using tools that are
4981 originally intended for use with other languages, it is useful to
4982 understand the conventions used to generate link names from the Ada
4983 entity names.
4985 All link names are in all lowercase letters. With the exception of library
4986 procedure names, the mechanism used is simply to use the full expanded
4987 Ada name with dots replaced by double underscores. For example, suppose
4988 we have the following package spec:
4990 .. code-block:: ada
4992      package QRS is
4993         MN : Integer;
4994      end QRS;
4996 .. index:: pragma Export
4998 The variable ``MN`` has a full expanded Ada name of ``QRS.MN``, so
4999 the corresponding link name is ``qrs__mn``.
5000 Of course if a ``pragma Export`` is used this may be overridden:
5002 .. code-block:: ada
5004      package Exports is
5005         Var1 : Integer;
5006         pragma Export (Var1, C, External_Name => "var1_name");
5007         Var2 : Integer;
5008         pragma Export (Var2, C, Link_Name => "var2_link_name");
5009      end Exports;
5011 In this case, the link name for ``Var1`` is whatever link name the
5012 C compiler would assign for the C function ``var1_name``. This typically
5013 would be either ``var1_name`` or ``_var1_name``, depending on operating
5014 system conventions, but other possibilities exist. The link name for
5015 ``Var2`` is ``var2_link_name``, and this is not operating system
5016 dependent.
5018 One exception occurs for library level procedures. A potential ambiguity
5019 arises between the required name ``_main`` for the C main program,
5020 and the name we would otherwise assign to an Ada library level procedure
5021 called ``Main`` (which might well not be the main program).
5023 To avoid this ambiguity, we attach the prefix ``_ada_`` to such
5024 names. So if we have a library level procedure such as:
5026 .. code-block:: ada
5028      procedure Hello (S : String);
5030 the external name of this procedure will be ``_ada_hello``.