Debian Codegraph @

gcc/ada/doc/gnat_ugn/the_gnat_compilation_model.rst

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