1 .. |with| replace:: *with*
2 .. |withs| replace:: *with*\ s
3 .. |withed| replace:: *with*\ ed
4 .. |withing| replace:: *with*\ ing
6 .. -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
9 .. _The_GNAT_Compilation_Model:
11 **************************
12 The GNAT Compilation Model
13 **************************
15 .. index:: ! GNAT compilation model
17 .. index:: Compilation model
19 This chapter describes the compilation model used by GNAT. Although
20 similar to that used by other languages such as C and C++, this model
21 is substantially different from the traditional Ada compilation models,
22 which are based on a centralized program library. The chapter covers
23 the following material:
25 * Topics related to source file makeup and naming
27 * :ref:`Source_Representation`
28 * :ref:`Foreign_Language_Representation`
29 * :ref:`File_Naming_Topics_and_Utilities`
31 * :ref:`Configuration_Pragmas`
32 * :ref:`Generating_Object_Files`
33 * :ref:`Source_Dependencies`
34 * :ref:`The_Ada_Library_Information_Files`
35 * :ref:`Binding_an_Ada_Program`
36 * :ref:`GNAT_and_Libraries`
37 * :ref:`Conditional_Compilation`
38 * :ref:`Mixed_Language_Programming`
39 * :ref:`GNAT_and_Other_Compilation_Models`
40 * :ref:`Using_GNAT_Files_with_External_Tools`
43 .. _Source_Representation:
50 .. index:: VT, HT, CR, LF, FF
52 Ada source programs are represented in standard text files, using
53 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
54 7-bit ASCII set, plus additional characters used for
55 representing foreign languages (see :ref:`Foreign_Language_Representation`
56 for support of non-USA character sets). The format effector characters
57 are represented using their standard ASCII encodings, as follows:
59 =========== ======================= =========
61 ----------- ----------------------- ---------
62 :kbd:`VT` Vertical tab `16#0B#`
63 :kbd:`HT` Horizontal tab `16#09#`
64 :kbd:`CR` Carriage return `16#0D#`
65 :kbd:`LF` Line feed `16#0A#`
66 :kbd:`FF` Form feed `16#0C#`
67 =========== ======================= =========
69 Source files are in standard text file format. In addition, GNAT will
70 recognize a wide variety of stream formats, in which the end of
71 physical lines is marked by any of the following sequences:
72 `LF`, `CR`, `CR-LF`, or `LF-CR`. This is useful
73 in accommodating files that are imported from other operating systems.
75 .. index:: pair: End of source file; Source file, end
77 .. index:: SUB (control character)
79 The end of a source file is normally represented by the physical end of
80 file. However, the control character `16#1A#` (:kbd:`SUB`) is also
81 recognized as signalling the end of the source file. Again, this is
82 provided for compatibility with other operating systems where this
83 code is used to represent the end of file.
85 .. index:: spec (definition), compilation (definition)
87 Each file contains a single Ada compilation unit, including any pragmas
88 associated with the unit. For example, this means you must place a
89 package declaration (a package `spec`) and the corresponding body in
90 separate files. An Ada `compilation` (which is a sequence of
91 compilation units) is represented using a sequence of files. Similarly,
92 you will place each subunit or child unit in a separate file.
94 .. _Foreign_Language_Representation:
96 Foreign Language Representation
97 ===============================
99 GNAT supports the standard character sets defined in Ada as well as
100 several other non-standard character sets for use in localized versions
101 of the compiler (:ref:`Character_Set_Control`).
110 The basic character set is Latin-1. This character set is defined by ISO
111 standard 8859, part 1. The lower half (character codes `16#00#`
112 ... `16#7F#)` is identical to standard ASCII coding, but the upper
113 half is used to represent additional characters. These include extended letters
114 used by European languages, such as French accents, the vowels with umlauts
115 used in German, and the extra letter A-ring used in Swedish.
117 .. index:: Ada.Characters.Latin_1
119 For a complete list of Latin-1 codes and their encodings, see the source
120 file of library unit `Ada.Characters.Latin_1` in file
121 :file:`a-chlat1.ads`.
122 You may use any of these extended characters freely in character or
123 string literals. In addition, the extended characters that represent
124 letters can be used in identifiers.
126 .. _Other_8-Bit_Codes:
131 GNAT also supports several other 8-bit coding schemes:
135 .. index:: ISO 8859-2
137 *ISO 8859-2 (Latin-2)*
138 Latin-2 letters allowed in identifiers, with uppercase and lowercase
142 .. index:: ISO 8859-3
144 *ISO 8859-3 (Latin-3)*
145 Latin-3 letters allowed in identifiers, with uppercase and lowercase
150 .. index:: ISO 8859-4
152 *ISO 8859-4 (Latin-4)*
153 Latin-4 letters allowed in identifiers, with uppercase and lowercase
157 .. index:: ISO 8859-5
160 *ISO 8859-5 (Cyrillic)*
161 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
162 lowercase equivalence.
164 .. index:: ISO 8859-15
167 *ISO 8859-15 (Latin-9)*
168 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
169 lowercase equivalence
171 .. index:: code page 437 (IBM PC)
173 *IBM PC (code page 437)*
174 This code page is the normal default for PCs in the U.S. It corresponds
175 to the original IBM PC character set. This set has some, but not all, of
176 the extended Latin-1 letters, but these letters do not have the same
177 encoding as Latin-1. In this mode, these letters are allowed in
178 identifiers with uppercase and lowercase equivalence.
180 .. index:: code page 850 (IBM PC)
182 *IBM PC (code page 850)*
183 This code page is a modification of 437 extended to include all the
184 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
185 mode, all these letters are allowed in identifiers with uppercase and
186 lowercase equivalence.
190 Any character in the range 80-FF allowed in identifiers, and all are
191 considered distinct. In other words, there are no uppercase and lowercase
192 equivalences in this range. This is useful in conjunction with
193 certain encoding schemes used for some foreign character sets (e.g.,
194 the typical method of representing Chinese characters on the PC).
198 No upper-half characters in the range 80-FF are allowed in identifiers.
199 This gives Ada 83 compatibility for identifier names.
201 For precise data on the encodings permitted, and the uppercase and lowercase
202 equivalences that are recognized, see the file :file:`csets.adb` in
203 the GNAT compiler sources. You will need to obtain a full source release
204 of GNAT to obtain this file.
206 .. _Wide_Character_Encodings:
208 Wide_Character Encodings
209 ------------------------
211 GNAT allows wide character codes to appear in character and string
212 literals, and also optionally in identifiers, by means of the following
213 possible encoding schemes:
216 In this encoding, a wide character is represented by the following five
221 where `a`, `b`, `c`, `d` are the four hexadecimal
222 characters (using uppercase letters) of the wide character code. For
223 example, ESC A345 is used to represent the wide character with code
225 This scheme is compatible with use of the full Wide_Character set.
228 .. index:: Upper-Half Coding
230 The wide character with encoding `16#abcd#` where the upper bit is on
231 (in other words, 'a' is in the range 8-F) is represented as two bytes,
232 `16#ab#` and `16#cd#`. The second byte cannot be a format control
233 character, but is not required to be in the upper half. This method can
234 be also used for shift-JIS or EUC, where the internal coding matches the
238 .. index:: Shift JIS Coding
240 A wide character is represented by a two-character sequence,
242 `16#cd#`, with the restrictions described for upper-half encoding as
243 described above. The internal character code is the corresponding JIS
244 character according to the standard algorithm for Shift-JIS
245 conversion. Only characters defined in the JIS code set table can be
246 used with this encoding method.
250 .. index:: EUC Coding
252 A wide character is represented by a two-character sequence
254 `16#cd#`, with both characters being in the upper half. The internal
255 character code is the corresponding JIS character according to the EUC
256 encoding algorithm. Only characters defined in the JIS code set table
257 can be used with this encoding method.
261 A wide character is represented using
262 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
263 10646-1/Am.2. Depending on the character value, the representation
264 is a one, two, or three byte sequence::
266 16#0000#-16#007f#: 2#0`xxxxxxx`#
267 16#0080#-16#07ff#: 2#110`xxxxx`# 2#10`xxxxxx`#
268 16#0800#-16#ffff#: 2#1110`xxxx`# 2#10`xxxxxx`# 2#10`xxxxxx`#
270 where the `xxx` bits correspond to the left-padded bits of the
271 16-bit character value. Note that all lower half ASCII characters
272 are represented as ASCII bytes and all upper half characters and
273 other wide characters are represented as sequences of upper-half
274 (The full UTF-8 scheme allows for encoding 31-bit characters as
275 6-byte sequences, and in the following section on wide wide
276 characters, the use of these sequences is documented).
280 In this encoding, a wide character is represented by the following eight
285 where `a`, `b`, `c`, `d` are the four hexadecimal
286 characters (using uppercase letters) of the wide character code. For
287 example, ['A345'] is used to represent the wide character with code
288 `16#A345#`. It is also possible (though not required) to use the
289 Brackets coding for upper half characters. For example, the code
290 `16#A3#` can be represented as `['A3']`.
292 This scheme is compatible with use of the full Wide_Character set,
293 and is also the method used for wide character encoding in some standard
294 ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
298 Some of these coding schemes do not permit the full use of the
299 Ada character set. For example, neither Shift JIS nor EUC allow the
300 use of the upper half of the Latin-1 set.
302 .. _Wide_Wide_Character_Encodings:
304 Wide_Wide_Character Encodings
305 -----------------------------
307 GNAT allows wide wide character codes to appear in character and string
308 literals, and also optionally in identifiers, by means of the following
309 possible encoding schemes:
312 A wide character is represented using
313 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
314 10646-1/Am.2. Depending on the character value, the representation
315 of character codes with values greater than 16#FFFF# is a
316 is a four, five, or six byte sequence::
318 16#01_0000#-16#10_FFFF#: 11110xxx 10xxxxxx 10xxxxxx
320 16#0020_0000#-16#03FF_FFFF#: 111110xx 10xxxxxx 10xxxxxx
322 16#0400_0000#-16#7FFF_FFFF#: 1111110x 10xxxxxx 10xxxxxx
323 10xxxxxx 10xxxxxx 10xxxxxx
326 where the `xxx` bits correspond to the left-padded bits of the
327 32-bit character value.
330 In this encoding, a wide wide character is represented by the following ten or
331 twelve byte character sequence::
334 [ " a b c d e f g h " ]
336 where `a-h` are the six or eight hexadecimal
337 characters (using uppercase letters) of the wide wide character code. For
338 example, ["1F4567"] is used to represent the wide wide character with code
341 This scheme is compatible with use of the full Wide_Wide_Character set,
342 and is also the method used for wide wide character encoding in some standard
343 ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
346 .. _File_Naming_Topics_and_Utilities:
348 File Naming Topics and Utilities
349 ================================
351 GNAT has a default file naming scheme and also provides the user with
352 a high degree of control over how the names and extensions of the
353 source files correspond to the Ada compilation units that they contain.
356 .. _File_Naming_Rules:
361 The default file name is determined by the name of the unit that the
362 file contains. The name is formed by taking the full expanded name of
363 the unit and replacing the separating dots with hyphens and using
364 lowercase for all letters.
366 An exception arises if the file name generated by the above rules starts
367 with one of the characters
368 `a`, `g`, `i`, or `s`, and the second character is a
369 minus. In this case, the character tilde is used in place
370 of the minus. The reason for this special rule is to avoid clashes with
371 the standard names for child units of the packages System, Ada,
372 Interfaces, and GNAT, which use the prefixes
373 `s-`, `a-`, `i-`, and `g-`,
376 The file extension is :file:`.ads` for a spec and
377 :file:`.adb` for a body. The following table shows some
378 examples of these rules.
380 ============================ ===============================
381 Source File Ada Compilation Unit
382 ---------------------------- -------------------------------
383 :file:`main.ads` Main (spec)
384 :file:`main.adb` Main (body)
385 :file:`arith_functions.ads` Arith_Functions (package spec)
386 :file:`arith_functions.adb` Arith_Functions (package body)
387 :file:`func-spec.ads` Func.Spec (child package spec)
388 :file:`func-spec.adb` Func.Spec (child package body)
389 :file:`main-sub.adb` Sub (subunit of Main)
390 :file:`a~bad.adb` A.Bad (child package body)
391 ============================ ===============================
393 Following these rules can result in excessively long
394 file names if corresponding
395 unit names are long (for example, if child units or subunits are
396 heavily nested). An option is available to shorten such long file names
397 (called file name 'krunching'). This may be particularly useful when
398 programs being developed with GNAT are to be used on operating systems
399 with limited file name lengths. :ref:`Using_gnatkr`.
401 Of course, no file shortening algorithm can guarantee uniqueness over
402 all possible unit names; if file name krunching is used, it is your
403 responsibility to ensure no name clashes occur. Alternatively you
404 can specify the exact file names that you want used, as described
405 in the next section. Finally, if your Ada programs are migrating from a
406 compiler with a different naming convention, you can use the gnatchop
407 utility to produce source files that follow the GNAT naming conventions.
408 (For details see :ref:`Renaming_Files_with_gnatchop`.)
410 Note: in the case of Windows or Mac OS operating systems, case is not
411 significant. So for example on `Windows` if the canonical name is
412 `main-sub.adb`, you can use the file name :file:`Main-Sub.adb` instead.
413 However, case is significant for other operating systems, so for example,
414 if you want to use other than canonically cased file names on a Unix system,
415 you need to follow the procedures described in the next section.
417 .. _Using_Other_File_Names:
419 Using Other File Names
420 ----------------------
422 .. index:: File names
424 In the previous section, we have described the default rules used by
425 GNAT to determine the file name in which a given unit resides. It is
426 often convenient to follow these default rules, and if you follow them,
427 the compiler knows without being explicitly told where to find all
430 .. index:: Source_File_Name pragma
432 However, in some cases, particularly when a program is imported from
433 another Ada compiler environment, it may be more convenient for the
434 programmer to specify which file names contain which units. GNAT allows
435 arbitrary file names to be used by means of the Source_File_Name pragma.
436 The form of this pragma is as shown in the following examples:
440 pragma Source_File_Name (My_Utilities.Stacks,
441 Spec_File_Name => "myutilst_a.ada");
442 pragma Source_File_name (My_Utilities.Stacks,
443 Body_File_Name => "myutilst.ada");
445 As shown in this example, the first argument for the pragma is the unit
446 name (in this example a child unit). The second argument has the form
447 of a named association. The identifier
448 indicates whether the file name is for a spec or a body;
449 the file name itself is given by a string literal.
451 The source file name pragma is a configuration pragma, which means that
452 normally it will be placed in the :file:`gnat.adc`
453 file used to hold configuration
454 pragmas that apply to a complete compilation environment.
455 For more details on how the :file:`gnat.adc` file is created and used
456 see :ref:`Handling_of_Configuration_Pragmas`.
460 GNAT allows completely arbitrary file names to be specified using the
461 source file name pragma. However, if the file name specified has an
462 extension other than :file:`.ads` or :file:`.adb` it is necessary to use
463 a special syntax when compiling the file. The name in this case must be
464 preceded by the special sequence *-x* followed by a space and the name
465 of the language, here `ada`, as in:
469 $ gcc -c -x ada peculiar_file_name.sim
471 `gnatmake` handles non-standard file names in the usual manner (the
472 non-standard file name for the main program is simply used as the
473 argument to gnatmake). Note that if the extension is also non-standard,
474 then it must be included in the `gnatmake` command, it may not
477 .. _Alternative_File_Naming_Schemes:
479 Alternative File Naming Schemes
480 -------------------------------
482 .. index:: File naming schemes, alternative
484 .. index:: File names
486 The previous section described the use of the `Source_File_Name`
487 pragma to allow arbitrary names to be assigned to individual source files.
488 However, this approach requires one pragma for each file, and especially in
489 large systems can result in very long :file:`gnat.adc` files, and also create
490 a maintenance problem.
492 .. index:: Source_File_Name pragma
494 GNAT also provides a facility for specifying systematic file naming schemes
495 other than the standard default naming scheme previously described. An
496 alternative scheme for naming is specified by the use of
497 `Source_File_Name` pragmas having the following format:
501 pragma Source_File_Name (
502 Spec_File_Name => FILE_NAME_PATTERN
503 [ , Casing => CASING_SPEC]
504 [ , Dot_Replacement => STRING_LITERAL ] );
506 pragma Source_File_Name (
507 Body_File_Name => FILE_NAME_PATTERN
508 [ , Casing => CASING_SPEC ]
509 [ , Dot_Replacement => STRING_LITERAL ] ) ;
511 pragma Source_File_Name (
512 Subunit_File_Name => FILE_NAME_PATTERN
513 [ , Casing => CASING_SPEC ]
514 [ , Dot_Replacement => STRING_LITERAL ] ) ;
516 FILE_NAME_PATTERN ::= STRING_LITERAL
517 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
519 The `FILE_NAME_PATTERN` string shows how the file name is constructed.
520 It contains a single asterisk character, and the unit name is substituted
521 systematically for this asterisk. The optional parameter
523 whether the unit name is to be all upper-case letters, all lower-case letters,
525 `Casing` parameter is used, then the default is all
528 The optional `Dot_Replacement` string is used to replace any periods
529 that occur in subunit or child unit names. If no `Dot_Replacement`
530 argument is used then separating dots appear unchanged in the resulting
532 Although the above syntax indicates that the
533 `Casing` argument must appear
534 before the `Dot_Replacement` argument, but it
535 is also permissible to write these arguments in the opposite order.
537 As indicated, it is possible to specify different naming schemes for
538 bodies, specs, and subunits. Quite often the rule for subunits is the
539 same as the rule for bodies, in which case, there is no need to give
540 a separate `Subunit_File_Name` rule, and in this case the
541 `Body_File_name` rule is used for subunits as well.
543 The separate rule for subunits can also be used to implement the rather
544 unusual case of a compilation environment (e.g., a single directory) which
545 contains a subunit and a child unit with the same unit name. Although
546 both units cannot appear in the same partition, the Ada Reference Manual
547 allows (but does not require) the possibility of the two units coexisting
548 in the same environment.
550 The file name translation works in the following steps:
552 * If there is a specific `Source_File_Name` pragma for the given unit,
553 then this is always used, and any general pattern rules are ignored.
555 * If there is a pattern type `Source_File_Name` pragma that applies to
556 the unit, then the resulting file name will be used if the file exists. If
557 more than one pattern matches, the latest one will be tried first, and the
558 first attempt resulting in a reference to a file that exists will be used.
560 * If no pattern type `Source_File_Name` pragma that applies to the unit
561 for which the corresponding file exists, then the standard GNAT default
562 naming rules are used.
564 As an example of the use of this mechanism, consider a commonly used scheme
565 in which file names are all lower case, with separating periods copied
566 unchanged to the resulting file name, and specs end with :file:`.1.ada`, and
567 bodies end with :file:`.2.ada`. GNAT will follow this scheme if the following
572 pragma Source_File_Name
573 (Spec_File_Name => ".1.ada");
574 pragma Source_File_Name
575 (Body_File_Name => ".2.ada");
577 The default GNAT scheme is actually implemented by providing the following
578 default pragmas internally:
582 pragma Source_File_Name
583 (Spec_File_Name => ".ads", Dot_Replacement => "-");
584 pragma Source_File_Name
585 (Body_File_Name => ".adb", Dot_Replacement => "-");
587 Our final example implements a scheme typically used with one of the
588 Ada 83 compilers, where the separator character for subunits was '__'
589 (two underscores), specs were identified by adding :file:`_.ADA`, bodies
590 by adding :file:`.ADA`, and subunits by
591 adding :file:`.SEP`. All file names were
592 upper case. Child units were not present of course since this was an
593 Ada 83 compiler, but it seems reasonable to extend this scheme to use
594 the same double underscore separator for child units.
598 pragma Source_File_Name
599 (Spec_File_Name => "_.ADA",
600 Dot_Replacement => "__",
602 pragma Source_File_Name
603 (Body_File_Name => ".ADA",
604 Dot_Replacement => "__",
606 pragma Source_File_Name
607 (Subunit_File_Name => ".SEP",
608 Dot_Replacement => "__",
612 .. index:: ! gnatname
614 .. _Handling_Arbitrary_File_Naming_Conventions_with_gnatname:
616 Handling Arbitrary File Naming Conventions with `gnatname`
617 ----------------------------------------------------------
619 .. index:: File Naming Conventions
621 .. _Arbitrary_File_Naming_Conventions:
623 Arbitrary File Naming Conventions
624 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
626 The GNAT compiler must be able to know the source file name of a compilation
627 unit. When using the standard GNAT default file naming conventions
628 (`.ads` for specs, `.adb` for bodies), the GNAT compiler
629 does not need additional information.
631 When the source file names do not follow the standard GNAT default file naming
632 conventions, the GNAT compiler must be given additional information through
633 a configuration pragmas file (:ref:`Configuration_Pragmas`)
635 When the non-standard file naming conventions are well-defined,
636 a small number of pragmas `Source_File_Name` specifying a naming pattern
637 (:ref:`Alternative_File_Naming_Schemes`) may be sufficient. However,
638 if the file naming conventions are irregular or arbitrary, a number
639 of pragma `Source_File_Name` for individual compilation units
641 To help maintain the correspondence between compilation unit names and
642 source file names within the compiler,
643 GNAT provides a tool `gnatname` to generate the required pragmas for a
646 .. _Running_gnatname:
651 The usual form of the `gnatname` command is:
655 $ gnatname [`switches`] `naming_pattern` [`naming_patterns`]
656 [--and [`switches`] `naming_pattern` [`naming_patterns`]]
659 All of the arguments are optional. If invoked without any argument,
660 `gnatname` will display its usage.
662 When used with at least one naming pattern, `gnatname` will attempt to
663 find all the compilation units in files that follow at least one of the
664 naming patterns. To find these compilation units,
665 `gnatname` will use the GNAT compiler in syntax-check-only mode on all
668 One or several Naming Patterns may be given as arguments to `gnatname`.
669 Each Naming Pattern is enclosed between double quotes (or single
671 A Naming Pattern is a regular expression similar to the wildcard patterns
672 used in file names by the Unix shells or the DOS prompt.
674 `gnatname` may be called with several sections of directories/patterns.
675 Sections are separated by switch `--and`. In each section, there must be
676 at least one pattern. If no directory is specified in a section, the current
677 directory (or the project directory is `-P` is used) is implied.
678 The options other that the directory switches and the patterns apply globally
679 even if they are in different sections.
681 Examples of Naming Patterns are::
687 For a more complete description of the syntax of Naming Patterns,
688 see the second kind of regular expressions described in :file:`g-regexp.ads`
689 (the 'Glob' regular expressions).
691 When invoked with no switch `-P`, `gnatname` will create a
692 configuration pragmas file :file:`gnat.adc` in the current working directory,
693 with pragmas `Source_File_Name` for each file that contains a valid Ada
696 .. _Switches_for_gnatname:
698 Switches for `gnatname`
699 ^^^^^^^^^^^^^^^^^^^^^^^
701 Switches for `gnatname` must precede any specified Naming Pattern.
703 You may specify any of the following switches to `gnatname`:
705 .. index:: --version (gnatname)
708 Display Copyright and version, then exit disregarding all other options.
710 .. index:: --help (gnatname)
713 If *--version* was not used, display usage, then exit disregarding
716 :samp:`--subdirs={dir}`
717 Real object, library or exec directories are subdirectories <dir> of the
721 Do not create a backup copy of an existing project file.
724 Start another section of directories/patterns.
726 .. index:: -c (gnatname)
729 Create a configuration pragmas file :file:`filename` (instead of the default
731 There may be zero, one or more space between *-c* and
733 :file:`filename` may include directory information. :file:`filename` must be
734 writable. There may be only one switch *-c*.
735 When a switch *-c* is
736 specified, no switch *-P* may be specified (see below).
738 .. index:: -d (gnatname)
741 Look for source files in directory :file:`dir`. There may be zero, one or more
742 spaces between *-d* and :file:`dir`.
743 :file:`dir` may end with `/**`, that is it may be of the form
744 `root_dir/**`. In this case, the directory `root_dir` and all of its
745 subdirectories, recursively, have to be searched for sources.
747 is specified, the current working directory will not be searched for source
748 files, unless it is explicitly specified with a *-d*
750 Several switches *-d* may be specified.
751 If :file:`dir` is a relative path, it is relative to the directory of
752 the configuration pragmas file specified with switch
754 or to the directory of the project file specified with switch
756 if neither switch *-c*
757 nor switch *-P* are specified, it is relative to the
758 current working directory. The directory
759 specified with switch *-d* must exist and be readable.
761 .. index:: -D (gnatname)
764 Look for source files in all directories listed in text file :file:`filename`.
765 There may be zero, one or more spaces between *-D*
766 and :file:`filename`.
767 :file:`filename` must be an existing, readable text file.
768 Each nonempty line in :file:`filename` must be a directory.
769 Specifying switch *-D* is equivalent to specifying as many
770 switches *-d* as there are nonempty lines in
774 Follow symbolic links when processing project files.
776 .. index:: -f (gnatname)
779 Foreign patterns. Using this switch, it is possible to add sources of languages
780 other than Ada to the list of sources of a project file.
781 It is only useful if a -P switch is used.
786 gnatname -Pprj -f"*.c" "*.ada"
788 will look for Ada units in all files with the :file:`.ada` extension,
789 and will add to the list of file for project :file:`prj.gpr` the C files
790 with extension :file:`.c`.
792 .. index:: -h (gnatname)
795 Output usage (help) information. The output is written to :file:`stdout`.
797 .. index:: -P (gnatname)
800 Create or update project file :file:`proj`. There may be zero, one or more space
801 between *-P* and :file:`proj`. :file:`proj` may include directory
802 information. :file:`proj` must be writable.
803 There may be only one switch *-P*.
804 When a switch *-P* is specified,
805 no switch *-c* may be specified.
806 On all platforms, except on VMS, when `gnatname` is invoked for an
807 existing project file <proj>.gpr, a backup copy of the project file is created
808 in the project directory with file name <proj>.gpr.saved_x. 'x' is the first
809 non negative number that makes this backup copy a new file.
811 .. index:: -v (gnatname)
814 Verbose mode. Output detailed explanation of behavior to :file:`stdout`.
815 This includes name of the file written, the name of the directories to search
816 and, for each file in those directories whose name matches at least one of
817 the Naming Patterns, an indication of whether the file contains a unit,
818 and if so the name of the unit.
820 .. index:: -v -v (gnatname)
823 Very Verbose mode. In addition to the output produced in verbose mode,
824 for each file in the searched directories whose name matches none of
825 the Naming Patterns, an indication is given that there is no match.
827 .. index:: -x (gnatname)
830 Excluded patterns. Using this switch, it is possible to exclude some files
831 that would match the name patterns. For example,
835 gnatname -x "*_nt.ada" "*.ada"
837 will look for Ada units in all files with the :file:`.ada` extension,
838 except those whose names end with :file:`_nt.ada`.
841 .. _Examples_of_gnatname_Usage:
843 Examples of `gnatname` Usage
844 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
848 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
850 In this example, the directory :file:`/home/me` must already exist
851 and be writable. In addition, the directory
852 :file:`/home/me/sources` (specified by
853 *-d sources*) must exist and be readable.
855 Note the optional spaces after *-c* and *-d*.
859 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
860 -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
862 Note that several switches *-d* may be used,
863 even in conjunction with one or several switches
864 *-D*. Several Naming Patterns and one excluded pattern
865 are used in this example.
868 .. _File_Name_Krunching_with_gnatkr:
870 File Name Krunching with `gnatkr`
871 ---------------------------------
875 This chapter discusses the method used by the compiler to shorten
876 the default file names chosen for Ada units so that they do not
877 exceed the maximum length permitted. It also describes the
878 `gnatkr` utility that can be used to determine the result of
879 applying this shortening.
886 The default file naming rule in GNAT
887 is that the file name must be derived from
888 the unit name. The exact default rule is as follows:
890 * Take the unit name and replace all dots by hyphens.
892 * If such a replacement occurs in the
893 second character position of a name, and the first character is
894 :samp:`a`, :samp:`g`, :samp:`s`, or :samp:`i`,
895 then replace the dot by the character
899 The reason for this exception is to avoid clashes
900 with the standard names for children of System, Ada, Interfaces,
901 and GNAT, which use the prefixes
902 :samp:`s-`, :samp:`a-`, :samp:`i-`, and :samp:`g-`,
905 The :samp:`-gnatk{nn}`
906 switch of the compiler activates a 'krunching'
907 circuit that limits file names to nn characters (where nn is a decimal
910 The `gnatkr` utility can be used to determine the krunched name for
911 a given file, when krunched to a specified maximum length.
918 The `gnatkr` command has the form:
922 $ gnatkr `name` [`length`]
924 `name` is the uncrunched file name, derived from the name of the unit
925 in the standard manner described in the previous section (i.e., in particular
926 all dots are replaced by hyphens). The file name may or may not have an
927 extension (defined as a suffix of the form period followed by arbitrary
928 characters other than period). If an extension is present then it will
929 be preserved in the output. For example, when krunching :file:`hellofile.ads`
930 to eight characters, the result will be hellofil.ads.
932 Note: for compatibility with previous versions of `gnatkr` dots may
933 appear in the name instead of hyphens, but the last dot will always be
934 taken as the start of an extension. So if `gnatkr` is given an argument
935 such as :file:`Hello.World.adb` it will be treated exactly as if the first
936 period had been a hyphen, and for example krunching to eight characters
937 gives the result :file:`hellworl.adb`.
939 Note that the result is always all lower case.
940 Characters of the other case are folded as required.
942 `length` represents the length of the krunched name. The default
943 when no argument is given is 8 characters. A length of zero stands for
944 unlimited, in other words do not chop except for system files where the
945 implied crunching length is always eight characters.
947 The output is the krunched name. The output has an extension only if the
948 original argument was a file name with an extension.
950 .. _Krunching_Method:
955 The initial file name is determined by the name of the unit that the file
956 contains. The name is formed by taking the full expanded name of the
957 unit and replacing the separating dots with hyphens and
959 for all letters, except that a hyphen in the second character position is
960 replaced by a tilde if the first character is
961 :samp:`a`, :samp:`i`, :samp:`g`, or :samp:`s`.
962 The extension is `.ads` for a
963 spec and `.adb` for a body.
964 Krunching does not affect the extension, but the file name is shortened to
965 the specified length by following these rules:
967 * The name is divided into segments separated by hyphens, tildes or
968 underscores and all hyphens, tildes, and underscores are
969 eliminated. If this leaves the name short enough, we are done.
971 * If the name is too long, the longest segment is located (left-most
972 if there are two of equal length), and shortened by dropping
973 its last character. This is repeated until the name is short enough.
975 As an example, consider the krunching of :file:`our-strings-wide_fixed.adb`
976 to fit the name into 8 characters as required by some operating systems::
978 our-strings-wide_fixed 22
979 our strings wide fixed 19
980 our string wide fixed 18
981 our strin wide fixed 17
982 our stri wide fixed 16
983 our stri wide fixe 15
991 Final file name: oustwifi.adb
993 * The file names for all predefined units are always krunched to eight
994 characters. The krunching of these predefined units uses the following
995 special prefix replacements:
997 ===================== ==============
999 --------------------- --------------
1000 :file:`ada-` :file:`a-`
1001 :file:`gnat-` :file:`g-`
1002 :file:`interfac es-` :file:`i-`
1003 :file:`system-` :file:`s-`
1004 ===================== ==============
1006 These system files have a hyphen in the second character position. That
1007 is why normal user files replace such a character with a
1008 tilde, to avoid confusion with system file names.
1010 As an example of this special rule, consider
1011 :file:`ada-strings-wide_fixed.adb`, which gets krunched as follows::
1013 ada-strings-wide_fixed 22
1014 a- strings wide fixed 18
1015 a- string wide fixed 17
1016 a- strin wide fixed 16
1017 a- stri wide fixed 15
1018 a- stri wide fixe 14
1025 Final file name: a-stwifi.adb
1027 Of course no file shortening algorithm can guarantee uniqueness over all
1028 possible unit names, and if file name krunching is used then it is your
1029 responsibility to ensure that no name clashes occur. The utility
1030 program `gnatkr` is supplied for conveniently determining the
1031 krunched name of a file.
1033 .. _Examples_of_gnatkr_Usage:
1035 Examples of `gnatkr` Usage
1036 ^^^^^^^^^^^^^^^^^^^^^^^^^^
1040 $ gnatkr very_long_unit_name.ads --> velounna.ads
1041 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
1042 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
1043 $ gnatkr grandparent-parent-child --> grparchi
1044 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
1045 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
1048 .. _Renaming_Files_with_gnatchop:
1050 Renaming Files with `gnatchop`
1051 ------------------------------
1053 .. index:: ! gnatchop
1055 This chapter discusses how to handle files with multiple units by using
1056 the `gnatchop` utility. This utility is also useful in renaming
1057 files to meet the standard GNAT default file naming conventions.
1059 .. _Handling_Files_with_Multiple_Units:
1061 Handling Files with Multiple Units
1062 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1064 The basic compilation model of GNAT requires that a file submitted to the
1065 compiler have only one unit and there be a strict correspondence
1066 between the file name and the unit name.
1068 The `gnatchop` utility allows both of these rules to be relaxed,
1069 allowing GNAT to process files which contain multiple compilation units
1070 and files with arbitrary file names. `gnatchop`
1071 reads the specified file and generates one or more output files,
1072 containing one unit per file. The unit and the file name correspond,
1073 as required by GNAT.
1075 If you want to permanently restructure a set of 'foreign' files so that
1076 they match the GNAT rules, and do the remaining development using the
1077 GNAT structure, you can simply use *gnatchop* once, generate the
1078 new set of files and work with them from that point on.
1080 Alternatively, if you want to keep your files in the 'foreign' format,
1081 perhaps to maintain compatibility with some other Ada compilation
1082 system, you can set up a procedure where you use *gnatchop* each
1083 time you compile, regarding the source files that it writes as temporary
1084 files that you throw away.
1086 Note that if your file containing multiple units starts with a byte order
1087 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
1088 will each start with a copy of this BOM, meaning that they can be compiled
1089 automatically in UTF-8 mode without needing to specify an explicit encoding.
1091 .. _Operating_gnatchop_in_Compilation_Mode:
1093 Operating gnatchop in Compilation Mode
1094 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1096 The basic function of `gnatchop` is to take a file with multiple units
1097 and split it into separate files. The boundary between files is reasonably
1098 clear, except for the issue of comments and pragmas. In default mode, the
1099 rule is that any pragmas between units belong to the previous unit, except
1100 that configuration pragmas always belong to the following unit. Any comments
1101 belong to the following unit. These rules
1102 almost always result in the right choice of
1103 the split point without needing to mark it explicitly and most users will
1104 find this default to be what they want. In this default mode it is incorrect to
1105 submit a file containing only configuration pragmas, or one that ends in
1106 configuration pragmas, to `gnatchop`.
1108 However, using a special option to activate 'compilation mode',
1110 can perform another function, which is to provide exactly the semantics
1111 required by the RM for handling of configuration pragmas in a compilation.
1112 In the absence of configuration pragmas (at the main file level), this
1113 option has no effect, but it causes such configuration pragmas to be handled
1114 in a quite different manner.
1116 First, in compilation mode, if `gnatchop` is given a file that consists of
1117 only configuration pragmas, then this file is appended to the
1118 :file:`gnat.adc` file in the current directory. This behavior provides
1119 the required behavior described in the RM for the actions to be taken
1120 on submitting such a file to the compiler, namely that these pragmas
1121 should apply to all subsequent compilations in the same compilation
1122 environment. Using GNAT, the current directory, possibly containing a
1123 :file:`gnat.adc` file is the representation
1124 of a compilation environment. For more information on the
1125 :file:`gnat.adc` file, see :ref:`Handling_of_Configuration_Pragmas`.
1127 Second, in compilation mode, if `gnatchop`
1128 is given a file that starts with
1129 configuration pragmas, and contains one or more units, then these
1130 configuration pragmas are prepended to each of the chopped files. This
1131 behavior provides the required behavior described in the RM for the
1132 actions to be taken on compiling such a file, namely that the pragmas
1133 apply to all units in the compilation, but not to subsequently compiled
1136 Finally, if configuration pragmas appear between units, they are appended
1137 to the previous unit. This results in the previous unit being illegal,
1138 since the compiler does not accept configuration pragmas that follow
1139 a unit. This provides the required RM behavior that forbids configuration
1140 pragmas other than those preceding the first compilation unit of a
1143 For most purposes, `gnatchop` will be used in default mode. The
1144 compilation mode described above is used only if you need exactly
1145 accurate behavior with respect to compilations, and you have files
1146 that contain multiple units and configuration pragmas. In this
1147 circumstance the use of `gnatchop` with the compilation mode
1148 switch provides the required behavior, and is for example the mode
1149 in which GNAT processes the ACVC tests.
1152 .. _Command_Line_for_gnatchop:
1154 Command Line for `gnatchop`
1155 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
1157 The `gnatchop` command has the form:
1161 $ gnatchop switches file_name [file_name ...]
1164 The only required argument is the file name of the file to be chopped.
1165 There are no restrictions on the form of this file name. The file itself
1166 contains one or more Ada units, in normal GNAT format, concatenated
1167 together. As shown, more than one file may be presented to be chopped.
1169 When run in default mode, `gnatchop` generates one output file in
1170 the current directory for each unit in each of the files.
1172 `directory`, if specified, gives the name of the directory to which
1173 the output files will be written. If it is not specified, all files are
1174 written to the current directory.
1176 For example, given a
1177 file called :file:`hellofiles` containing
1183 with Ada.Text_IO; use Ada.Text_IO;
1193 $ gnatchop hellofiles
1195 generates two files in the current directory, one called
1196 :file:`hello.ads` containing the single line that is the procedure spec,
1197 and the other called :file:`hello.adb` containing the remaining text. The
1198 original file is not affected. The generated files can be compiled in
1201 When gnatchop is invoked on a file that is empty or that contains only empty
1202 lines and/or comments, gnatchop will not fail, but will not produce any
1205 For example, given a
1206 file called :file:`toto.txt` containing
1218 will not produce any new file and will result in the following warnings::
1220 toto.txt:1:01: warning: empty file, contains no compilation units
1221 no compilation units found
1222 no source files written
1225 .. _Switches_for_gnatchop:
1227 Switches for `gnatchop`
1228 ^^^^^^^^^^^^^^^^^^^^^^^
1230 *gnatchop* recognizes the following switches:
1233 .. index:: --version (gnatchop)
1236 Display Copyright and version, then exit disregarding all other options.
1238 .. index:: --help (gnatchop)
1241 If *--version* was not used, display usage, then exit disregarding
1244 .. index:: -c (gnatchop)
1247 Causes `gnatchop` to operate in compilation mode, in which
1248 configuration pragmas are handled according to strict RM rules. See
1249 previous section for a full description of this mode.
1252 This passes the given *-gnat`xxx*` switch to `gnat` which is
1253 used to parse the given file. Not all `xxx` options make sense,
1254 but for example, the use of *-gnati2* allows `gnatchop` to
1255 process a source file that uses Latin-2 coding for identifiers.
1258 Causes `gnatchop` to generate a brief help summary to the standard
1259 output file showing usage information.
1261 .. index:: -k (gnatchop)
1264 Limit generated file names to the specified number `mm`
1266 This is useful if the
1267 resulting set of files is required to be interoperable with systems
1268 which limit the length of file names.
1269 No space is allowed between the *-k* and the numeric value. The numeric
1270 value may be omitted in which case a default of *-k8*,
1272 with DOS-like file systems, is used. If no *-k* switch
1274 there is no limit on the length of file names.
1276 .. index:: -p (gnatchop)
1279 Causes the file modification time stamp of the input file to be
1280 preserved and used for the time stamp of the output file(s). This may be
1281 useful for preserving coherency of time stamps in an environment where
1282 `gnatchop` is used as part of a standard build process.
1284 .. index:: -q (gnatchop)
1287 Causes output of informational messages indicating the set of generated
1288 files to be suppressed. Warnings and error messages are unaffected.
1290 .. index:: -r (gnatchop)
1291 .. index:: Source_Reference pragmas
1294 Generate `Source_Reference` pragmas. Use this switch if the output
1295 files are regarded as temporary and development is to be done in terms
1296 of the original unchopped file. This switch causes
1297 `Source_Reference` pragmas to be inserted into each of the
1298 generated files to refers back to the original file name and line number.
1299 The result is that all error messages refer back to the original
1301 In addition, the debugging information placed into the object file (when
1302 the *-g* switch of *gcc* or *gnatmake* is
1304 also refers back to this original file so that tools like profilers and
1305 debuggers will give information in terms of the original unchopped file.
1307 If the original file to be chopped itself contains
1308 a `Source_Reference`
1309 pragma referencing a third file, then gnatchop respects
1310 this pragma, and the generated `Source_Reference` pragmas
1311 in the chopped file refer to the original file, with appropriate
1312 line numbers. This is particularly useful when `gnatchop`
1313 is used in conjunction with `gnatprep` to compile files that
1314 contain preprocessing statements and multiple units.
1316 .. index:: -v (gnatchop)
1319 Causes `gnatchop` to operate in verbose mode. The version
1320 number and copyright notice are output, as well as exact copies of
1321 the gnat1 commands spawned to obtain the chop control information.
1323 .. index:: -w (gnatchop)
1326 Overwrite existing file names. Normally `gnatchop` regards it as a
1327 fatal error if there is already a file with the same name as a
1328 file it would otherwise output, in other words if the files to be
1329 chopped contain duplicated units. This switch bypasses this
1330 check, and causes all but the last instance of such duplicated
1331 units to be skipped.
1333 .. index:: --GCC= (gnatchop)
1335 :samp:`--GCC={xxxx}`
1336 Specify the path of the GNAT parser to be used. When this switch is used,
1337 no attempt is made to add the prefix to the GNAT parser executable.
1340 .. _Examples_of_gnatchop_Usage:
1342 Examples of `gnatchop` Usage
1343 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1347 $ gnatchop -w hello_s.ada prerelease/files
1349 Chops the source file :file:`hello_s.ada`. The output files will be
1350 placed in the directory :file:`prerelease/files`,
1352 files with matching names in that directory (no files in the current
1353 directory are modified).
1359 Chops the source file :file:`archive`
1360 into the current directory. One
1361 useful application of `gnatchop` is in sending sets of sources
1362 around, for example in email messages. The required sources are simply
1363 concatenated (for example, using a Unix `cat`
1365 *gnatchop* is used at the other end to reconstitute the original
1370 $ gnatchop file1 file2 file3 direc
1372 Chops all units in files :file:`file1`, :file:`file2`, :file:`file3`, placing
1373 the resulting files in the directory :file:`direc`. Note that if any units
1374 occur more than once anywhere within this set of files, an error message
1375 is generated, and no files are written. To override this check, use the
1377 in which case the last occurrence in the last file will
1378 be the one that is output, and earlier duplicate occurrences for a given
1379 unit will be skipped.
1381 .. _Configuration_Pragmas:
1383 Configuration Pragmas
1384 =====================
1386 .. index:: Configuration pragmas
1388 .. index:: Pragmas, configuration
1390 Configuration pragmas include those pragmas described as
1391 such in the Ada Reference Manual, as well as
1392 implementation-dependent pragmas that are configuration pragmas.
1393 See the `Implementation_Defined_Pragmas` chapter in the
1394 :title:`GNAT_Reference_Manual` for details on these
1395 additional GNAT-specific configuration pragmas.
1396 Most notably, the pragma `Source_File_Name`, which allows
1397 specifying non-default names for source files, is a configuration
1398 pragma. The following is a complete list of configuration pragmas
1399 recognized by GNAT::
1407 Allow_Integer_Address
1410 Assume_No_Invalid_Values
1415 Compile_Time_Warning
1418 Convention_Identifier
1421 Default_Storage_Pool
1427 External_Name_Casing
1430 Float_Representation
1443 Priority_Specific_Dispatching
1446 Propagate_Exceptions
1451 Restrictions_Warnings
1453 Short_Circuit_And_Or
1455 Source_File_Name_Project
1459 Suppress_Exception_Locations
1460 Task_Dispatching_Policy
1466 Wide_Character_Encoding
1469 .. _Handling_of_Configuration_Pragmas:
1471 Handling of Configuration Pragmas
1472 ---------------------------------
1474 Configuration pragmas may either appear at the start of a compilation
1475 unit, or they can appear in a configuration pragma file to apply to
1476 all compilations performed in a given compilation environment.
1478 GNAT also provides the `gnatchop` utility to provide an automatic
1479 way to handle configuration pragmas following the semantics for
1480 compilations (that is, files with multiple units), described in the RM.
1481 See :ref:`Operating_gnatchop_in_Compilation_Mode` for details.
1482 However, for most purposes, it will be more convenient to edit the
1483 :file:`gnat.adc` file that contains configuration pragmas directly,
1484 as described in the following section.
1486 In the case of `Restrictions` pragmas appearing as configuration
1487 pragmas in individual compilation units, the exact handling depends on
1488 the type of restriction.
1490 Restrictions that require partition-wide consistency (like
1492 recognized wherever they appear
1493 and can be freely inherited, e.g. from a |withed| unit to the |withing|
1494 unit. This makes sense since the binder will in any case insist on seeing
1495 consistent use, so any unit not conforming to any restrictions that are
1496 anywhere in the partition will be rejected, and you might as well find
1497 that out at compile time rather than at bind time.
1499 For restrictions that do not require partition-wide consistency, e.g.
1500 SPARK or No_Implementation_Attributes, in general the restriction applies
1501 only to the unit in which the pragma appears, and not to any other units.
1503 The exception is No_Elaboration_Code which always applies to the entire
1504 object file from a compilation, i.e. to the body, spec, and all subunits.
1505 This restriction can be specified in a configuration pragma file, or it
1506 can be on the body and/or the spec (in eithe case it applies to all the
1507 relevant units). It can appear on a subunit only if it has previously
1508 appeared in the body of spec.
1511 .. _The_Configuration_Pragmas_Files:
1513 The Configuration Pragmas Files
1514 -------------------------------
1518 In GNAT a compilation environment is defined by the current
1519 directory at the time that a compile command is given. This current
1520 directory is searched for a file whose name is :file:`gnat.adc`. If
1521 this file is present, it is expected to contain one or more
1522 configuration pragmas that will be applied to the current compilation.
1523 However, if the switch *-gnatA* is used, :file:`gnat.adc` is not
1524 considered. When taken into account, :file:`gnat.adc` is added to the
1525 dependencies, so that if :file:`gnat.adc` is modified later, an invocation of
1526 *gnatmake* will recompile the source.
1528 Configuration pragmas may be entered into the :file:`gnat.adc` file
1529 either by running `gnatchop` on a source file that consists only of
1530 configuration pragmas, or more conveniently by direct editing of the
1531 :file:`gnat.adc` file, which is a standard format source file.
1533 Besides :file:`gnat.adc`, additional files containing configuration
1534 pragmas may be applied to the current compilation using the switch
1535 :samp:`-gnatec={path}` where `path` must designate an existing file that
1536 contains only configuration pragmas. These configuration pragmas are
1537 in addition to those found in :file:`gnat.adc` (provided :file:`gnat.adc`
1538 is present and switch *-gnatA* is not used).
1540 It is allowable to specify several switches *-gnatec=*, all of which
1541 will be taken into account.
1543 Files containing configuration pragmas specified with switches
1544 *-gnatec=* are added to the dependencies, unless they are
1545 temporary files. A file is considered temporary if its name ends in
1546 :file:`.tmp` or :file:`.TMP`. Certain tools follow this naming
1547 convention because they pass information to *gcc* via
1548 temporary files that are immediately deleted; it doesn't make sense to
1549 depend on a file that no longer exists. Such tools include
1550 *gprbuild*, *gnatmake*, and *gnatcheck*.
1552 If you are using project file, a separate mechanism is provided using
1553 project attributes, see :ref:`Specifying_Configuration_Pragmas` for more
1557 .. _Generating_Object_Files:
1559 Generating Object Files
1560 =======================
1562 An Ada program consists of a set of source files, and the first step in
1563 compiling the program is to generate the corresponding object files.
1564 These are generated by compiling a subset of these source files.
1565 The files you need to compile are the following:
1567 * If a package spec has no body, compile the package spec to produce the
1568 object file for the package.
1570 * If a package has both a spec and a body, compile the body to produce the
1571 object file for the package. The source file for the package spec need
1572 not be compiled in this case because there is only one object file, which
1573 contains the code for both the spec and body of the package.
1575 * For a subprogram, compile the subprogram body to produce the object file
1576 for the subprogram. The spec, if one is present, is as usual in a
1577 separate file, and need not be compiled.
1581 * In the case of subunits, only compile the parent unit. A single object
1582 file is generated for the entire subunit tree, which includes all the
1585 * Compile child units independently of their parent units
1586 (though, of course, the spec of all the ancestor unit must be present in order
1587 to compile a child unit).
1591 * Compile generic units in the same manner as any other units. The object
1592 files in this case are small dummy files that contain at most the
1593 flag used for elaboration checking. This is because GNAT always handles generic
1594 instantiation by means of macro expansion. However, it is still necessary to
1595 compile generic units, for dependency checking and elaboration purposes.
1597 The preceding rules describe the set of files that must be compiled to
1598 generate the object files for a program. Each object file has the same
1599 name as the corresponding source file, except that the extension is
1600 :file:`.o` as usual.
1602 You may wish to compile other files for the purpose of checking their
1603 syntactic and semantic correctness. For example, in the case where a
1604 package has a separate spec and body, you would not normally compile the
1605 spec. However, it is convenient in practice to compile the spec to make
1606 sure it is error-free before compiling clients of this spec, because such
1607 compilations will fail if there is an error in the spec.
1609 GNAT provides an option for compiling such files purely for the
1610 purposes of checking correctness; such compilations are not required as
1611 part of the process of building a program. To compile a file in this
1612 checking mode, use the *-gnatc* switch.
1614 .. _Source_Dependencies:
1619 A given object file clearly depends on the source file which is compiled
1620 to produce it. Here we are using "depends" in the sense of a typical
1621 `make` utility; in other words, an object file depends on a source
1622 file if changes to the source file require the object file to be
1624 In addition to this basic dependency, a given object may depend on
1625 additional source files as follows:
1627 * If a file being compiled |withs| a unit `X`, the object file
1628 depends on the file containing the spec of unit `X`. This includes
1629 files that are |withed| implicitly either because they are parents
1630 of |withed| child units or they are run-time units required by the
1631 language constructs used in a particular unit.
1633 * If a file being compiled instantiates a library level generic unit, the
1634 object file depends on both the spec and body files for this generic
1637 * If a file being compiled instantiates a generic unit defined within a
1638 package, the object file depends on the body file for the package as
1639 well as the spec file.
1642 .. index:: -gnatn switch
1644 * If a file being compiled contains a call to a subprogram for which
1645 pragma `Inline` applies and inlining is activated with the
1646 *-gnatn* switch, the object file depends on the file containing the
1647 body of this subprogram as well as on the file containing the spec. Note
1648 that for inlining to actually occur as a result of the use of this switch,
1649 it is necessary to compile in optimizing mode.
1651 .. index:: -gnatN switch
1653 The use of *-gnatN* activates inlining optimization
1654 that is performed by the front end of the compiler. This inlining does
1655 not require that the code generation be optimized. Like *-gnatn*,
1656 the use of this switch generates additional dependencies.
1658 When using a gcc-based back end (in practice this means using any version
1659 of GNAT other than for the JVM, .NET or GNAAMP platforms), then the use of
1660 *-gnatN* is deprecated, and the use of *-gnatn* is preferred.
1661 Historically front end inlining was more extensive than the gcc back end
1662 inlining, but that is no longer the case.
1664 * If an object file :file:`O` depends on the proper body of a subunit through
1665 inlining or instantiation, it depends on the parent unit of the subunit.
1666 This means that any modification of the parent unit or one of its subunits
1667 affects the compilation of :file:`O`.
1669 * The object file for a parent unit depends on all its subunit body files.
1671 * The previous two rules meant that for purposes of computing dependencies and
1672 recompilation, a body and all its subunits are treated as an indivisible whole.
1674 These rules are applied transitively: if unit `A` |withs|
1675 unit `B`, whose elaboration calls an inlined procedure in package
1676 `C`, the object file for unit `A` will depend on the body of
1677 `C`, in file :file:`c.adb`.
1679 The set of dependent files described by these rules includes all the
1680 files on which the unit is semantically dependent, as dictated by the
1681 Ada language standard. However, it is a superset of what the
1682 standard describes, because it includes generic, inline, and subunit
1685 An object file must be recreated by recompiling the corresponding source
1686 file if any of the source files on which it depends are modified. For
1687 example, if the `make` utility is used to control compilation,
1688 the rule for an Ada object file must mention all the source files on
1689 which the object file depends, according to the above definition.
1690 The determination of the necessary
1691 recompilations is done automatically when one uses *gnatmake*.
1693 .. _The_Ada_Library_Information_Files:
1695 The Ada Library Information Files
1696 =================================
1698 .. index:: Ada Library Information files
1700 .. index:: ALI files
1702 Each compilation actually generates two output files. The first of these
1703 is the normal object file that has a :file:`.o` extension. The second is a
1704 text file containing full dependency information. It has the same
1705 name as the source file, but an :file:`.ali` extension.
1706 This file is known as the Ada Library Information (:file:`ALI`) file.
1707 The following information is contained in the :file:`ALI` file.
1709 * Version information (indicates which version of GNAT was used to compile
1710 the unit(s) in question)
1712 * Main program information (including priority and time slice settings,
1713 as well as the wide character encoding used during compilation).
1715 * List of arguments used in the *gcc* command for the compilation
1717 * Attributes of the unit, including configuration pragmas used, an indication
1718 of whether the compilation was successful, exception model used etc.
1720 * A list of relevant restrictions applying to the unit (used for consistency)
1723 * Categorization information (e.g., use of pragma `Pure`).
1725 * Information on all |withed| units, including presence of
1726 Elaborate` or `Elaborate_All` pragmas.
1728 * Information from any `Linker_Options` pragmas used in the unit
1730 * Information on the use of `Body_Version` or `Version`
1731 attributes in the unit.
1733 * Dependency information. This is a list of files, together with
1734 time stamp and checksum information. These are files on which
1735 the unit depends in the sense that recompilation is required
1736 if any of these units are modified.
1738 * Cross-reference data. Contains information on all entities referenced
1739 in the unit. Used by tools like `gnatxref` and `gnatfind` to
1740 provide cross-reference information.
1742 For a full detailed description of the format of the :file:`ALI` file,
1743 see the source of the body of unit `Lib.Writ`, contained in file
1744 :file:`lib-writ.adb` in the GNAT compiler sources.
1747 .. _Binding_an_Ada_Program:
1749 Binding an Ada Program
1750 ======================
1752 When using languages such as C and C++, once the source files have been
1753 compiled the only remaining step in building an executable program
1754 is linking the object modules together. This means that it is possible to
1755 link an inconsistent version of a program, in which two units have
1756 included different versions of the same header.
1758 The rules of Ada do not permit such an inconsistent program to be built.
1759 For example, if two clients have different versions of the same package,
1760 it is illegal to build a program containing these two clients.
1761 These rules are enforced by the GNAT binder, which also determines an
1762 elaboration order consistent with the Ada rules.
1764 The GNAT binder is run after all the object files for a program have
1765 been created. It is given the name of the main program unit, and from
1766 this it determines the set of units required by the program, by reading the
1767 corresponding ALI files. It generates error messages if the program is
1768 inconsistent or if no valid order of elaboration exists.
1770 If no errors are detected, the binder produces a main program, in Ada by
1771 default, that contains calls to the elaboration procedures of those
1772 compilation unit that require them, followed by
1773 a call to the main program. This Ada program is compiled to generate the
1774 object file for the main program. The name of
1775 the Ada file is :file:`b~xxx`.adb` (with the corresponding spec
1776 :file:`b~xxx`.ads`) where `xxx` is the name of the
1779 Finally, the linker is used to build the resulting executable program,
1780 using the object from the main program from the bind step as well as the
1781 object files for the Ada units of the program.
1784 .. _GNAT_and_Libraries:
1789 .. index:: Library building and using
1791 This chapter describes how to build and use libraries with GNAT, and also shows
1792 how to recompile the GNAT run-time library. You should be familiar with the
1793 Project Manager facility (:ref:`GNAT_Project_Manager`) before reading this
1796 .. _Introduction_to_Libraries_in_GNAT:
1798 Introduction to Libraries in GNAT
1799 ---------------------------------
1801 A library is, conceptually, a collection of objects which does not have its
1802 own main thread of execution, but rather provides certain services to the
1803 applications that use it. A library can be either statically linked with the
1804 application, in which case its code is directly included in the application,
1805 or, on platforms that support it, be dynamically linked, in which case
1806 its code is shared by all applications making use of this library.
1808 GNAT supports both types of libraries.
1809 In the static case, the compiled code can be provided in different ways. The
1810 simplest approach is to provide directly the set of objects resulting from
1811 compilation of the library source files. Alternatively, you can group the
1812 objects into an archive using whatever commands are provided by the operating
1813 system. For the latter case, the objects are grouped into a shared library.
1815 In the GNAT environment, a library has three types of components:
1819 * :file:`ALI` files (see :ref:`The_Ada_Library_Information_Files`), and
1821 * Object files, an archive or a shared library.
1823 A GNAT library may expose all its source files, which is useful for
1824 documentation purposes. Alternatively, it may expose only the units needed by
1825 an external user to make use of the library. That is to say, the specs
1826 reflecting the library services along with all the units needed to compile
1827 those specs, which can include generic bodies or any body implementing an
1828 inlined routine. In the case of *stand-alone libraries* those exposed
1829 units are called *interface units* (:ref:`Stand-alone_Ada_Libraries`).
1831 All compilation units comprising an application, including those in a library,
1832 need to be elaborated in an order partially defined by Ada's semantics. GNAT
1833 computes the elaboration order from the :file:`ALI` files and this is why they
1834 constitute a mandatory part of GNAT libraries.
1835 *Stand-alone libraries* are the exception to this rule because a specific
1836 library elaboration routine is produced independently of the application(s)
1839 .. _General_Ada_Libraries:
1841 General Ada Libraries
1842 ---------------------
1845 .. _Building_a_library:
1850 The easiest way to build a library is to use the Project Manager,
1851 which supports a special type of project called a *Library Project*
1852 (see :ref:`Library_Projects`).
1854 A project is considered a library project, when two project-level attributes
1855 are defined in it: `Library_Name` and `Library_Dir`. In order to
1856 control different aspects of library configuration, additional optional
1857 project-level attributes can be specified:
1860 This attribute controls whether the library is to be static or dynamic
1864 This attribute specifies the library version; this value is used
1865 during dynamic linking of shared libraries to determine if the currently
1866 installed versions of the binaries are compatible.
1871 These attributes specify additional low-level options to be used during
1872 library generation, and redefine the actual application used to generate
1875 The GNAT Project Manager takes full care of the library maintenance task,
1876 including recompilation of the source files for which objects do not exist
1877 or are not up to date, assembly of the library archive, and installation of
1878 the library (i.e., copying associated source, object and :file:`ALI` files
1879 to the specified location).
1881 Here is a simple library project file:
1886 for Source_Dirs use ("src1", "src2");
1887 for Object_Dir use "obj";
1888 for Library_Name use "mylib";
1889 for Library_Dir use "lib";
1890 for Library_Kind use "dynamic";
1893 and the compilation command to build and install the library:
1899 It is not entirely trivial to perform manually all the steps required to
1900 produce a library. We recommend that you use the GNAT Project Manager
1901 for this task. In special cases where this is not desired, the necessary
1902 steps are discussed below.
1904 There are various possibilities for compiling the units that make up the
1905 library: for example with a Makefile (:ref:`Using_the_GNU_make_Utility`) or
1906 with a conventional script. For simple libraries, it is also possible to create
1907 a dummy main program which depends upon all the packages that comprise the
1908 interface of the library. This dummy main program can then be given to
1909 *gnatmake*, which will ensure that all necessary objects are built.
1911 After this task is accomplished, you should follow the standard procedure
1912 of the underlying operating system to produce the static or shared library.
1914 Here is an example of such a dummy program:
1918 with My_Lib.Service1;
1919 with My_Lib.Service2;
1920 with My_Lib.Service3;
1921 procedure My_Lib_Dummy is
1926 Here are the generic commands that will build an archive or a shared library.
1930 # compiling the library
1931 $ gnatmake -c my_lib_dummy.adb
1933 # we don't need the dummy object itself
1934 $ rm my_lib_dummy.o my_lib_dummy.ali
1936 # create an archive with the remaining objects
1937 $ ar rc libmy_lib.a *.o
1938 # some systems may require "ranlib" to be run as well
1940 # or create a shared library
1941 $ gcc -shared -o libmy_lib.so *.o
1942 # some systems may require the code to have been compiled with -fPIC
1944 # remove the object files that are now in the library
1947 # Make the ALI files read-only so that gnatmake will not try to
1948 # regenerate the objects that are in the library
1951 Please note that the library must have a name of the form :file:`lib{xxx}.a`
1952 or :file:`lib{xxx}.so` (or :file:`lib{xxx}.dll` on Windows) in order to
1953 be accessed by the directive :samp:`-l{xxx}` at link time.
1955 .. _Installing_a_library:
1957 Installing a library
1958 ^^^^^^^^^^^^^^^^^^^^
1960 .. index:: ADA_PROJECT_PATH
1961 .. index:: GPR_PROJECT_PATH
1963 If you use project files, library installation is part of the library build
1964 process (:ref:`Installing_a_library_with_project_files`).
1966 When project files are not an option, it is also possible, but not recommended,
1967 to install the library so that the sources needed to use the library are on the
1968 Ada source path and the ALI files & libraries be on the Ada Object path (see
1969 :ref:`Search_Paths_and_the_Run-Time_Library_RTL`. Alternatively, the system
1970 administrator can place general-purpose libraries in the default compiler
1971 paths, by specifying the libraries' location in the configuration files
1972 :file:`ada_source_path` and :file:`ada_object_path`. These configuration files
1973 must be located in the GNAT installation tree at the same place as the gcc spec
1974 file. The location of the gcc spec file can be determined as follows:
1981 The configuration files mentioned above have a simple format: each line
1982 must contain one unique directory name.
1983 Those names are added to the corresponding path
1984 in their order of appearance in the file. The names can be either absolute
1985 or relative; in the latter case, they are relative to where theses files
1988 The files :file:`ada_source_path` and :file:`ada_object_path` might not be
1990 GNAT installation, in which case, GNAT will look for its run-time library in
1991 the directories :file:`adainclude` (for the sources) and :file:`adalib` (for the
1992 objects and :file:`ALI` files). When the files exist, the compiler does not
1993 look in :file:`adainclude` and :file:`adalib`, and thus the
1994 :file:`ada_source_path` file
1995 must contain the location for the GNAT run-time sources (which can simply
1996 be :file:`adainclude`). In the same way, the :file:`ada_object_path` file must
1997 contain the location for the GNAT run-time objects (which can simply
2000 You can also specify a new default path to the run-time library at compilation
2001 time with the switch *--RTS=rts-path*. You can thus choose / change
2002 the run-time library you want your program to be compiled with. This switch is
2003 recognized by *gcc*, *gnatmake*, *gnatbind*,
2004 *gnatls*, *gnatfind* and *gnatxref*.
2006 It is possible to install a library before or after the standard GNAT
2007 library, by reordering the lines in the configuration files. In general, a
2008 library must be installed before the GNAT library if it redefines
2011 .. _Using_a_library:
2016 Once again, the project facility greatly simplifies the use of
2017 libraries. In this context, using a library is just a matter of adding a
2018 |with| clause in the user project. For instance, to make use of the
2019 library `My_Lib` shown in examples in earlier sections, you can
2029 Even if you have a third-party, non-Ada library, you can still use GNAT's
2030 Project Manager facility to provide a wrapper for it. For example, the
2031 following project, when |withed| by your main project, will link with the
2032 third-party library :file:`liba.a`:
2037 for Externally_Built use "true";
2038 for Source_Files use ();
2039 for Library_Dir use "lib";
2040 for Library_Name use "a";
2041 for Library_Kind use "static";
2044 This is an alternative to the use of `pragma Linker_Options`. It is
2045 especially interesting in the context of systems with several interdependent
2046 static libraries where finding a proper linker order is not easy and best be
2047 left to the tools having visibility over project dependence information.
2049 In order to use an Ada library manually, you need to make sure that this
2050 library is on both your source and object path
2051 (see :ref:`Search_Paths_and_the_Run-Time_Library_RTL`
2052 and :ref:`Search_Paths_for_gnatbind`). Furthermore, when the objects are grouped
2053 in an archive or a shared library, you need to specify the desired
2054 library at link time.
2056 For example, you can use the library :file:`mylib` installed in
2057 :file:`/dir/my_lib_src` and :file:`/dir/my_lib_obj` with the following commands:
2061 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \\
2064 This can be expressed more simply:
2070 when the following conditions are met:
2072 * :file:`/dir/my_lib_src` has been added by the user to the environment
2073 variable :envvar:`ADA_INCLUDE_PATH`, or by the administrator to the file
2074 :file:`ada_source_path`
2076 * :file:`/dir/my_lib_obj` has been added by the user to the environment
2077 variable :envvar:`ADA_OBJECTS_PATH`, or by the administrator to the file
2078 :file:`ada_object_path`
2080 * a pragma `Linker_Options` has been added to one of the sources.
2085 pragma Linker_Options ("-lmy_lib");
2087 Note that you may also load a library dynamically at
2088 run time given its filename, as illustrated in the GNAT :file:`plugins` example
2089 in the directory :file:`share/examples/gnat/plugins` within the GNAT
2092 .. _Stand-alone_Ada_Libraries:
2094 Stand-alone Ada Libraries
2095 -------------------------
2097 .. index:: ! Stand-alone libraries
2099 .. _Introduction_to_Stand-alone_Libraries:
2101 Introduction to Stand-alone Libraries
2102 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2104 A Stand-alone Library (abbreviated 'SAL') is a library that contains the
2106 elaborate the Ada units that are included in the library. In contrast with
2107 an ordinary library, which consists of all sources, objects and :file:`ALI`
2109 library, a SAL may specify a restricted subset of compilation units
2110 to serve as a library interface. In this case, the fully
2111 self-sufficient set of files will normally consist of an objects
2112 archive, the sources of interface units' specs, and the :file:`ALI`
2113 files of interface units.
2114 If an interface spec contains a generic unit or an inlined subprogram,
2116 source must also be provided; if the units that must be provided in the source
2117 form depend on other units, the source and :file:`ALI` files of those must
2120 The main purpose of a SAL is to minimize the recompilation overhead of client
2121 applications when a new version of the library is installed. Specifically,
2122 if the interface sources have not changed, client applications do not need to
2123 be recompiled. If, furthermore, a SAL is provided in the shared form and its
2124 version, controlled by `Library_Version` attribute, is not changed,
2125 then the clients do not need to be relinked.
2127 SALs also allow the library providers to minimize the amount of library source
2128 text exposed to the clients. Such 'information hiding' might be useful or
2129 necessary for various reasons.
2131 Stand-alone libraries are also well suited to be used in an executable whose
2132 main routine is not written in Ada.
2134 .. _Building_a_Stand-alone_Library:
2136 Building a Stand-alone Library
2137 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2139 GNAT's Project facility provides a simple way of building and installing
2140 stand-alone libraries; see :ref:`Stand-alone_Library_Projects`.
2141 To be a Stand-alone Library Project, in addition to the two attributes
2142 that make a project a Library Project (`Library_Name` and
2143 `Library_Dir`; see :ref:`Library_Projects`), the attribute
2144 `Library_Interface` must be defined. For example:
2148 for Library_Dir use "lib_dir";
2149 for Library_Name use "dummy";
2150 for Library_Interface use ("int1", "int1.child");
2152 Attribute `Library_Interface` has a non-empty string list value,
2153 each string in the list designating a unit contained in an immediate source
2154 of the project file.
2156 When a Stand-alone Library is built, first the binder is invoked to build
2157 a package whose name depends on the library name
2158 (:file:`b~dummy.ads/b` in the example above).
2159 This binder-generated package includes initialization and
2160 finalization procedures whose
2161 names depend on the library name (`dummyinit` and `dummyfinal`
2163 above). The object corresponding to this package is included in the library.
2165 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
2166 calling of these procedures if a static SAL is built, or if a shared SAL
2168 with the project-level attribute `Library_Auto_Init` set to
2171 For a Stand-Alone Library, only the :file:`ALI` files of the Interface Units
2172 (those that are listed in attribute `Library_Interface`) are copied to
2173 the Library Directory. As a consequence, only the Interface Units may be
2174 imported from Ada units outside of the library. If other units are imported,
2175 the binding phase will fail.
2177 It is also possible to build an encapsulated library where not only
2178 the code to elaborate and finalize the library is embedded but also
2179 ensuring that the library is linked only against static
2180 libraries. So an encapsulated library only depends on system
2181 libraries, all other code, including the GNAT runtime, is embedded. To
2182 build an encapsulated library the attribute
2183 `Library_Standalone` must be set to `encapsulated`:
2187 for Library_Dir use "lib_dir";
2188 for Library_Name use "dummy";
2189 for Library_Kind use "dynamic";
2190 for Library_Interface use ("int1", "int1.child");
2191 for Library_Standalone use "encapsulated";
2193 The default value for this attribute is `standard` in which case
2194 a stand-alone library is built.
2196 The attribute `Library_Src_Dir` may be specified for a
2197 Stand-Alone Library. `Library_Src_Dir` is a simple attribute that has a
2198 single string value. Its value must be the path (absolute or relative to the
2199 project directory) of an existing directory. This directory cannot be the
2200 object directory or one of the source directories, but it can be the same as
2201 the library directory. The sources of the Interface
2202 Units of the library that are needed by an Ada client of the library will be
2203 copied to the designated directory, called the Interface Copy directory.
2204 These sources include the specs of the Interface Units, but they may also
2205 include bodies and subunits, when pragmas `Inline` or `Inline_Always`
2206 are used, or when there is a generic unit in the spec. Before the sources
2207 are copied to the Interface Copy directory, an attempt is made to delete all
2208 files in the Interface Copy directory.
2210 Building stand-alone libraries by hand is somewhat tedious, but for those
2211 occasions when it is necessary here are the steps that you need to perform:
2213 * Compile all library sources.
2215 * Invoke the binder with the switch *-n* (No Ada main program),
2216 with all the :file:`ALI` files of the interfaces, and
2217 with the switch *-L* to give specific names to the `init`
2218 and `final` procedures. For example:
2222 $ gnatbind -n int1.ali int2.ali -Lsal1
2224 * Compile the binder generated file:
2230 * Link the dynamic library with all the necessary object files,
2231 indicating to the linker the names of the `init` (and possibly
2232 `final`) procedures for automatic initialization (and finalization).
2233 The built library should be placed in a directory different from
2234 the object directory.
2236 * Copy the `ALI` files of the interface to the library directory,
2237 add in this copy an indication that it is an interface to a SAL
2238 (i.e., add a word *SL* on the line in the :file:`ALI` file that starts
2239 with letter 'P') and make the modified copy of the :file:`ALI` file
2242 Using SALs is not different from using other libraries
2243 (see :ref:`Using_a_library`).
2245 .. _Creating_a_Stand-alone_Library_to_be_used_in_a_non-Ada_context:
2247 Creating a Stand-alone Library to be used in a non-Ada context
2248 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2250 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
2253 The only extra step required is to ensure that library interface subprograms
2254 are compatible with the main program, by means of `pragma Export`
2255 or `pragma Convention`.
2257 Here is an example of simple library interface for use with C main program:
2261 package My_Package is
2263 procedure Do_Something;
2264 pragma Export (C, Do_Something, "do_something");
2266 procedure Do_Something_Else;
2267 pragma Export (C, Do_Something_Else, "do_something_else");
2271 On the foreign language side, you must provide a 'foreign' view of the
2272 library interface; remember that it should contain elaboration routines in
2273 addition to interface subprograms.
2275 The example below shows the content of `mylib_interface.h` (note
2276 that there is no rule for the naming of this file, any name can be used)
2280 /* the library elaboration procedure */
2281 extern void mylibinit (void);
2283 /* the library finalization procedure */
2284 extern void mylibfinal (void);
2286 /* the interface exported by the library */
2287 extern void do_something (void);
2288 extern void do_something_else (void);
2290 Libraries built as explained above can be used from any program, provided
2291 that the elaboration procedures (named `mylibinit` in the previous
2292 example) are called before the library services are used. Any number of
2293 libraries can be used simultaneously, as long as the elaboration
2294 procedure of each library is called.
2296 Below is an example of a C program that uses the `mylib` library.
2300 #include "mylib_interface.h"
2305 /* First, elaborate the library before using it */
2308 /* Main program, using the library exported entities */
2310 do_something_else ();
2312 /* Library finalization at the end of the program */
2317 Note that invoking any library finalization procedure generated by
2318 `gnatbind` shuts down the Ada run-time environment.
2320 finalization of all Ada libraries must be performed at the end of the program.
2321 No call to these libraries or to the Ada run-time library should be made
2322 after the finalization phase.
2324 Note also that special care must be taken with multi-tasks
2325 applications. The initialization and finalization routines are not
2326 protected against concurrent access. If such requirement is needed it
2327 must be ensured at the application level using a specific operating
2328 system services like a mutex or a critical-section.
2330 .. _Restrictions_in_Stand-alone_Libraries:
2332 Restrictions in Stand-alone Libraries
2333 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2335 The pragmas listed below should be used with caution inside libraries,
2336 as they can create incompatibilities with other Ada libraries:
2338 * pragma `Locking_Policy`
2339 * pragma `Partition_Elaboration_Policy`
2340 * pragma `Queuing_Policy`
2341 * pragma `Task_Dispatching_Policy`
2342 * pragma `Unreserve_All_Interrupts`
2344 When using a library that contains such pragmas, the user must make sure
2345 that all libraries use the same pragmas with the same values. Otherwise,
2346 `Program_Error` will
2347 be raised during the elaboration of the conflicting
2348 libraries. The usage of these pragmas and its consequences for the user
2349 should therefore be well documented.
2351 Similarly, the traceback in the exception occurrence mechanism should be
2352 enabled or disabled in a consistent manner across all libraries.
2353 Otherwise, Program_Error will be raised during the elaboration of the
2354 conflicting libraries.
2356 If the `Version` or `Body_Version`
2357 attributes are used inside a library, then you need to
2358 perform a `gnatbind` step that specifies all :file:`ALI` files in all
2359 libraries, so that version identifiers can be properly computed.
2360 In practice these attributes are rarely used, so this is unlikely
2361 to be a consideration.
2363 .. _Rebuilding_the_GNAT_Run-Time_Library:
2365 Rebuilding the GNAT Run-Time Library
2366 ------------------------------------
2368 .. index:: GNAT Run-Time Library, rebuilding
2369 .. index:: Building the GNAT Run-Time Library
2370 .. index:: Rebuilding the GNAT Run-Time Library
2371 .. index:: Run-Time Library, rebuilding
2373 It may be useful to recompile the GNAT library in various contexts, the
2374 most important one being the use of partition-wide configuration pragmas
2375 such as `Normalize_Scalars`. A special Makefile called
2376 `Makefile.adalib` is provided to that effect and can be found in
2377 the directory containing the GNAT library. The location of this
2378 directory depends on the way the GNAT environment has been installed and can
2379 be determined by means of the command:
2385 The last entry in the object search path usually contains the
2386 gnat library. This Makefile contains its own documentation and in
2387 particular the set of instructions needed to rebuild a new library and
2391 .. index:: ! Conditional compilation
2393 .. _Conditional_Compilation:
2395 Conditional Compilation
2396 =======================
2398 This section presents some guidelines for modeling conditional compilation in Ada and describes the
2399 gnatprep preprocessor utility.
2401 .. index:: ! Conditional compilation
2403 .. _Modeling_Conditional_Compilation_in_Ada:
2405 Modeling Conditional Compilation in Ada
2406 ---------------------------------------
2408 It is often necessary to arrange for a single source program
2409 to serve multiple purposes, where it is compiled in different
2410 ways to achieve these different goals. Some examples of the
2411 need for this feature are
2413 * Adapting a program to a different hardware environment
2414 * Adapting a program to a different target architecture
2415 * Turning debugging features on and off
2416 * Arranging for a program to compile with different compilers
2418 In C, or C++, the typical approach would be to use the preprocessor
2419 that is defined as part of the language. The Ada language does not
2420 contain such a feature. This is not an oversight, but rather a very
2421 deliberate design decision, based on the experience that overuse of
2422 the preprocessing features in C and C++ can result in programs that
2423 are extremely difficult to maintain. For example, if we have ten
2424 switches that can be on or off, this means that there are a thousand
2425 separate programs, any one of which might not even be syntactically
2426 correct, and even if syntactically correct, the resulting program
2427 might not work correctly. Testing all combinations can quickly become
2430 Nevertheless, the need to tailor programs certainly exists, and in
2431 this section we will discuss how this can
2432 be achieved using Ada in general, and GNAT in particular.
2434 .. _Use_of_Boolean_Constants:
2436 Use of Boolean Constants
2437 ^^^^^^^^^^^^^^^^^^^^^^^^
2439 In the case where the difference is simply which code
2440 sequence is executed, the cleanest solution is to use Boolean
2441 constants to control which code is executed.
2445 FP_Initialize_Required : constant Boolean := True;
2447 if FP_Initialize_Required then
2451 Not only will the code inside the `if` statement not be executed if
2452 the constant Boolean is `False`, but it will also be completely
2453 deleted from the program.
2454 However, the code is only deleted after the `if` statement
2455 has been checked for syntactic and semantic correctness.
2456 (In contrast, with preprocessors the code is deleted before the
2457 compiler ever gets to see it, so it is not checked until the switch
2460 .. index:: Preprocessors (contrasted with conditional compilation)
2462 Typically the Boolean constants will be in a separate package,
2468 FP_Initialize_Required : constant Boolean := True;
2469 Reset_Available : constant Boolean := False;
2473 The `Config` package exists in multiple forms for the various targets,
2474 with an appropriate script selecting the version of `Config` needed.
2475 Then any other unit requiring conditional compilation can do a |with|
2476 of `Config` to make the constants visible.
2478 .. _Debugging_-_A_Special_Case:
2480 Debugging - A Special Case
2481 ^^^^^^^^^^^^^^^^^^^^^^^^^^
2483 A common use of conditional code is to execute statements (for example
2484 dynamic checks, or output of intermediate results) under control of a
2485 debug switch, so that the debugging behavior can be turned on and off.
2486 This can be done using a Boolean constant to control whether the code
2492 Put_Line ("got to the first stage!");
2499 if Debugging and then Temperature > 999.0 then
2500 raise Temperature_Crazy;
2503 .. index:: pragma Assert
2505 Since this is a common case, there are special features to deal with
2506 this in a convenient manner. For the case of tests, Ada 2005 has added
2507 a pragma `Assert` that can be used for such tests. This pragma is modeled
2508 on the `Assert` pragma that has always been available in GNAT, so this
2509 feature may be used with GNAT even if you are not using Ada 2005 features.
2510 The use of pragma `Assert` is described in the
2511 :title:`GNAT_Reference_Manual`, but as an
2512 example, the last test could be written:
2516 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
2522 pragma Assert (Temperature <= 999.0);
2524 In both cases, if assertions are active and the temperature is excessive,
2525 the exception `Assert_Failure` will be raised, with the given string in
2526 the first case or a string indicating the location of the pragma in the second
2527 case used as the exception message.
2529 .. index:: pragma Assertion_Policy
2531 You can turn assertions on and off by using the `Assertion_Policy`
2534 .. index:: -gnata switch
2536 This is an Ada 2005 pragma which is implemented in all modes by
2537 GNAT. Alternatively, you can use the *-gnata* switch
2538 to enable assertions from the command line, which applies to
2539 all versions of Ada.
2541 .. index:: pragma Debug
2543 For the example above with the `Put_Line`, the GNAT-specific pragma
2544 `Debug` can be used:
2548 pragma Debug (Put_Line ("got to the first stage!"));
2550 If debug pragmas are enabled, the argument, which must be of the form of
2551 a procedure call, is executed (in this case, `Put_Line` will be called).
2552 Only one call can be present, but of course a special debugging procedure
2553 containing any code you like can be included in the program and then
2554 called in a pragma `Debug` argument as needed.
2556 One advantage of pragma `Debug` over the `if Debugging then`
2557 construct is that pragma `Debug` can appear in declarative contexts,
2558 such as at the very beginning of a procedure, before local declarations have
2561 .. index:: pragma Debug_Policy
2563 Debug pragmas are enabled using either the *-gnata* switch that also
2564 controls assertions, or with a separate Debug_Policy pragma.
2566 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
2567 in Ada 95 and Ada 83 programs as well), and is analogous to
2568 pragma `Assertion_Policy` to control assertions.
2570 `Assertion_Policy` and `Debug_Policy` are configuration pragmas,
2571 and thus they can appear in :file:`gnat.adc` if you are not using a
2572 project file, or in the file designated to contain configuration pragmas
2574 They then apply to all subsequent compilations. In practice the use of
2575 the *-gnata* switch is often the most convenient method of controlling
2576 the status of these pragmas.
2578 Note that a pragma is not a statement, so in contexts where a statement
2579 sequence is required, you can't just write a pragma on its own. You have
2580 to add a `null` statement.
2585 ... -- some statements
2587 pragma Assert (Num_Cases < 10);
2591 .. _Conditionalizing_Declarations:
2593 Conditionalizing Declarations
2594 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2596 In some cases it may be necessary to conditionalize declarations to meet
2597 different requirements. For example we might want a bit string whose length
2598 is set to meet some hardware message requirement.
2600 This may be possible using declare blocks controlled
2601 by conditional constants:
2605 if Small_Machine then
2607 X : Bit_String (1 .. 10);
2613 X : Large_Bit_String (1 .. 1000);
2619 Note that in this approach, both declarations are analyzed by the
2620 compiler so this can only be used where both declarations are legal,
2621 even though one of them will not be used.
2623 Another approach is to define integer constants, e.g., `Bits_Per_Word`,
2624 or Boolean constants, e.g., `Little_Endian`, and then write declarations
2625 that are parameterized by these constants. For example
2630 Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
2633 If `Bits_Per_Word` is set to 32, this generates either
2638 Field1 at 0 range 0 .. 32;
2641 for the big endian case, or
2646 Field1 at 0 range 10 .. 32;
2649 for the little endian case. Since a powerful subset of Ada expression
2650 notation is usable for creating static constants, clever use of this
2651 feature can often solve quite difficult problems in conditionalizing
2652 compilation (note incidentally that in Ada 95, the little endian
2653 constant was introduced as `System.Default_Bit_Order`, so you do not
2654 need to define this one yourself).
2656 .. _Use_of_Alternative_Implementations:
2658 Use of Alternative Implementations
2659 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2661 In some cases, none of the approaches described above are adequate. This
2662 can occur for example if the set of declarations required is radically
2663 different for two different configurations.
2665 In this situation, the official Ada way of dealing with conditionalizing
2666 such code is to write separate units for the different cases. As long as
2667 this does not result in excessive duplication of code, this can be done
2668 without creating maintenance problems. The approach is to share common
2669 code as far as possible, and then isolate the code and declarations
2670 that are different. Subunits are often a convenient method for breaking
2671 out a piece of a unit that is to be conditionalized, with separate files
2672 for different versions of the subunit for different targets, where the
2673 build script selects the right one to give to the compiler.
2675 .. index:: Subunits (and conditional compilation)
2677 As an example, consider a situation where a new feature in Ada 2005
2678 allows something to be done in a really nice way. But your code must be able
2679 to compile with an Ada 95 compiler. Conceptually you want to say:
2684 ... neat Ada 2005 code
2686 ... not quite as neat Ada 95 code
2689 where `Ada_2005` is a Boolean constant.
2691 But this won't work when `Ada_2005` is set to `False`,
2692 since the `then` clause will be illegal for an Ada 95 compiler.
2693 (Recall that although such unreachable code would eventually be deleted
2694 by the compiler, it still needs to be legal. If it uses features
2695 introduced in Ada 2005, it will be illegal in Ada 95.)
2701 procedure Insert is separate;
2703 Then we have two files for the subunit `Insert`, with the two sets of
2705 If the package containing this is called `File_Queries`, then we might
2708 * :file:`file_queries-insert-2005.adb`
2709 * :file:`file_queries-insert-95.adb`
2711 and the build script renames the appropriate file to :file:`file_queries-insert.adb` and then carries out the compilation.
2713 This can also be done with project files' naming schemes. For example:
2717 for body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
2719 Note also that with project files it is desirable to use a different extension
2720 than :file:`ads` / :file:`adb` for alternative versions. Otherwise a naming
2721 conflict may arise through another commonly used feature: to declare as part
2722 of the project a set of directories containing all the sources obeying the
2723 default naming scheme.
2725 The use of alternative units is certainly feasible in all situations,
2726 and for example the Ada part of the GNAT run-time is conditionalized
2727 based on the target architecture using this approach. As a specific example,
2728 consider the implementation of the AST feature in VMS. There is one
2729 spec: :file:`s-asthan.ads` which is the same for all architectures, and three
2732 * :file:`s-asthan.adb`
2733 used for all non-VMS operating systems
2735 * :file:`s-asthan-vms-alpha.adb`
2736 used for VMS on the Alpha
2738 * :file:`s-asthan-vms-ia64.adb`
2739 used for VMS on the ia64
2741 The dummy version :file:`s-asthan.adb` simply raises exceptions noting that
2742 this operating system feature is not available, and the two remaining
2743 versions interface with the corresponding versions of VMS to provide
2744 VMS-compatible AST handling. The GNAT build script knows the architecture
2745 and operating system, and automatically selects the right version,
2746 renaming it if necessary to :file:`s-asthan.adb` before the run-time build.
2748 Another style for arranging alternative implementations is through Ada's
2749 access-to-subprogram facility.
2750 In case some functionality is to be conditionally included,
2751 you can declare an access-to-procedure variable `Ref` that is initialized
2752 to designate a 'do nothing' procedure, and then invoke `Ref.all`
2754 In some library package, set `Ref` to `Proc'Access` for some
2755 procedure `Proc` that performs the relevant processing.
2756 The initialization only occurs if the library package is included in the
2758 The same idea can also be implemented using tagged types and dispatching
2766 .. index:: Preprocessing
2768 Although it is quite possible to conditionalize code without the use of
2769 C-style preprocessing, as described earlier in this section, it is
2770 nevertheless convenient in some cases to use the C approach. Moreover,
2771 older Ada compilers have often provided some preprocessing capability,
2772 so legacy code may depend on this approach, even though it is not
2775 To accommodate such use, GNAT provides a preprocessor (modeled to a large
2776 extent on the various preprocessors that have been used
2777 with legacy code on other compilers, to enable easier transition).
2781 The preprocessor may be used in two separate modes. It can be used quite
2782 separately from the compiler, to generate a separate output source file
2783 that is then fed to the compiler as a separate step. This is the
2784 `gnatprep` utility, whose use is fully described in
2785 :ref:`Preprocessing_with_gnatprep`.
2787 The preprocessing language allows such constructs as
2791 #if DEBUG or else (PRIORITY > 4) then
2792 bunch of declarations
2794 completely different bunch of declarations
2797 The values of the symbols `DEBUG` and `PRIORITY` can be
2798 defined either on the command line or in a separate file.
2800 The other way of running the preprocessor is even closer to the C style and
2801 often more convenient. In this approach the preprocessing is integrated into
2802 the compilation process. The compiler is fed the preprocessor input which
2803 includes `#if` lines etc, and then the compiler carries out the
2804 preprocessing internally and processes the resulting output.
2805 For more details on this approach, see :ref:`Integrated_Preprocessing`.
2807 .. _Preprocessing_with_gnatprep:
2809 Preprocessing with `gnatprep`
2810 -----------------------------
2812 .. index:: ! gnatprep
2813 .. index:: Preprocessing (gnatprep)
2815 This section discusses how to use GNAT's `gnatprep` utility for simple
2817 Although designed for use with GNAT, `gnatprep` does not depend on any
2818 special GNAT features.
2819 For further discussion of conditional compilation in general, see
2820 :ref:`Conditional_Compilation`.
2822 .. _Preprocessing_Symbols:
2824 Preprocessing Symbols
2825 ^^^^^^^^^^^^^^^^^^^^^
2827 Preprocessing symbols are defined in definition files and referred to in
2828 sources to be preprocessed. A Preprocessing symbol is an identifier, following
2829 normal Ada (case-insensitive) rules for its syntax, with the restriction that
2830 all characters need to be in the ASCII set (no accented letters).
2837 To call `gnatprep` use:
2841 $ gnatprep [`switches`] `infile` `outfile` [`deffile`]
2846 is an optional sequence of switches as described in the next section.
2849 is the full name of the input file, which is an Ada source
2850 file containing preprocessor directives.
2853 is the full name of the output file, which is an Ada source
2854 in standard Ada form. When used with GNAT, this file name will
2855 normally have an ads or adb suffix.
2858 is the full name of a text file containing definitions of
2859 preprocessing symbols to be referenced by the preprocessor. This argument is
2860 optional, and can be replaced by the use of the *-D* switch.
2863 .. _Switches_for_gnatprep:
2865 Switches for `gnatprep`
2866 ^^^^^^^^^^^^^^^^^^^^^^^
2868 .. index:: -b (gnatprep)
2871 Causes both preprocessor lines and the lines deleted by
2872 preprocessing to be replaced by blank lines in the output source file,
2873 preserving line numbers in the output file.
2875 .. index:: -c (gnatprep)
2878 Causes both preprocessor lines and the lines deleted
2879 by preprocessing to be retained in the output source as comments marked
2880 with the special string `"--! "`. This option will result in line numbers
2881 being preserved in the output file.
2883 .. index:: -C (gnatprep)
2886 Causes comments to be scanned. Normally comments are ignored by gnatprep.
2887 If this option is specified, then comments are scanned and any $symbol
2888 substitutions performed as in program text. This is particularly useful
2889 when structured comments are used (e.g., when writing programs in the
2890 SPARK dialect of Ada). Note that this switch is not available when
2891 doing integrated preprocessing (it would be useless in this context
2892 since comments are ignored by the compiler in any case).
2894 .. index:: -D (gnatprep)
2896 :samp:`-D{symbol}={value}`
2897 Defines a new preprocessing symbol, associated with value. If no value is given
2898 on the command line, then symbol is considered to be `True`. This switch
2899 can be used in place of a definition file.
2901 .. index:: -r (gnatprep)
2904 Causes a `Source_Reference` pragma to be generated that
2905 references the original input file, so that error messages will use
2906 the file name of this original file. The use of this switch implies
2907 that preprocessor lines are not to be removed from the file, so its
2908 use will force *-b* mode if *-c*
2909 has not been specified explicitly.
2911 Note that if the file to be preprocessed contains multiple units, then
2912 it will be necessary to `gnatchop` the output file from
2913 `gnatprep`. If a `Source_Reference` pragma is present
2914 in the preprocessed file, it will be respected by
2916 so that the final chopped files will correctly refer to the original
2917 input source file for `gnatprep`.
2919 .. index:: -s (gnatprep)
2922 Causes a sorted list of symbol names and values to be
2923 listed on the standard output file.
2925 .. index:: -u (gnatprep)
2928 Causes undefined symbols to be treated as having the value FALSE in the context
2929 of a preprocessor test. In the absence of this option, an undefined symbol in
2930 a `#if` or `#elsif` test will be treated as an error.
2933 Note: if neither *-b* nor *-c* is present,
2934 then preprocessor lines and
2935 deleted lines are completely removed from the output, unless -r is
2936 specified, in which case -b is assumed.
2939 .. _Form_of_Definitions_File:
2941 Form of Definitions File
2942 ^^^^^^^^^^^^^^^^^^^^^^^^
2944 The definitions file contains lines of the form::
2948 where `symbol` is a preprocessing symbol, and `value` is one of the following:
2950 * Empty, corresponding to a null substitution,
2951 * A string literal using normal Ada syntax, or
2952 * Any sequence of characters from the set {letters, digits, period, underline}.
2954 Comment lines may also appear in the definitions file, starting with
2956 and comments may be added to the definitions lines.
2959 .. _Form_of_Input_Text_for_gnatprep:
2961 Form of Input Text for `gnatprep`
2962 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2964 The input text may contain preprocessor conditional inclusion lines,
2965 as well as general symbol substitution sequences.
2967 The preprocessor conditional inclusion commands have the form:
2971 #if <expression> [then]
2973 #elsif <expression> [then]
2975 #elsif <expression> [then]
2982 In this example, <expression> is defined by the following grammar::
2984 <expression> ::= <symbol>
2985 <expression> ::= <symbol> = "<value>"
2986 <expression> ::= <symbol> = <symbol>
2987 <expression> ::= <symbol> = <integer>
2988 <expression> ::= <symbol> > <integer>
2989 <expression> ::= <symbol> >= <integer>
2990 <expression> ::= <symbol> < <integer>
2991 <expression> ::= <symbol> <= <integer>
2992 <expression> ::= <symbol> 'Defined
2993 <expression> ::= not <expression>
2994 <expression> ::= <expression> and <expression>
2995 <expression> ::= <expression> or <expression>
2996 <expression> ::= <expression> and then <expression>
2997 <expression> ::= <expression> or else <expression>
2998 <expression> ::= ( <expression> )
3000 Note the following restriction: it is not allowed to have "and" or "or"
3001 following "not" in the same expression without parentheses. For example, this
3008 This can be expressed instead as one of the following forms:
3015 For the first test (<expression> ::= <symbol>) the symbol must have
3016 either the value true or false, that is to say the right-hand of the
3017 symbol definition must be one of the (case-insensitive) literals
3018 `True` or `False`. If the value is true, then the
3019 corresponding lines are included, and if the value is false, they are
3022 When comparing a symbol to an integer, the integer is any non negative
3023 literal integer as defined in the Ada Reference Manual, such as 3, 16#FF# or
3024 2#11#. The symbol value must also be a non negative integer. Integer values
3025 in the range 0 .. 2**31-1 are supported.
3027 The test (<expression> ::= <symbol>'Defined) is true only if
3028 the symbol has been defined in the definition file or by a *-D*
3029 switch on the command line. Otherwise, the test is false.
3031 The equality tests are case insensitive, as are all the preprocessor lines.
3033 If the symbol referenced is not defined in the symbol definitions file,
3034 then the effect depends on whether or not switch *-u*
3035 is specified. If so, then the symbol is treated as if it had the value
3036 false and the test fails. If this switch is not specified, then
3037 it is an error to reference an undefined symbol. It is also an error to
3038 reference a symbol that is defined with a value other than `True`
3041 The use of the `not` operator inverts the sense of this logical test.
3042 The `not` operator cannot be combined with the `or` or `and`
3043 operators, without parentheses. For example, "if not X or Y then" is not
3044 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
3046 The `then` keyword is optional as shown
3048 The `#` must be the first non-blank character on a line, but
3049 otherwise the format is free form. Spaces or tabs may appear between
3050 the `#` and the keyword. The keywords and the symbols are case
3051 insensitive as in normal Ada code. Comments may be used on a
3052 preprocessor line, but other than that, no other tokens may appear on a
3053 preprocessor line. Any number of `elsif` clauses can be present,
3054 including none at all. The `else` is optional, as in Ada.
3056 The `#` marking the start of a preprocessor line must be the first
3057 non-blank character on the line, i.e., it must be preceded only by
3058 spaces or horizontal tabs.
3060 Symbol substitution outside of preprocessor lines is obtained by using
3065 anywhere within a source line, except in a comment or within a
3066 string literal. The identifier
3067 following the `$` must match one of the symbols defined in the symbol
3068 definition file, and the result is to substitute the value of the
3069 symbol in place of `$symbol` in the output file.
3071 Note that although the substitution of strings within a string literal
3072 is not possible, it is possible to have a symbol whose defined value is
3073 a string literal. So instead of setting XYZ to `hello` and writing:
3077 Header : String := "$XYZ";
3079 you should set XYZ to `"hello"` and write:
3083 Header : String := $XYZ;
3085 and then the substitution will occur as desired.
3088 .. _Integrated_Preprocessing:
3090 Integrated Preprocessing
3091 ------------------------
3093 GNAT sources may be preprocessed immediately before compilation.
3094 In this case, the actual
3095 text of the source is not the text of the source file, but is derived from it
3096 through a process called preprocessing. Integrated preprocessing is specified
3097 through switches *-gnatep* and/or *-gnateD*. *-gnatep*
3098 indicates, through a text file, the preprocessing data to be used.
3099 :samp:`-gnateD` specifies or modifies the values of preprocessing symbol.
3100 Note that integrated preprocessing applies only to Ada source files, it is
3101 not available for configuration pragma files.
3103 Note that when integrated preprocessing is used, the output from the
3104 preprocessor is not written to any external file. Instead it is passed
3105 internally to the compiler. If you need to preserve the result of
3106 preprocessing in a file, then you should use *gnatprep*
3107 to perform the desired preprocessing in stand-alone mode.
3109 It is recommended that *gnatmake* switch -s should be
3110 used when Integrated Preprocessing is used. The reason is that preprocessing
3111 with another Preprocessing Data file without changing the sources will
3112 not trigger recompilation without this switch.
3114 Note that *gnatmake* switch -m will almost
3115 always trigger recompilation for sources that are preprocessed,
3116 because *gnatmake* cannot compute the checksum of the source after
3119 The actual preprocessing function is described in detail in section
3120 :ref:`Preprocessing_with_gnatprep`. This section only describes how integrated
3121 preprocessing is triggered and parameterized.
3124 .. index:: -gnatep (gcc)
3126 :samp:`-gnatep={file}`
3127 This switch indicates to the compiler the file name (without directory
3128 information) of the preprocessor data file to use. The preprocessor data file
3129 should be found in the source directories. Note that when the compiler is
3130 called by a builder such as (*gnatmake* with a project
3131 file, if the object directory is not also a source directory, the builder needs
3132 to be called with *-x*.
3134 A preprocessing data file is a text file with significant lines indicating
3135 how should be preprocessed either a specific source or all sources not
3136 mentioned in other lines. A significant line is a nonempty, non-comment line.
3137 Comments are similar to Ada comments.
3139 Each significant line starts with either a literal string or the character '*'.
3140 A literal string is the file name (without directory information) of the source
3141 to preprocess. A character '*' indicates the preprocessing for all the sources
3142 that are not specified explicitly on other lines (order of the lines is not
3143 significant). It is an error to have two lines with the same file name or two
3144 lines starting with the character '*'.
3146 After the file name or the character '*', another optional literal string
3147 indicating the file name of the definition file to be used for preprocessing
3148 (:ref:`Form_of_Definitions_File`). The definition files are found by the
3149 compiler in one of the source directories. In some cases, when compiling
3150 a source in a directory other than the current directory, if the definition
3151 file is in the current directory, it may be necessary to add the current
3152 directory as a source directory through switch -I., otherwise
3153 the compiler would not find the definition file.
3155 Then, optionally, switches similar to those of `gnatprep` may
3156 be found. Those switches are:
3159 Causes both preprocessor lines and the lines deleted by
3160 preprocessing to be replaced by blank lines, preserving the line number.
3161 This switch is always implied; however, if specified after *-c*
3162 it cancels the effect of *-c*.
3166 Causes both preprocessor lines and the lines deleted
3167 by preprocessing to be retained as comments marked
3168 with the special string '`--!`'.
3171 :samp:`-Dsymbol={value}`
3172 Define or redefine a symbol, associated with value. A symbol is an Ada
3173 identifier, or an Ada reserved word, with the exception of `if`,
3174 `else`, `elsif`, `end`, `and`, `or` and `then`.
3175 `value` is either a literal string, an Ada identifier or any Ada reserved
3176 word. A symbol declared with this switch replaces a symbol with the
3177 same name defined in a definition file.
3181 Causes a sorted list of symbol names and values to be
3182 listed on the standard output file.
3186 Causes undefined symbols to be treated as having the value `FALSE`
3188 of a preprocessor test. In the absence of this option, an undefined symbol in
3189 a `#if` or `#elsif` test will be treated as an error.
3192 Examples of valid lines in a preprocessor data file:
3196 "toto.adb" "prep.def" -u
3197 -- preprocess "toto.adb", using definition file "prep.def",
3198 -- undefined symbol are False.
3201 -- preprocess all other sources without a definition file;
3202 -- suppressed lined are commented; symbol VERSION has the value V101.
3204 "titi.adb" "prep2.def" -s
3205 -- preprocess "titi.adb", using definition file "prep2.def";
3206 -- list all symbols with their values.
3208 .. index:: -gnateD (gcc)
3210 :samp:`-gnateDsymbol[=value]`
3211 Define or redefine a preprocessing symbol, associated with value. If no value
3212 is given on the command line, then the value of the symbol is `True`.
3213 A symbol is an identifier, following normal Ada (case-insensitive)
3214 rules for its syntax, and value is either an arbitrary string between double
3215 quotes or any sequence (including an empty sequence) of characters from the
3216 set (letters, digits, period, underline).
3217 Ada reserved words may be used as symbols, with the exceptions of `if`,
3218 `else`, `elsif`, `end`, `and`, `or` and `then`.
3224 -gnateDFoo=\"Foo-Bar\"
3226 A symbol declared with this switch on the command line replaces a
3227 symbol with the same name either in a definition file or specified with a
3228 switch -D in the preprocessor data file.
3230 This switch is similar to switch *-D* of `gnatprep`.
3234 When integrated preprocessing is performed and the preprocessor modifies
3235 the source text, write the result of this preprocessing into a file
3239 .. _Mixed_Language_Programming:
3241 Mixed Language Programming
3242 ==========================
3244 .. index:: Mixed Language Programming
3246 This section describes how to develop a mixed-language program,
3247 with a focus on combining Ada with C or C++.
3249 .. _Interfacing_to_C:
3254 Interfacing Ada with a foreign language such as C involves using
3255 compiler directives to import and/or export entity definitions in each
3256 language -- using `extern` statements in C, for instance, and the
3257 `Import`, `Export`, and `Convention` pragmas in Ada.
3258 A full treatment of these topics is provided in Appendix B, section 1
3259 of the Ada Reference Manual.
3261 There are two ways to build a program using GNAT that contains some Ada
3262 sources and some foreign language sources, depending on whether or not
3263 the main subprogram is written in Ada. Here is a source example with
3264 the main subprogram in Ada:
3271 void print_num (int num)
3273 printf ("num is %d.\\n", num);
3281 /* num_from_Ada is declared in my_main.adb */
3282 extern int num_from_Ada;
3286 return num_from_Ada;
3292 procedure My_Main is
3294 -- Declare then export an Integer entity called num_from_Ada
3295 My_Num : Integer := 10;
3296 pragma Export (C, My_Num, "num_from_Ada");
3298 -- Declare an Ada function spec for Get_Num, then use
3299 -- C function get_num for the implementation.
3300 function Get_Num return Integer;
3301 pragma Import (C, Get_Num, "get_num");
3303 -- Declare an Ada procedure spec for Print_Num, then use
3304 -- C function print_num for the implementation.
3305 procedure Print_Num (Num : Integer);
3306 pragma Import (C, Print_Num, "print_num";
3309 Print_Num (Get_Num);
3312 To build this example:
3314 * First compile the foreign language files to
3315 generate object files:
3322 * Then, compile the Ada units to produce a set of object files and ALI
3327 $ gnatmake -c my_main.adb
3329 * Run the Ada binder on the Ada main program:
3333 $ gnatbind my_main.ali
3335 * Link the Ada main program, the Ada objects and the other language
3340 $ gnatlink my_main.ali file1.o file2.o
3342 The last three steps can be grouped in a single command:
3346 $ gnatmake my_main.adb -largs file1.o file2.o
3349 .. index:: Binder output file
3351 If the main program is in a language other than Ada, then you may have
3352 more than one entry point into the Ada subsystem. You must use a special
3353 binder option to generate callable routines that initialize and
3354 finalize the Ada units (:ref:`Binding_with_Non-Ada_Main_Programs`).
3355 Calls to the initialization and finalization routines must be inserted
3356 in the main program, or some other appropriate point in the code. The
3357 call to initialize the Ada units must occur before the first Ada
3358 subprogram is called, and the call to finalize the Ada units must occur
3359 after the last Ada subprogram returns. The binder will place the
3360 initialization and finalization subprograms into the
3361 :file:`b~xxx.adb` file where they can be accessed by your C
3362 sources. To illustrate, we have the following example:
3367 extern void adainit (void);
3368 extern void adafinal (void);
3369 extern int add (int, int);
3370 extern int sub (int, int);
3372 int main (int argc, char *argv[])
3378 /* Should print "21 + 7 = 28" */
3379 printf ("%d + %d = %d\\n", a, b, add (a, b));
3381 /* Should print "21 - 7 = 14" */
3382 printf ("%d - %d = %d\\n", a, b, sub (a, b));
3391 function Add (A, B : Integer) return Integer;
3392 pragma Export (C, Add, "add");
3398 package body Unit1 is
3399 function Add (A, B : Integer) return Integer is
3409 function Sub (A, B : Integer) return Integer;
3410 pragma Export (C, Sub, "sub");
3416 package body Unit2 is
3417 function Sub (A, B : Integer) return Integer is
3423 The build procedure for this application is similar to the last
3426 * First, compile the foreign language files to generate object files:
3433 * Next, compile the Ada units to produce a set of object files and ALI
3438 $ gnatmake -c unit1.adb
3439 $ gnatmake -c unit2.adb
3441 * Run the Ada binder on every generated ALI file. Make sure to use the
3442 :option:`-n` option to specify a foreign main program:
3446 $ gnatbind -n unit1.ali unit2.ali
3448 * Link the Ada main program, the Ada objects and the foreign language
3449 objects. You need only list the last ALI file here:
3453 $ gnatlink unit2.ali main.o -o exec_file
3455 This procedure yields a binary executable called :file:`exec_file`.
3457 Depending on the circumstances (for example when your non-Ada main object
3458 does not provide symbol `main`), you may also need to instruct the
3459 GNAT linker not to include the standard startup objects by passing the
3460 :option:`-nostartfiles` switch to `gnatlink`.
3462 .. _Calling_Conventions:
3467 .. index:: Foreign Languages
3469 .. index:: Calling Conventions
3471 GNAT follows standard calling sequence conventions and will thus interface
3472 to any other language that also follows these conventions. The following
3473 Convention identifiers are recognized by GNAT:
3476 .. index:: Interfacing to Ada
3478 .. index:: Other Ada compilers
3480 .. index:: Convention Ada
3483 This indicates that the standard Ada calling sequence will be
3484 used and all Ada data items may be passed without any limitations in the
3485 case where GNAT is used to generate both the caller and callee. It is also
3486 possible to mix GNAT generated code and code generated by another Ada
3487 compiler. In this case, the data types should be restricted to simple
3488 cases, including primitive types. Whether complex data types can be passed
3489 depends on the situation. Probably it is safe to pass simple arrays, such
3490 as arrays of integers or floats. Records may or may not work, depending
3491 on whether both compilers lay them out identically. Complex structures
3492 involving variant records, access parameters, tasks, or protected types,
3493 are unlikely to be able to be passed.
3495 Note that in the case of GNAT running
3496 on a platform that supports HP Ada 83, a higher degree of compatibility
3497 can be guaranteed, and in particular records are laid out in an identical
3498 manner in the two compilers. Note also that if output from two different
3499 compilers is mixed, the program is responsible for dealing with elaboration
3500 issues. Probably the safest approach is to write the main program in the
3501 version of Ada other than GNAT, so that it takes care of its own elaboration
3502 requirements, and then call the GNAT-generated adainit procedure to ensure
3503 elaboration of the GNAT components. Consult the documentation of the other
3504 Ada compiler for further details on elaboration.
3506 However, it is not possible to mix the tasking run time of GNAT and
3507 HP Ada 83, All the tasking operations must either be entirely within
3508 GNAT compiled sections of the program, or entirely within HP Ada 83
3509 compiled sections of the program.
3511 .. index:: Interfacing to Assembly
3513 .. index:: Convention Assembler
3517 Specifies assembler as the convention. In practice this has the
3518 same effect as convention Ada (but is not equivalent in the sense of being
3519 considered the same convention).
3521 .. index:: Convention Asm
3526 Equivalent to Assembler.
3528 .. index:: Interfacing to COBOL
3530 .. index:: Convention COBOL
3535 Data will be passed according to the conventions described
3536 in section B.4 of the Ada Reference Manual.
3539 .. index:: Interfacing to C
3541 .. index:: Convention C
3545 Data will be passed according to the conventions described
3546 in section B.3 of the Ada Reference Manual.
3548 A note on interfacing to a C 'varargs' function:
3550 .. index:: C varargs function
3551 .. index:: Interfacing to C varargs function
3552 .. index:: varargs function interfaces
3554 In C, `varargs` allows a function to take a variable number of
3555 arguments. There is no direct equivalent in this to Ada. One
3556 approach that can be used is to create a C wrapper for each
3557 different profile and then interface to this C wrapper. For
3558 example, to print an `int` value using `printf`,
3559 create a C function `printfi` that takes two arguments, a
3560 pointer to a string and an int, and calls `printf`.
3561 Then in the Ada program, use pragma `Import` to
3562 interface to `printfi`.
3564 It may work on some platforms to directly interface to
3565 a `varargs` function by providing a specific Ada profile
3566 for a particular call. However, this does not work on
3567 all platforms, since there is no guarantee that the
3568 calling sequence for a two argument normal C function
3569 is the same as for calling a `varargs` C function with
3570 the same two arguments.
3572 .. index:: Convention Default
3579 .. index:: Convention External
3587 .. index:: Interfacing to C++
3589 .. index:: Convention C++
3592 *C_Plus_Plus (or CPP)*
3593 This stands for C++. For most purposes this is identical to C.
3594 See the separate description of the specialized GNAT pragmas relating to
3595 C++ interfacing for further details.
3598 .. index:: Interfacing to Fortran
3599 .. index:: Convention Fortran
3603 Data will be passed according to the conventions described
3604 in section B.5 of the Ada Reference Manual.
3608 This applies to an intrinsic operation, as defined in the Ada
3609 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
3610 this means that the body of the subprogram is provided by the compiler itself,
3611 usually by means of an efficient code sequence, and that the user does not
3612 supply an explicit body for it. In an application program, the pragma may
3613 be applied to the following sets of names:
3616 * Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_Arithmetic.
3617 The corresponding subprogram declaration must have
3618 two formal parameters. The
3619 first one must be a signed integer type or a modular type with a binary
3620 modulus, and the second parameter must be of type Natural.
3621 The return type must be the same as the type of the first argument. The size
3622 of this type can only be 8, 16, 32, or 64.
3625 * Binary arithmetic operators: '+', '-', '*', '/'.
3626 The corresponding operator declaration must have parameters and result type
3627 that have the same root numeric type (for example, all three are long_float
3628 types). This simplifies the definition of operations that use type checking
3629 to perform dimensional checks:
3634 type Distance is new Long_Float;
3635 type Time is new Long_Float;
3636 type Velocity is new Long_Float;
3637 function "/" (D : Distance; T : Time)
3639 pragma Import (Intrinsic, "/");
3641 This common idiom is often programmed with a generic definition and an
3642 explicit body. The pragma makes it simpler to introduce such declarations.
3643 It incurs no overhead in compilation time or code size, because it is
3644 implemented as a single machine instruction.
3647 * General subprogram entities. This is used to bind an Ada subprogram
3649 a compiler builtin by name with back-ends where such interfaces are
3650 available. A typical example is the set of `__builtin` functions
3651 exposed by the GCC back-end, as in the following example:
3656 function builtin_sqrt (F : Float) return Float;
3657 pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
3659 Most of the GCC builtins are accessible this way, and as for other
3660 import conventions (e.g. C), it is the user's responsibility to ensure
3661 that the Ada subprogram profile matches the underlying builtin
3665 .. index:: Convention Stdcall
3668 This is relevant only to Windows XP/2000/NT implementations of GNAT,
3669 and specifies that the `Stdcall` calling sequence will be used,
3670 as defined by the NT API. Nevertheless, to ease building
3671 cross-platform bindings this convention will be handled as a `C` calling
3672 convention on non-Windows platforms.
3675 .. index:: Convention DLL
3679 This is equivalent to `Stdcall`.
3682 .. index:: Convention Win32
3686 This is equivalent to `Stdcall`.
3689 .. index:: Convention Stubbed
3693 This is a special convention that indicates that the compiler
3694 should provide a stub body that raises `Program_Error`.
3696 GNAT additionally provides a useful pragma `Convention_Identifier`
3697 that can be used to parameterize conventions and allow additional synonyms
3698 to be specified. For example if you have legacy code in which the convention
3699 identifier Fortran77 was used for Fortran, you can use the configuration
3704 pragma Convention_Identifier (Fortran77, Fortran);
3706 And from now on the identifier Fortran77 may be used as a convention
3707 identifier (for example in an `Import` pragma) with the same
3711 .. _Building_Mixed_Ada_and_C++_Programs:
3713 Building Mixed Ada and C++ Programs
3714 -----------------------------------
3716 A programmer inexperienced with mixed-language development may find that
3717 building an application containing both Ada and C++ code can be a
3718 challenge. This section gives a few hints that should make this task easier.
3720 .. _Interfacing_to_C++:
3725 GNAT supports interfacing with the G++ compiler (or any C++ compiler
3726 generating code that is compatible with the G++ Application Binary
3727 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
3729 Interfacing can be done at 3 levels: simple data, subprograms, and
3730 classes. In the first two cases, GNAT offers a specific `Convention C_Plus_Plus`
3731 (or `CPP`) that behaves exactly like `Convention C`.
3732 Usually, C++ mangles the names of subprograms. To generate proper mangled
3733 names automatically, see :ref:`Generating_Ada_Bindings_for_C_and_C++_headers`).
3734 This problem can also be addressed manually in two ways:
3736 * by modifying the C++ code in order to force a C convention using
3737 the `extern "C"` syntax.
3739 * by figuring out the mangled name (using e.g. *nm*) and using it as the
3740 Link_Name argument of the pragma import.
3742 Interfacing at the class level can be achieved by using the GNAT specific
3743 pragmas such as `CPP_Constructor`. See the :title:`GNAT_Reference_Manual` for additional information.
3745 .. _Linking_a_Mixed_C++_and_Ada_Program:
3747 Linking a Mixed C++ & Ada Program
3748 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3750 Usually the linker of the C++ development system must be used to link
3751 mixed applications because most C++ systems will resolve elaboration
3752 issues (such as calling constructors on global class instances)
3753 transparently during the link phase. GNAT has been adapted to ease the
3754 use of a foreign linker for the last phase. Three cases can be
3758 * Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3759 The C++ linker can simply be called by using the C++ specific driver
3762 Note that if the C++ code uses inline functions, you will need to
3763 compile your C++ code with the `-fkeep-inline-functions` switch in
3764 order to provide an existing function implementation that the Ada code can
3769 $ g++ -c -fkeep-inline-functions file1.C
3770 $ g++ -c -fkeep-inline-functions file2.C
3771 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
3774 * Using GNAT and G++ from two different GCC installations: If both
3775 compilers are on the :envvar`PATH`, the previous method may be used. It is
3776 important to note that environment variables such as
3777 :envvar:`C_INCLUDE_PATH`, :envvar:`GCC_EXEC_PREFIX`,
3778 :envvar:`BINUTILS_ROOT`, and
3779 :envvar:`GCC_ROOT` will affect both compilers
3780 at the same time and may make one of the two compilers operate
3781 improperly if set during invocation of the wrong compiler. It is also
3782 very important that the linker uses the proper :file:`libgcc.a` GCC
3783 library -- that is, the one from the C++ compiler installation. The
3784 implicit link command as suggested in the `gnatmake` command
3785 from the former example can be replaced by an explicit link command with
3786 the full-verbosity option in order to verify which library is used:
3791 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3793 If there is a problem due to interfering environment variables, it can
3794 be worked around by using an intermediate script. The following example
3795 shows the proper script to use when GNAT has not been installed at its
3796 default location and g++ has been installed at its default location:
3805 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3808 * Using a non-GNU C++ compiler: The commands previously described can be
3809 used to insure that the C++ linker is used. Nonetheless, you need to add
3810 a few more parameters to the link command line, depending on the exception
3813 If the `setjmp/longjmp` exception mechanism is used, only the paths
3814 to the libgcc libraries are required:
3820 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
3821 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3824 where CC is the name of the non-GNU C++ compiler.
3826 If the `zero cost` exception mechanism is used, and the platform
3827 supports automatic registration of exception tables (e.g., Solaris),
3828 paths to more objects are required:
3834 CC `gcc -print-file-name=crtbegin.o` $* \\
3835 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \\
3836 `gcc -print-file-name=crtend.o`
3837 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3840 If the "zero cost exception" mechanism is used, and the platform
3841 doesn't support automatic registration of exception tables (e.g., HP-UX
3842 or AIX), the simple approach described above will not work and
3843 a pre-linking phase using GNAT will be necessary.
3846 Another alternative is to use the :command:`gprbuild` multi-language builder
3847 which has a large knowledge base and knows how to link Ada and C++ code
3848 together automatically in most cases.
3850 .. _A_Simple_Example:
3855 The following example, provided as part of the GNAT examples, shows how
3856 to achieve procedural interfacing between Ada and C++ in both
3857 directions. The C++ class A has two methods. The first method is exported
3858 to Ada by the means of an extern C wrapper function. The second method
3859 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3860 a limited record with a layout comparable to the C++ class. The Ada
3861 subprogram, in turn, calls the C++ method. So, starting from the C++
3862 main program, the process passes back and forth between the two
3865 Here are the compilation commands:
3869 $ gnatmake -c simple_cpp_interface
3872 $ gnatbind -n simple_cpp_interface
3873 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++ -lstdc++ ex7.o cpp_main.o
3875 Here are the corresponding sources:
3884 void adainit (void);
3885 void adafinal (void);
3886 void method1 (A *t);
3910 class A : public Origin {
3912 void method1 (void);
3913 void method2 (int v);
3925 extern "C" { void ada_method2 (A *t, int v);}
3927 void A::method1 (void)
3930 printf ("in A::method1, a_value = %d \\n",a_value);
3933 void A::method2 (int v)
3935 ada_method2 (this, v);
3936 printf ("in A::method2, a_value = %d \\n",a_value);
3942 printf ("in A::A, a_value = %d \\n",a_value);
3947 -- simple_cpp_interface.ads
3949 package Simple_Cpp_Interface is
3952 Vptr : System.Address;
3956 pragma Convention (C, A);
3958 procedure Method1 (This : in out A);
3959 pragma Import (C, Method1);
3961 procedure Ada_Method2 (This : in out A; V : Integer);
3962 pragma Export (C, Ada_Method2);
3964 end Simple_Cpp_Interface;
3968 -- simple_cpp_interface.adb
3969 package body Simple_Cpp_Interface is
3971 procedure Ada_Method2 (This : in out A; V : Integer) is
3977 end Simple_Cpp_Interface;
3980 .. _Interfacing_with_C++_constructors:
3982 Interfacing with C++ constructors
3983 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3985 In order to interface with C++ constructors GNAT provides the
3986 `pragma CPP_Constructor` (see the :title:`GNAT_Reference_Manual`
3987 for additional information).
3988 In this section we present some common uses of C++ constructors
3989 in mixed-languages programs in GNAT.
3991 Let us assume that we need to interface with the following
4000 virtual int Get_Value ();
4001 Root(); // Default constructor
4002 Root(int v); // 1st non-default constructor
4003 Root(int v, int w); // 2nd non-default constructor
4006 For this purpose we can write the following package spec (further
4007 information on how to build this spec is available in
4008 :ref:`Interfacing_with_C++_at_the_Class_Level` and
4009 :ref:`Generating_Ada_Bindings_for_C_and_C++_headers`).
4013 with Interfaces.C; use Interfaces.C;
4015 type Root is tagged limited record
4019 pragma Import (CPP, Root);
4021 function Get_Value (Obj : Root) return int;
4022 pragma Import (CPP, Get_Value);
4024 function Constructor return Root;
4025 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
4027 function Constructor (v : Integer) return Root;
4028 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
4030 function Constructor (v, w : Integer) return Root;
4031 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
4034 On the Ada side the constructor is represented by a function (whose
4035 name is arbitrary) that returns the classwide type corresponding to
4036 the imported C++ class. Although the constructor is described as a
4037 function, it is typically a procedure with an extra implicit argument
4038 (the object being initialized) at the implementation level. GNAT
4039 issues the appropriate call, whatever it is, to get the object
4040 properly initialized.
4042 Constructors can only appear in the following contexts:
4044 * On the right side of an initialization of an object of type `T`.
4045 * On the right side of an initialization of a record component of type `T`.
4046 * In an Ada 2005 limited aggregate.
4047 * In an Ada 2005 nested limited aggregate.
4048 * In an Ada 2005 limited aggregate that initializes an object built in
4049 place by an extended return statement.
4051 In a declaration of an object whose type is a class imported from C++,
4052 either the default C++ constructor is implicitly called by GNAT, or
4053 else the required C++ constructor must be explicitly called in the
4054 expression that initializes the object. For example:
4059 Obj2 : Root := Constructor;
4060 Obj3 : Root := Constructor (v => 10);
4061 Obj4 : Root := Constructor (30, 40);
4063 The first two declarations are equivalent: in both cases the default C++
4064 constructor is invoked (in the former case the call to the constructor is
4065 implicit, and in the latter case the call is explicit in the object
4066 declaration). `Obj3` is initialized by the C++ non-default constructor
4067 that takes an integer argument, and `Obj4` is initialized by the
4068 non-default C++ constructor that takes two integers.
4070 Let us derive the imported C++ class in the Ada side. For example:
4074 type DT is new Root with record
4075 C_Value : Natural := 2009;
4078 In this case the components DT inherited from the C++ side must be
4079 initialized by a C++ constructor, and the additional Ada components
4080 of type DT are initialized by GNAT. The initialization of such an
4081 object is done either by default, or by means of a function returning
4082 an aggregate of type DT, or by means of an extension aggregate.
4087 Obj6 : DT := Function_Returning_DT (50);
4088 Obj7 : DT := (Constructor (30,40) with C_Value => 50);
4090 The declaration of `Obj5` invokes the default constructors: the
4091 C++ default constructor of the parent type takes care of the initialization
4092 of the components inherited from Root, and GNAT takes care of the default
4093 initialization of the additional Ada components of type DT (that is,
4094 `C_Value` is initialized to value 2009). The order of invocation of
4095 the constructors is consistent with the order of elaboration required by
4096 Ada and C++. That is, the constructor of the parent type is always called
4097 before the constructor of the derived type.
4099 Let us now consider a record that has components whose type is imported
4100 from C++. For example:
4104 type Rec1 is limited record
4105 Data1 : Root := Constructor (10);
4106 Value : Natural := 1000;
4109 type Rec2 (D : Integer := 20) is limited record
4111 Data2 : Root := Constructor (D, 30);
4114 The initialization of an object of type `Rec2` will call the
4115 non-default C++ constructors specified for the imported components.
4122 Using Ada 2005 we can use limited aggregates to initialize an object
4123 invoking C++ constructors that differ from those specified in the type
4124 declarations. For example:
4128 Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
4132 The above declaration uses an Ada 2005 limited aggregate to
4133 initialize `Obj9`, and the C++ constructor that has two integer
4134 arguments is invoked to initialize the `Data1` component instead
4135 of the constructor specified in the declaration of type `Rec1`. In
4136 Ada 2005 the box in the aggregate indicates that unspecified components
4137 are initialized using the expression (if any) available in the component
4138 declaration. That is, in this case discriminant `D` is initialized
4139 to value `20`, `Value` is initialized to value 1000, and the
4140 non-default C++ constructor that handles two integers takes care of
4141 initializing component `Data2` with values `20,30`.
4143 In Ada 2005 we can use the extended return statement to build the Ada
4144 equivalent to C++ non-default constructors. For example:
4148 function Constructor (V : Integer) return Rec2 is
4150 return Obj : Rec2 := (Rec => (Data1 => Constructor (V, 20),
4153 -- Further actions required for construction of
4154 -- objects of type Rec2
4159 In this example the extended return statement construct is used to
4160 build in place the returned object whose components are initialized
4161 by means of a limited aggregate. Any further action associated with
4162 the constructor can be placed inside the construct.
4164 .. _Interfacing_with_C++_at_the_Class_Level:
4166 Interfacing with C++ at the Class Level
4167 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4169 In this section we demonstrate the GNAT features for interfacing with
4170 C++ by means of an example making use of Ada 2005 abstract interface
4171 types. This example consists of a classification of animals; classes
4172 have been used to model our main classification of animals, and
4173 interfaces provide support for the management of secondary
4174 classifications. We first demonstrate a case in which the types and
4175 constructors are defined on the C++ side and imported from the Ada
4176 side, and latter the reverse case.
4178 The root of our derivation will be the `Animal` class, with a
4179 single private attribute (the `Age` of the animal), a constructor,
4180 and two public primitives to set and get the value of this attribute.
4186 virtual void Set_Age (int New_Age);
4188 Animal() {Age_Count = 0;};
4193 Abstract interface types are defined in C++ by means of classes with pure
4194 virtual functions and no data members. In our example we will use two
4195 interfaces that provide support for the common management of `Carnivore`
4196 and `Domestic` animals:
4202 virtual int Number_Of_Teeth () = 0;
4207 virtual void Set_Owner (char* Name) = 0;
4210 Using these declarations, we can now say that a `Dog` is an animal that is
4211 both Carnivore and Domestic, that is:
4215 class Dog : Animal, Carnivore, Domestic {
4217 virtual int Number_Of_Teeth ();
4218 virtual void Set_Owner (char* Name);
4220 Dog(); // Constructor
4226 In the following examples we will assume that the previous declarations are
4227 located in a file named `animals.h`. The following package demonstrates
4228 how to import these C++ declarations from the Ada side:
4232 with Interfaces.C.Strings; use Interfaces.C.Strings;
4234 type Carnivore is limited interface;
4235 pragma Convention (C_Plus_Plus, Carnivore);
4236 function Number_Of_Teeth (X : Carnivore)
4237 return Natural is abstract;
4239 type Domestic is limited interface;
4240 pragma Convention (C_Plus_Plus, Domestic);
4242 (X : in out Domestic;
4243 Name : Chars_Ptr) is abstract;
4245 type Animal is tagged limited record
4248 pragma Import (C_Plus_Plus, Animal);
4250 procedure Set_Age (X : in out Animal; Age : Integer);
4251 pragma Import (C_Plus_Plus, Set_Age);
4253 function Age (X : Animal) return Integer;
4254 pragma Import (C_Plus_Plus, Age);
4256 function New_Animal return Animal;
4257 pragma CPP_Constructor (New_Animal);
4258 pragma Import (CPP, New_Animal, "_ZN6AnimalC1Ev");
4260 type Dog is new Animal and Carnivore and Domestic with record
4261 Tooth_Count : Natural;
4262 Owner : String (1 .. 30);
4264 pragma Import (C_Plus_Plus, Dog);
4266 function Number_Of_Teeth (A : Dog) return Natural;
4267 pragma Import (C_Plus_Plus, Number_Of_Teeth);
4269 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
4270 pragma Import (C_Plus_Plus, Set_Owner);
4272 function New_Dog return Dog;
4273 pragma CPP_Constructor (New_Dog);
4274 pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
4277 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
4278 interfacing with these C++ classes is easy. The only requirement is that all
4279 the primitives and components must be declared exactly in the same order in
4282 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
4283 means of a `pragma Convention (C_Plus_Plus)`, the convention used to pass
4284 the arguments to the called primitives will be the same as for C++. For the
4285 imported classes we use `pragma Import` with convention `C_Plus_Plus`
4286 to indicate that they have been defined on the C++ side; this is required
4287 because the dispatch table associated with these tagged types will be built
4288 in the C++ side and therefore will not contain the predefined Ada primitives
4289 which Ada would otherwise expect.
4291 As the reader can see there is no need to indicate the C++ mangled names
4292 associated with each subprogram because it is assumed that all the calls to
4293 these primitives will be dispatching calls. The only exception is the
4294 constructor, which must be registered with the compiler by means of
4295 `pragma CPP_Constructor` and needs to provide its associated C++
4296 mangled name because the Ada compiler generates direct calls to it.
4298 With the above packages we can now declare objects of type Dog on the Ada side
4299 and dispatch calls to the corresponding subprograms on the C++ side. We can
4300 also extend the tagged type Dog with further fields and primitives, and
4301 override some of its C++ primitives on the Ada side. For example, here we have
4302 a type derivation defined on the Ada side that inherits all the dispatching
4303 primitives of the ancestor from the C++ side.
4307 with Animals; use Animals;
4308 package Vaccinated_Animals is
4309 type Vaccinated_Dog is new Dog with null record;
4310 function Vaccination_Expired (A : Vaccinated_Dog) return Boolean;
4311 end Vaccinated_Animals;
4313 It is important to note that, because of the ABI compatibility, the programmer
4314 does not need to add any further information to indicate either the object
4315 layout or the dispatch table entry associated with each dispatching operation.
4317 Now let us define all the types and constructors on the Ada side and export
4318 them to C++, using the same hierarchy of our previous example:
4322 with Interfaces.C.Strings;
4323 use Interfaces.C.Strings;
4325 type Carnivore is limited interface;
4326 pragma Convention (C_Plus_Plus, Carnivore);
4327 function Number_Of_Teeth (X : Carnivore)
4328 return Natural is abstract;
4330 type Domestic is limited interface;
4331 pragma Convention (C_Plus_Plus, Domestic);
4333 (X : in out Domestic;
4334 Name : Chars_Ptr) is abstract;
4336 type Animal is tagged record
4339 pragma Convention (C_Plus_Plus, Animal);
4341 procedure Set_Age (X : in out Animal; Age : Integer);
4342 pragma Export (C_Plus_Plus, Set_Age);
4344 function Age (X : Animal) return Integer;
4345 pragma Export (C_Plus_Plus, Age);
4347 function New_Animal return Animal'Class;
4348 pragma Export (C_Plus_Plus, New_Animal);
4350 type Dog is new Animal and Carnivore and Domestic with record
4351 Tooth_Count : Natural;
4352 Owner : String (1 .. 30);
4354 pragma Convention (C_Plus_Plus, Dog);
4356 function Number_Of_Teeth (A : Dog) return Natural;
4357 pragma Export (C_Plus_Plus, Number_Of_Teeth);
4359 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
4360 pragma Export (C_Plus_Plus, Set_Owner);
4362 function New_Dog return Dog'Class;
4363 pragma Export (C_Plus_Plus, New_Dog);
4366 Compared with our previous example the only differences are the use of
4367 `pragma Convention` (instead of `pragma Import`), and the use of
4368 `pragma Export` to indicate to the GNAT compiler that the primitives will
4369 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
4370 nothing else to be done; as explained above, the only requirement is that all
4371 the primitives and components are declared in exactly the same order.
4373 For completeness, let us see a brief C++ main program that uses the
4374 declarations available in `animals.h` (presented in our first example) to
4375 import and use the declarations from the Ada side, properly initializing and
4376 finalizing the Ada run-time system along the way:
4380 #include "animals.h"
4382 using namespace std;
4384 void Check_Carnivore (Carnivore *obj) {...}
4385 void Check_Domestic (Domestic *obj) {...}
4386 void Check_Animal (Animal *obj) {...}
4387 void Check_Dog (Dog *obj) {...}
4390 void adainit (void);
4391 void adafinal (void);
4397 Dog *obj = new_dog(); // Ada constructor
4398 Check_Carnivore (obj); // Check secondary DT
4399 Check_Domestic (obj); // Check secondary DT
4400 Check_Animal (obj); // Check primary DT
4401 Check_Dog (obj); // Check primary DT
4406 adainit (); test(); adafinal ();
4410 .. _Generating_Ada_Bindings_for_C_and_C++_headers:
4412 Generating Ada Bindings for C and C++ headers
4413 ---------------------------------------------
4415 .. index:: Binding generation (for C and C++ headers)
4416 .. index:: C headers (binding generation)
4417 .. index:: C++ headers (binding generation)
4419 GNAT includes a binding generator for C and C++ headers which is
4420 intended to do 95% of the tedious work of generating Ada specs from C
4421 or C++ header files.
4423 Note that this capability is not intended to generate 100% correct Ada specs,
4424 and will is some cases require manual adjustments, although it can often
4425 be used out of the box in practice.
4427 Some of the known limitations include:
4429 * only very simple character constant macros are translated into Ada
4430 constants. Function macros (macros with arguments) are partially translated
4431 as comments, to be completed manually if needed.
4432 * some extensions (e.g. vector types) are not supported
4433 * pointers to pointers or complex structures are mapped to System.Address
4434 * identifiers with identical name (except casing) will generate compilation
4435 errors (e.g. `shm_get` vs `SHM_GET`).
4437 The code generated is using the Ada 2005 syntax, which makes it
4438 easier to interface with other languages than previous versions of Ada.
4440 .. _Running_the_binding_generator:
4442 Running the binding generator
4443 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4445 The binding generator is part of the *gcc* compiler and can be
4446 invoked via the *-fdump-ada-spec* switch, which will generate Ada
4447 spec files for the header files specified on the command line, and all
4448 header files needed by these files transitively. For example:
4452 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
4453 $ gcc -c -gnat05 *.ads
4455 will generate, under GNU/Linux, the following files: :file:`time_h.ads`,
4456 :file:`bits_time_h.ads`, :file:`stddef_h.ads`, :file:`bits_types_h.ads` which
4457 correspond to the files :file:`/usr/include/time.h`,
4458 :file:`/usr/include/bits/time.h`, etc..., and will then compile in Ada 2005
4459 mode these Ada specs.
4461 The `-C` switch tells *gcc* to extract comments from headers,
4462 and will attempt to generate corresponding Ada comments.
4464 If you want to generate a single Ada file and not the transitive closure, you
4465 can use instead the *-fdump-ada-spec-slim* switch.
4467 You can optionally specify a parent unit, of which all generated units will
4468 be children, using `-fada-spec-parent=``unit`.
4470 Note that we recommend when possible to use the *g++* driver to
4471 generate bindings, even for most C headers, since this will in general
4472 generate better Ada specs. For generating bindings for C++ headers, it is
4473 mandatory to use the *g++* command, or *gcc -x c++* which
4474 is equivalent in this case. If *g++* cannot work on your C headers
4475 because of incompatibilities between C and C++, then you can fallback to
4478 For an example of better bindings generated from the C++ front-end,
4479 the name of the parameters (when available) are actually ignored by the C
4480 front-end. Consider the following C header:
4484 extern void foo (int variable);
4486 with the C front-end, `variable` is ignored, and the above is handled as:
4490 extern void foo (int);
4492 generating a generic:
4496 procedure foo (param1 : int);
4498 with the C++ front-end, the name is available, and we generate:
4502 procedure foo (variable : int);
4504 In some cases, the generated bindings will be more complete or more meaningful
4505 when defining some macros, which you can do via the *-D* switch. This
4506 is for example the case with :file:`Xlib.h` under GNU/Linux:
4510 $ g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
4512 The above will generate more complete bindings than a straight call without
4513 the *-DXLIB_ILLEGAL_ACCESS* switch.
4515 In other cases, it is not possible to parse a header file in a stand-alone
4516 manner, because other include files need to be included first. In this
4517 case, the solution is to create a small header file including the needed
4518 `#include` and possible `#define` directives. For example, to
4519 generate Ada bindings for :file:`readline/readline.h`, you need to first
4520 include :file:`stdio.h`, so you can create a file with the following two
4521 lines in e.g. :file:`readline1.h`:
4526 #include <readline/readline.h>
4528 and then generate Ada bindings from this file:
4532 $ g++ -c -fdump-ada-spec readline1.h
4535 .. _Generating_bindings_for_C++_headers:
4537 Generating bindings for C++ headers
4538 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4540 Generating bindings for C++ headers is done using the same options, always
4541 with the *g++* compiler. Note that generating Ada spec from C++ headers is a
4542 much more complex job and support for C++ headers is much more limited that
4543 support for C headers. As a result, you will need to modify the resulting
4544 bindings by hand more extensively when using C++ headers.
4546 In this mode, C++ classes will be mapped to Ada tagged types, constructors
4547 will be mapped using the `CPP_Constructor` pragma, and when possible,
4548 multiple inheritance of abstract classes will be mapped to Ada interfaces
4549 (see the *Interfacing to C++* section in the :title:`GNAT Reference Manual`
4550 for additional information on interfacing to C++).
4552 For example, given the following C++ header file:
4558 virtual int Number_Of_Teeth () = 0;
4563 virtual void Set_Owner (char* Name) = 0;
4569 virtual void Set_Age (int New_Age);
4572 class Dog : Animal, Carnivore, Domestic {
4577 virtual int Number_Of_Teeth ();
4578 virtual void Set_Owner (char* Name);
4583 The corresponding Ada code is generated:
4587 package Class_Carnivore is
4588 type Carnivore is limited interface;
4589 pragma Import (CPP, Carnivore);
4591 function Number_Of_Teeth (this : access Carnivore) return int is abstract;
4593 use Class_Carnivore;
4595 package Class_Domestic is
4596 type Domestic is limited interface;
4597 pragma Import (CPP, Domestic);
4600 (this : access Domestic;
4601 Name : Interfaces.C.Strings.chars_ptr) is abstract;
4605 package Class_Animal is
4606 type Animal is tagged limited record
4607 Age_Count : aliased int;
4609 pragma Import (CPP, Animal);
4611 procedure Set_Age (this : access Animal; New_Age : int);
4612 pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
4616 package Class_Dog is
4617 type Dog is new Animal and Carnivore and Domestic with record
4618 Tooth_Count : aliased int;
4619 Owner : Interfaces.C.Strings.chars_ptr;
4621 pragma Import (CPP, Dog);
4623 function Number_Of_Teeth (this : access Dog) return int;
4624 pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
4627 (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
4628 pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
4630 function New_Dog return Dog;
4631 pragma CPP_Constructor (New_Dog);
4632 pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
4637 .. _Switches_for_Ada_Binding_Generation:
4642 .. index:: -fdump-ada-spec (gcc)
4644 :samp:`-fdump-ada-spec`
4645 Generate Ada spec files for the given header files transitively (including
4646 all header files that these headers depend upon).
4648 .. index:: -fdump-ada-spec-slim (gcc)
4650 :samp:`-fdump-ada-spec-slim`
4651 Generate Ada spec files for the header files specified on the command line
4654 .. index:: -fada-spec-parent (gcc)
4656 :samp:`-fada-spec-parent={unit}`
4657 Specifies that all files generated by *-fdump-ada-spec** are
4658 to be child units of the specified parent unit.
4663 Extract comments from headers and generate Ada comments in the Ada spec files.
4666 .. _GNAT_and_Other_Compilation_Models:
4668 GNAT and Other Compilation Models
4669 =================================
4671 This section compares the GNAT model with the approaches taken in
4672 other environents, first the C/C++ model and then the mechanism that
4673 has been used in other Ada systems, in particular those traditionally
4676 .. _Comparison_between_GNAT_and_C/C++_Compilation_Models:
4678 Comparison between GNAT and C/C++ Compilation Models
4679 ----------------------------------------------------
4681 The GNAT model of compilation is close to the C and C++ models. You can
4682 think of Ada specs as corresponding to header files in C. As in C, you
4683 don't need to compile specs; they are compiled when they are used. The
4684 Ada |with| is similar in effect to the `#include` of a C
4687 One notable difference is that, in Ada, you may compile specs separately
4688 to check them for semantic and syntactic accuracy. This is not always
4689 possible with C headers because they are fragments of programs that have
4690 less specific syntactic or semantic rules.
4692 The other major difference is the requirement for running the binder,
4693 which performs two important functions. First, it checks for
4694 consistency. In C or C++, the only defense against assembling
4695 inconsistent programs lies outside the compiler, in a makefile, for
4696 example. The binder satisfies the Ada requirement that it be impossible
4697 to construct an inconsistent program when the compiler is used in normal
4700 .. index:: Elaboration order control
4702 The other important function of the binder is to deal with elaboration
4703 issues. There are also elaboration issues in C++ that are handled
4704 automatically. This automatic handling has the advantage of being
4705 simpler to use, but the C++ programmer has no control over elaboration.
4706 Where `gnatbind` might complain there was no valid order of
4707 elaboration, a C++ compiler would simply construct a program that
4708 malfunctioned at run time.
4710 .. _Comparison_between_GNAT_and_Conventional_Ada_Library_Models:
4712 Comparison between GNAT and Conventional Ada Library Models
4713 -----------------------------------------------------------
4715 This section is intended for Ada programmers who have
4716 used an Ada compiler implementing the traditional Ada library
4717 model, as described in the Ada Reference Manual.
4719 .. index:: GNAT library
4721 In GNAT, there is no 'library' in the normal sense. Instead, the set of
4722 source files themselves acts as the library. Compiling Ada programs does
4723 not generate any centralized information, but rather an object file and
4724 a ALI file, which are of interest only to the binder and linker.
4725 In a traditional system, the compiler reads information not only from
4726 the source file being compiled, but also from the centralized library.
4727 This means that the effect of a compilation depends on what has been
4728 previously compiled. In particular:
4730 * When a unit is |withed|, the unit seen by the compiler corresponds
4731 to the version of the unit most recently compiled into the library.
4733 * Inlining is effective only if the necessary body has already been
4734 compiled into the library.
4736 * Compiling a unit may obsolete other units in the library.
4738 In GNAT, compiling one unit never affects the compilation of any other
4739 units because the compiler reads only source files. Only changes to source
4740 files can affect the results of a compilation. In particular:
4742 * When a unit is |withed|, the unit seen by the compiler corresponds
4743 to the source version of the unit that is currently accessible to the
4748 * Inlining requires the appropriate source files for the package or
4749 subprogram bodies to be available to the compiler. Inlining is always
4750 effective, independent of the order in which units are compiled.
4752 * Compiling a unit never affects any other compilations. The editing of
4753 sources may cause previous compilations to be out of date if they
4754 depended on the source file being modified.
4756 The most important result of these differences is that order of compilation
4757 is never significant in GNAT. There is no situation in which one is
4758 required to do one compilation before another. What shows up as order of
4759 compilation requirements in the traditional Ada library becomes, in
4760 GNAT, simple source dependencies; in other words, there is only a set
4761 of rules saying what source files must be present when a file is
4765 .. _Using_GNAT_Files_with_External_Tools:
4767 Using GNAT Files with External Tools
4768 ====================================
4770 This section explains how files that are produced by GNAT may be
4771 used with tools designed for other languages.
4774 .. _Using_Other_Utility_Programs_with_GNAT:
4776 Using Other Utility Programs with GNAT
4777 --------------------------------------
4779 The object files generated by GNAT are in standard system format and in
4780 particular the debugging information uses this format. This means
4781 programs generated by GNAT can be used with existing utilities that
4782 depend on these formats.
4784 In general, any utility program that works with C will also often work with
4785 Ada programs generated by GNAT. This includes software utilities such as
4786 gprof (a profiling program), gdb (the FSF debugger), and utilities such
4790 .. _The_External_Symbol_Naming_Scheme_of_GNAT:
4792 The External Symbol Naming Scheme of GNAT
4793 -----------------------------------------
4795 In order to interpret the output from GNAT, when using tools that are
4796 originally intended for use with other languages, it is useful to
4797 understand the conventions used to generate link names from the Ada
4800 All link names are in all lowercase letters. With the exception of library
4801 procedure names, the mechanism used is simply to use the full expanded
4802 Ada name with dots replaced by double underscores. For example, suppose
4803 we have the following package spec:
4811 .. index:: pragma Export
4813 The variable `MN` has a full expanded Ada name of `QRS.MN`, so
4814 the corresponding link name is `qrs__mn`.
4815 Of course if a `pragma Export` is used this may be overridden:
4821 pragma Export (Var1, C, External_Name => "var1_name");
4823 pragma Export (Var2, C, Link_Name => "var2_link_name");
4826 In this case, the link name for `Var1` is whatever link name the
4827 C compiler would assign for the C function `var1_name`. This typically
4828 would be either `var1_name` or `_var1_name`, depending on operating
4829 system conventions, but other possibilities exist. The link name for
4830 `Var2` is `var2_link_name`, and this is not operating system
4833 One exception occurs for library level procedures. A potential ambiguity
4834 arises between the required name `_main` for the C main program,
4835 and the name we would otherwise assign to an Ada library level procedure
4836 called `Main` (which might well not be the main program).
4838 To avoid this ambiguity, we attach the prefix `_ada_` to such
4839 names. So if we have a library level procedure such as:
4843 procedure Hello (S : String);
4845 the external name of this procedure will be `_ada_hello`.