OSDN Git Service

* extend.texi: Bring back reference to trampoline paper.
[pf3gnuchains/gcc-fork.git] / gcc / extend.texi
1 @c Copyright (C) 1988,89,92,93,94,96 Free Software Foundation, Inc.
2 @c This is part of the GCC manual.
3 @c For copying conditions, see the file gcc.texi.
4
5 @node C Extensions
6 @chapter Extensions to the C Language Family
7 @cindex extensions, C language
8 @cindex C language extensions
9
10 GNU C provides several language features not found in ANSI standard C.
11 (The @samp{-pedantic} option directs GNU CC to print a warning message if
12 any of these features is used.)  To test for the availability of these
13 features in conditional compilation, check for a predefined macro
14 @code{__GNUC__}, which is always defined under GNU CC.
15
16 These extensions are available in C and Objective C.  Most of them are
17 also available in C++.  @xref{C++ Extensions,,Extensions to the
18 C++ Language}, for extensions that apply @emph{only} to C++.
19
20 @c The only difference between the two versions of this menu is that the
21 @c version for clear INTERNALS has an extra node, "Constraints" (which
22 @c appears in a separate chapter in the other version of the manual).
23 @ifset INTERNALS
24 @menu
25 * Statement Exprs::     Putting statements and declarations inside expressions.
26 * Local Labels::        Labels local to a statement-expression.
27 * Labels as Values::    Getting pointers to labels, and computed gotos.
28 * Nested Functions::    As in Algol and Pascal, lexical scoping of functions.
29 * Constructing Calls::  Dispatching a call to another function.
30 * Naming Types::        Giving a name to the type of some expression.
31 * Typeof::              @code{typeof}: referring to the type of an expression.
32 * Lvalues::             Using @samp{?:}, @samp{,} and casts in lvalues.
33 * Conditionals::        Omitting the middle operand of a @samp{?:} expression.
34 * Long Long::           Double-word integers---@code{long long int}.
35 * Complex::             Data types for complex numbers.
36 * Zero Length::         Zero-length arrays.
37 * Variable Length::     Arrays whose length is computed at run time.
38 * Macro Varargs::       Macros with variable number of arguments.
39 * Subscripting::        Any array can be subscripted, even if not an lvalue.
40 * Pointer Arith::       Arithmetic on @code{void}-pointers and function pointers.
41 * Initializers::        Non-constant initializers.
42 * Constructors::        Constructor expressions give structures, unions
43                          or arrays as values.
44 * Labeled Elements::    Labeling elements of initializers.
45 * Cast to Union::       Casting to union type from any member of the union.
46 * Case Ranges::         `case 1 ... 9' and such.
47 * Function Attributes:: Declaring that functions have no side effects,
48                          or that they can never return.
49 * Function Prototypes:: Prototype declarations and old-style definitions.
50 * C++ Comments::        C++ comments are recognized.
51 * Dollar Signs::        Dollar sign is allowed in identifiers.
52 * Character Escapes::   @samp{\e} stands for the character @key{ESC}.
53 * Variable Attributes:: Specifying attributes of variables.
54 * Type Attributes::     Specifying attributes of types.
55 * Alignment::           Inquiring about the alignment of a type or variable.
56 * Inline::              Defining inline functions (as fast as macros).
57 * Extended Asm::        Assembler instructions with C expressions as operands.
58                          (With them you can define ``built-in'' functions.)
59 * Asm Labels::          Specifying the assembler name to use for a C symbol.
60 * Explicit Reg Vars::   Defining variables residing in specified registers.
61 * Alternate Keywords::  @code{__const__}, @code{__asm__}, etc., for header files.
62 * Incomplete Enums::    @code{enum foo;}, with details to follow.
63 * Function Names::      Printable strings which are the name of the current
64                          function.
65 * Return Address::      Getting the return or frame address of a function.
66 @end menu
67 @end ifset
68 @ifclear INTERNALS
69 @menu
70 * Statement Exprs::     Putting statements and declarations inside expressions.
71 * Local Labels::        Labels local to a statement-expression.
72 * Labels as Values::    Getting pointers to labels, and computed gotos.
73 * Nested Functions::    As in Algol and Pascal, lexical scoping of functions.
74 * Constructing Calls::  Dispatching a call to another function.
75 * Naming Types::        Giving a name to the type of some expression.
76 * Typeof::              @code{typeof}: referring to the type of an expression.
77 * Lvalues::             Using @samp{?:}, @samp{,} and casts in lvalues.
78 * Conditionals::        Omitting the middle operand of a @samp{?:} expression.
79 * Long Long::           Double-word integers---@code{long long int}.
80 * Complex::             Data types for complex numbers.
81 * Zero Length::         Zero-length arrays.
82 * Variable Length::     Arrays whose length is computed at run time.
83 * Macro Varargs::       Macros with variable number of arguments.
84 * Subscripting::        Any array can be subscripted, even if not an lvalue.
85 * Pointer Arith::       Arithmetic on @code{void}-pointers and function pointers.
86 * Initializers::        Non-constant initializers.
87 * Constructors::        Constructor expressions give structures, unions
88                          or arrays as values.
89 * Labeled Elements::    Labeling elements of initializers.
90 * Cast to Union::       Casting to union type from any member of the union.
91 * Case Ranges::         `case 1 ... 9' and such.
92 * Function Attributes:: Declaring that functions have no side effects,
93                          or that they can never return.
94 * Function Prototypes:: Prototype declarations and old-style definitions.
95 * C++ Comments::        C++ comments are recognized.
96 * Dollar Signs::        Dollar sign is allowed in identifiers.
97 * Character Escapes::   @samp{\e} stands for the character @key{ESC}.
98 * Variable Attributes:: Specifying attributes of variables.
99 * Type Attributes::     Specifying attributes of types.
100 * Alignment::           Inquiring about the alignment of a type or variable.
101 * Inline::              Defining inline functions (as fast as macros).
102 * Extended Asm::        Assembler instructions with C expressions as operands.
103                          (With them you can define ``built-in'' functions.)
104 * Constraints::         Constraints for asm operands
105 * Asm Labels::          Specifying the assembler name to use for a C symbol.
106 * Explicit Reg Vars::   Defining variables residing in specified registers.
107 * Alternate Keywords::  @code{__const__}, @code{__asm__}, etc., for header files.
108 * Incomplete Enums::    @code{enum foo;}, with details to follow.
109 * Function Names::      Printable strings which are the name of the current
110                          function.
111 * Return Address::      Getting the return or frame address of a function.
112 @end menu
113 @end ifclear
114
115 @node Statement Exprs
116 @section Statements and Declarations in Expressions
117 @cindex statements inside expressions
118 @cindex declarations inside expressions
119 @cindex expressions containing statements
120 @cindex macros, statements in expressions
121
122 @c the above section title wrapped and causes an underfull hbox.. i
123 @c changed it from "within" to "in". --mew 4feb93
124
125 A compound statement enclosed in parentheses may appear as an expression
126 in GNU C.  This allows you to use loops, switches, and local variables
127 within an expression.
128
129 Recall that a compound statement is a sequence of statements surrounded
130 by braces; in this construct, parentheses go around the braces.  For
131 example:
132
133 @example
134 (@{ int y = foo (); int z;
135    if (y > 0) z = y;
136    else z = - y;
137    z; @})
138 @end example
139
140 @noindent
141 is a valid (though slightly more complex than necessary) expression
142 for the absolute value of @code{foo ()}.
143
144 The last thing in the compound statement should be an expression
145 followed by a semicolon; the value of this subexpression serves as the
146 value of the entire construct.  (If you use some other kind of statement
147 last within the braces, the construct has type @code{void}, and thus
148 effectively no value.)
149
150 This feature is especially useful in making macro definitions ``safe'' (so
151 that they evaluate each operand exactly once).  For example, the
152 ``maximum'' function is commonly defined as a macro in standard C as
153 follows:
154
155 @example
156 #define max(a,b) ((a) > (b) ? (a) : (b))
157 @end example
158
159 @noindent
160 @cindex side effects, macro argument
161 But this definition computes either @var{a} or @var{b} twice, with bad
162 results if the operand has side effects.  In GNU C, if you know the
163 type of the operands (here let's assume @code{int}), you can define
164 the macro safely as follows:
165
166 @example
167 #define maxint(a,b) \
168   (@{int _a = (a), _b = (b); _a > _b ? _a : _b; @})
169 @end example
170
171 Embedded statements are not allowed in constant expressions, such as
172 the value of an enumeration constant, the width of a bit field, or
173 the initial value of a static variable.
174
175 If you don't know the type of the operand, you can still do this, but you
176 must use @code{typeof} (@pxref{Typeof}) or type naming (@pxref{Naming
177 Types}).
178
179 @node Local Labels
180 @section Locally Declared Labels
181 @cindex local labels
182 @cindex macros, local labels
183
184 Each statement expression is a scope in which @dfn{local labels} can be
185 declared.  A local label is simply an identifier; you can jump to it
186 with an ordinary @code{goto} statement, but only from within the
187 statement expression it belongs to.
188
189 A local label declaration looks like this:
190
191 @example
192 __label__ @var{label};
193 @end example
194
195 @noindent
196 or
197
198 @example
199 __label__ @var{label1}, @var{label2}, @dots{};
200 @end example
201
202 Local label declarations must come at the beginning of the statement
203 expression, right after the @samp{(@{}, before any ordinary
204 declarations.
205
206 The label declaration defines the label @emph{name}, but does not define
207 the label itself.  You must do this in the usual way, with
208 @code{@var{label}:}, within the statements of the statement expression.
209
210 The local label feature is useful because statement expressions are
211 often used in macros.  If the macro contains nested loops, a @code{goto}
212 can be useful for breaking out of them.  However, an ordinary label
213 whose scope is the whole function cannot be used: if the macro can be
214 expanded several times in one function, the label will be multiply
215 defined in that function.  A local label avoids this problem.  For
216 example:
217
218 @example
219 #define SEARCH(array, target)                     \
220 (@{                                               \
221   __label__ found;                                \
222   typeof (target) _SEARCH_target = (target);      \
223   typeof (*(array)) *_SEARCH_array = (array);     \
224   int i, j;                                       \
225   int value;                                      \
226   for (i = 0; i < max; i++)                       \
227     for (j = 0; j < max; j++)                     \
228       if (_SEARCH_array[i][j] == _SEARCH_target)  \
229         @{ value = i; goto found; @}              \
230   value = -1;                                     \
231  found:                                           \
232   value;                                          \
233 @})
234 @end example
235
236 @node Labels as Values
237 @section Labels as Values
238 @cindex labels as values
239 @cindex computed gotos
240 @cindex goto with computed label
241 @cindex address of a label
242
243 You can get the address of a label defined in the current function
244 (or a containing function) with the unary operator @samp{&&}.  The
245 value has type @code{void *}.  This value is a constant and can be used
246 wherever a constant of that type is valid.  For example:
247
248 @example
249 void *ptr;
250 @dots{}
251 ptr = &&foo;
252 @end example
253
254 To use these values, you need to be able to jump to one.  This is done
255 with the computed goto statement@footnote{The analogous feature in
256 Fortran is called an assigned goto, but that name seems inappropriate in
257 C, where one can do more than simply store label addresses in label
258 variables.}, @code{goto *@var{exp};}.  For example,
259
260 @example
261 goto *ptr;
262 @end example
263
264 @noindent
265 Any expression of type @code{void *} is allowed.
266
267 One way of using these constants is in initializing a static array that
268 will serve as a jump table:
269
270 @example
271 static void *array[] = @{ &&foo, &&bar, &&hack @};
272 @end example
273
274 Then you can select a label with indexing, like this:
275
276 @example
277 goto *array[i];
278 @end example
279
280 @noindent
281 Note that this does not check whether the subscript is in bounds---array
282 indexing in C never does that.
283
284 Such an array of label values serves a purpose much like that of the
285 @code{switch} statement.  The @code{switch} statement is cleaner, so
286 use that rather than an array unless the problem does not fit a
287 @code{switch} statement very well.
288
289 Another use of label values is in an interpreter for threaded code.
290 The labels within the interpreter function can be stored in the
291 threaded code for super-fast dispatching.
292
293 You can use this mechanism to jump to code in a different function.  If
294 you do that, totally unpredictable things will happen.  The best way to
295 avoid this is to store the label address only in automatic variables and
296 never pass it as an argument.
297
298 @node Nested Functions
299 @section Nested Functions
300 @cindex nested functions
301 @cindex downward funargs
302 @cindex thunks
303
304 A @dfn{nested function} is a function defined inside another function.
305 (Nested functions are not supported for GNU C++.)  The nested function's
306 name is local to the block where it is defined.  For example, here we
307 define a nested function named @code{square}, and call it twice:
308
309 @example
310 @group
311 foo (double a, double b)
312 @{
313   double square (double z) @{ return z * z; @}
314
315   return square (a) + square (b);
316 @}
317 @end group
318 @end example
319
320 The nested function can access all the variables of the containing
321 function that are visible at the point of its definition.  This is
322 called @dfn{lexical scoping}.  For example, here we show a nested
323 function which uses an inherited variable named @code{offset}:
324
325 @example
326 bar (int *array, int offset, int size)
327 @{
328   int access (int *array, int index)
329     @{ return array[index + offset]; @}
330   int i;
331   @dots{}
332   for (i = 0; i < size; i++)
333     @dots{} access (array, i) @dots{}
334 @}
335 @end example
336
337 Nested function definitions are permitted within functions in the places
338 where variable definitions are allowed; that is, in any block, before
339 the first statement in the block.
340
341 It is possible to call the nested function from outside the scope of its
342 name by storing its address or passing the address to another function:
343
344 @example
345 hack (int *array, int size)
346 @{
347   void store (int index, int value)
348     @{ array[index] = value; @}
349
350   intermediate (store, size);
351 @}
352 @end example
353
354 Here, the function @code{intermediate} receives the address of
355 @code{store} as an argument.  If @code{intermediate} calls @code{store},
356 the arguments given to @code{store} are used to store into @code{array}.
357 But this technique works only so long as the containing function
358 (@code{hack}, in this example) does not exit.
359
360 If you try to call the nested function through its address after the
361 containing function has exited, all hell will break loose.  If you try
362 to call it after a containing scope level has exited, and if it refers
363 to some of the variables that are no longer in scope, you may be lucky,
364 but it's not wise to take the risk.  If, however, the nested function
365 does not refer to anything that has gone out of scope, you should be
366 safe.
367
368 GNU CC implements taking the address of a nested function using a
369 technique called @dfn{trampolines}.   A paper describing them is
370 available as @samp{http://master.debian.org/~karlheg/Usenix88-lexic.pdf}.
371
372 A nested function can jump to a label inherited from a containing
373 function, provided the label was explicitly declared in the containing
374 function (@pxref{Local Labels}).  Such a jump returns instantly to the
375 containing function, exiting the nested function which did the
376 @code{goto} and any intermediate functions as well.  Here is an example:
377
378 @example
379 @group
380 bar (int *array, int offset, int size)
381 @{
382   __label__ failure;
383   int access (int *array, int index)
384     @{
385       if (index > size)
386         goto failure;
387       return array[index + offset];
388     @}
389   int i;
390   @dots{}
391   for (i = 0; i < size; i++)
392     @dots{} access (array, i) @dots{}
393   @dots{}
394   return 0;
395
396  /* @r{Control comes here from @code{access}
397     if it detects an error.}  */
398  failure:
399   return -1;
400 @}
401 @end group
402 @end example
403
404 A nested function always has internal linkage.  Declaring one with
405 @code{extern} is erroneous.  If you need to declare the nested function
406 before its definition, use @code{auto} (which is otherwise meaningless
407 for function declarations).
408
409 @example
410 bar (int *array, int offset, int size)
411 @{
412   __label__ failure;
413   auto int access (int *, int);
414   @dots{}
415   int access (int *array, int index)
416     @{
417       if (index > size)
418         goto failure;
419       return array[index + offset];
420     @}
421   @dots{}
422 @}
423 @end example
424
425 @node Constructing Calls
426 @section Constructing Function Calls
427 @cindex constructing calls
428 @cindex forwarding calls
429
430 Using the built-in functions described below, you can record
431 the arguments a function received, and call another function
432 with the same arguments, without knowing the number or types
433 of the arguments.
434
435 You can also record the return value of that function call,
436 and later return that value, without knowing what data type
437 the function tried to return (as long as your caller expects
438 that data type).
439
440 @table @code
441 @findex __builtin_apply_args
442 @item __builtin_apply_args ()
443 This built-in function returns a pointer of type @code{void *} to data
444 describing how to perform a call with the same arguments as were passed
445 to the current function.
446
447 The function saves the arg pointer register, structure value address,
448 and all registers that might be used to pass arguments to a function
449 into a block of memory allocated on the stack.  Then it returns the
450 address of that block.
451
452 @findex __builtin_apply
453 @item __builtin_apply (@var{function}, @var{arguments}, @var{size})
454 This built-in function invokes @var{function} (type @code{void (*)()})
455 with a copy of the parameters described by @var{arguments} (type
456 @code{void *}) and @var{size} (type @code{int}).
457
458 The value of @var{arguments} should be the value returned by
459 @code{__builtin_apply_args}.  The argument @var{size} specifies the size
460 of the stack argument data, in bytes.
461
462 This function returns a pointer of type @code{void *} to data describing
463 how to return whatever value was returned by @var{function}.  The data
464 is saved in a block of memory allocated on the stack.
465
466 It is not always simple to compute the proper value for @var{size}.  The
467 value is used by @code{__builtin_apply} to compute the amount of data
468 that should be pushed on the stack and copied from the incoming argument
469 area.
470
471 @findex __builtin_return
472 @item __builtin_return (@var{result})
473 This built-in function returns the value described by @var{result} from
474 the containing function.  You should specify, for @var{result}, a value
475 returned by @code{__builtin_apply}.
476 @end table
477
478 @node Naming Types
479 @section Naming an Expression's Type
480 @cindex naming types
481
482 You can give a name to the type of an expression using a @code{typedef}
483 declaration with an initializer.  Here is how to define @var{name} as a
484 type name for the type of @var{exp}:
485
486 @example
487 typedef @var{name} = @var{exp};
488 @end example
489
490 This is useful in conjunction with the statements-within-expressions
491 feature.  Here is how the two together can be used to define a safe
492 ``maximum'' macro that operates on any arithmetic type:
493
494 @example
495 #define max(a,b) \
496   (@{typedef _ta = (a), _tb = (b);  \
497     _ta _a = (a); _tb _b = (b);     \
498     _a > _b ? _a : _b; @})
499 @end example
500
501 @cindex underscores in variables in macros
502 @cindex @samp{_} in variables in macros
503 @cindex local variables in macros
504 @cindex variables, local, in macros
505 @cindex macros, local variables in
506
507 The reason for using names that start with underscores for the local
508 variables is to avoid conflicts with variable names that occur within the
509 expressions that are substituted for @code{a} and @code{b}.  Eventually we
510 hope to design a new form of declaration syntax that allows you to declare
511 variables whose scopes start only after their initializers; this will be a
512 more reliable way to prevent such conflicts.
513
514 @node Typeof
515 @section Referring to a Type with @code{typeof}
516 @findex typeof
517 @findex sizeof
518 @cindex macros, types of arguments
519
520 Another way to refer to the type of an expression is with @code{typeof}.
521 The syntax of using of this keyword looks like @code{sizeof}, but the
522 construct acts semantically like a type name defined with @code{typedef}.
523
524 There are two ways of writing the argument to @code{typeof}: with an
525 expression or with a type.  Here is an example with an expression:
526
527 @example
528 typeof (x[0](1))
529 @end example
530
531 @noindent
532 This assumes that @code{x} is an array of functions; the type described
533 is that of the values of the functions.
534
535 Here is an example with a typename as the argument:
536
537 @example
538 typeof (int *)
539 @end example
540
541 @noindent
542 Here the type described is that of pointers to @code{int}.
543
544 If you are writing a header file that must work when included in ANSI C
545 programs, write @code{__typeof__} instead of @code{typeof}.
546 @xref{Alternate Keywords}.
547
548 A @code{typeof}-construct can be used anywhere a typedef name could be
549 used.  For example, you can use it in a declaration, in a cast, or inside
550 of @code{sizeof} or @code{typeof}.
551
552 @itemize @bullet
553 @item
554 This declares @code{y} with the type of what @code{x} points to.
555
556 @example
557 typeof (*x) y;
558 @end example
559
560 @item
561 This declares @code{y} as an array of such values.
562
563 @example
564 typeof (*x) y[4];
565 @end example
566
567 @item
568 This declares @code{y} as an array of pointers to characters:
569
570 @example
571 typeof (typeof (char *)[4]) y;
572 @end example
573
574 @noindent
575 It is equivalent to the following traditional C declaration:
576
577 @example
578 char *y[4];
579 @end example
580
581 To see the meaning of the declaration using @code{typeof}, and why it
582 might be a useful way to write, let's rewrite it with these macros:
583
584 @example
585 #define pointer(T)  typeof(T *)
586 #define array(T, N) typeof(T [N])
587 @end example
588
589 @noindent
590 Now the declaration can be rewritten this way:
591
592 @example
593 array (pointer (char), 4) y;
594 @end example
595
596 @noindent
597 Thus, @code{array (pointer (char), 4)} is the type of arrays of 4
598 pointers to @code{char}.
599 @end itemize
600
601 @node Lvalues
602 @section Generalized Lvalues
603 @cindex compound expressions as lvalues
604 @cindex expressions, compound, as lvalues
605 @cindex conditional expressions as lvalues
606 @cindex expressions, conditional, as lvalues
607 @cindex casts as lvalues
608 @cindex generalized lvalues
609 @cindex lvalues, generalized
610 @cindex extensions, @code{?:}
611 @cindex @code{?:} extensions
612 Compound expressions, conditional expressions and casts are allowed as
613 lvalues provided their operands are lvalues.  This means that you can take
614 their addresses or store values into them.
615
616 Standard C++ allows compound expressions and conditional expressions as
617 lvalues, and permits casts to reference type, so use of this extension
618 is deprecated for C++ code.
619
620 For example, a compound expression can be assigned, provided the last
621 expression in the sequence is an lvalue.  These two expressions are
622 equivalent:
623
624 @example
625 (a, b) += 5
626 a, (b += 5)
627 @end example
628
629 Similarly, the address of the compound expression can be taken.  These two
630 expressions are equivalent:
631
632 @example
633 &(a, b)
634 a, &b
635 @end example
636
637 A conditional expression is a valid lvalue if its type is not void and the
638 true and false branches are both valid lvalues.  For example, these two
639 expressions are equivalent:
640
641 @example
642 (a ? b : c) = 5
643 (a ? b = 5 : (c = 5))
644 @end example
645
646 A cast is a valid lvalue if its operand is an lvalue.  A simple
647 assignment whose left-hand side is a cast works by converting the
648 right-hand side first to the specified type, then to the type of the
649 inner left-hand side expression.  After this is stored, the value is
650 converted back to the specified type to become the value of the
651 assignment.  Thus, if @code{a} has type @code{char *}, the following two
652 expressions are equivalent:
653
654 @example
655 (int)a = 5
656 (int)(a = (char *)(int)5)
657 @end example
658
659 An assignment-with-arithmetic operation such as @samp{+=} applied to a cast
660 performs the arithmetic using the type resulting from the cast, and then
661 continues as in the previous case.  Therefore, these two expressions are
662 equivalent:
663
664 @example
665 (int)a += 5
666 (int)(a = (char *)(int) ((int)a + 5))
667 @end example
668
669 You cannot take the address of an lvalue cast, because the use of its
670 address would not work out coherently.  Suppose that @code{&(int)f} were
671 permitted, where @code{f} has type @code{float}.  Then the following
672 statement would try to store an integer bit-pattern where a floating
673 point number belongs:
674
675 @example
676 *&(int)f = 1;
677 @end example
678
679 This is quite different from what @code{(int)f = 1} would do---that
680 would convert 1 to floating point and store it.  Rather than cause this
681 inconsistency, we think it is better to prohibit use of @samp{&} on a cast.
682
683 If you really do want an @code{int *} pointer with the address of
684 @code{f}, you can simply write @code{(int *)&f}.
685
686 @node Conditionals
687 @section Conditionals with Omitted Operands
688 @cindex conditional expressions, extensions
689 @cindex omitted middle-operands
690 @cindex middle-operands, omitted
691 @cindex extensions, @code{?:}
692 @cindex @code{?:} extensions
693
694 The middle operand in a conditional expression may be omitted.  Then
695 if the first operand is nonzero, its value is the value of the conditional
696 expression.
697
698 Therefore, the expression
699
700 @example
701 x ? : y
702 @end example
703
704 @noindent
705 has the value of @code{x} if that is nonzero; otherwise, the value of
706 @code{y}.
707
708 This example is perfectly equivalent to
709
710 @example
711 x ? x : y
712 @end example
713
714 @cindex side effect in ?:
715 @cindex ?: side effect
716 @noindent
717 In this simple case, the ability to omit the middle operand is not
718 especially useful.  When it becomes useful is when the first operand does,
719 or may (if it is a macro argument), contain a side effect.  Then repeating
720 the operand in the middle would perform the side effect twice.  Omitting
721 the middle operand uses the value already computed without the undesirable
722 effects of recomputing it.
723
724 @node Long Long
725 @section Double-Word Integers
726 @cindex @code{long long} data types
727 @cindex double-word arithmetic
728 @cindex multiprecision arithmetic
729
730 GNU C supports data types for integers that are twice as long as
731 @code{int}.  Simply write @code{long long int} for a signed integer, or
732 @code{unsigned long long int} for an unsigned integer.  To make an
733 integer constant of type @code{long long int}, add the suffix @code{LL}
734 to the integer.  To make an integer constant of type @code{unsigned long
735 long int}, add the suffix @code{ULL} to the integer.
736
737 You can use these types in arithmetic like any other integer types.
738 Addition, subtraction, and bitwise boolean operations on these types
739 are open-coded on all types of machines.  Multiplication is open-coded
740 if the machine supports fullword-to-doubleword a widening multiply
741 instruction.  Division and shifts are open-coded only on machines that
742 provide special support.  The operations that are not open-coded use
743 special library routines that come with GNU CC.
744
745 There may be pitfalls when you use @code{long long} types for function
746 arguments, unless you declare function prototypes.  If a function
747 expects type @code{int} for its argument, and you pass a value of type
748 @code{long long int}, confusion will result because the caller and the
749 subroutine will disagree about the number of bytes for the argument.
750 Likewise, if the function expects @code{long long int} and you pass
751 @code{int}.  The best way to avoid such problems is to use prototypes.
752
753 @node Complex
754 @section Complex Numbers
755 @cindex complex numbers
756
757 GNU C supports complex data types.  You can declare both complex integer
758 types and complex floating types, using the keyword @code{__complex__}.
759
760 For example, @samp{__complex__ double x;} declares @code{x} as a
761 variable whose real part and imaginary part are both of type
762 @code{double}.  @samp{__complex__ short int y;} declares @code{y} to
763 have real and imaginary parts of type @code{short int}; this is not
764 likely to be useful, but it shows that the set of complex types is
765 complete.
766
767 To write a constant with a complex data type, use the suffix @samp{i} or
768 @samp{j} (either one; they are equivalent).  For example, @code{2.5fi}
769 has type @code{__complex__ float} and @code{3i} has type
770 @code{__complex__ int}.  Such a constant always has a pure imaginary
771 value, but you can form any complex value you like by adding one to a
772 real constant.
773
774 To extract the real part of a complex-valued expression @var{exp}, write
775 @code{__real__ @var{exp}}.  Likewise, use @code{__imag__} to
776 extract the imaginary part.
777
778 The operator @samp{~} performs complex conjugation when used on a value
779 with a complex type.
780
781 GNU CC can allocate complex automatic variables in a noncontiguous
782 fashion; it's even possible for the real part to be in a register while
783 the imaginary part is on the stack (or vice-versa).  None of the
784 supported debugging info formats has a way to represent noncontiguous
785 allocation like this, so GNU CC describes a noncontiguous complex
786 variable as if it were two separate variables of noncomplex type.
787 If the variable's actual name is @code{foo}, the two fictitious
788 variables are named @code{foo$real} and @code{foo$imag}.  You can
789 examine and set these two fictitious variables with your debugger.
790
791 A future version of GDB will know how to recognize such pairs and treat
792 them as a single variable with a complex type.
793
794 @node Zero Length
795 @section Arrays of Length Zero
796 @cindex arrays of length zero
797 @cindex zero-length arrays
798 @cindex length-zero arrays
799
800 Zero-length arrays are allowed in GNU C.  They are very useful as the last
801 element of a structure which is really a header for a variable-length
802 object:
803
804 @example
805 struct line @{
806   int length;
807   char contents[0];
808 @};
809
810 @{
811   struct line *thisline = (struct line *)
812     malloc (sizeof (struct line) + this_length);
813   thisline->length = this_length;
814 @}
815 @end example
816
817 In standard C, you would have to give @code{contents} a length of 1, which
818 means either you waste space or complicate the argument to @code{malloc}.
819
820 @node Variable Length
821 @section Arrays of Variable Length
822 @cindex variable-length arrays
823 @cindex arrays of variable length
824
825 Variable-length automatic arrays are allowed in GNU C.  These arrays are
826 declared like any other automatic arrays, but with a length that is not
827 a constant expression.  The storage is allocated at the point of
828 declaration and deallocated when the brace-level is exited.  For
829 example:
830
831 @example
832 FILE *
833 concat_fopen (char *s1, char *s2, char *mode)
834 @{
835   char str[strlen (s1) + strlen (s2) + 1];
836   strcpy (str, s1);
837   strcat (str, s2);
838   return fopen (str, mode);
839 @}
840 @end example
841
842 @cindex scope of a variable length array
843 @cindex variable-length array scope
844 @cindex deallocating variable length arrays
845 Jumping or breaking out of the scope of the array name deallocates the
846 storage.  Jumping into the scope is not allowed; you get an error
847 message for it.
848
849 @cindex @code{alloca} vs variable-length arrays
850 You can use the function @code{alloca} to get an effect much like
851 variable-length arrays.  The function @code{alloca} is available in
852 many other C implementations (but not in all).  On the other hand,
853 variable-length arrays are more elegant.
854
855 There are other differences between these two methods.  Space allocated
856 with @code{alloca} exists until the containing @emph{function} returns.
857 The space for a variable-length array is deallocated as soon as the array
858 name's scope ends.  (If you use both variable-length arrays and
859 @code{alloca} in the same function, deallocation of a variable-length array
860 will also deallocate anything more recently allocated with @code{alloca}.)
861
862 You can also use variable-length arrays as arguments to functions:
863
864 @example
865 struct entry
866 tester (int len, char data[len][len])
867 @{
868   @dots{}
869 @}
870 @end example
871
872 The length of an array is computed once when the storage is allocated
873 and is remembered for the scope of the array in case you access it with
874 @code{sizeof}.
875
876 If you want to pass the array first and the length afterward, you can
877 use a forward declaration in the parameter list---another GNU extension.
878
879 @example
880 struct entry
881 tester (int len; char data[len][len], int len)
882 @{
883   @dots{}
884 @}
885 @end example
886
887 @cindex parameter forward declaration
888 The @samp{int len} before the semicolon is a @dfn{parameter forward
889 declaration}, and it serves the purpose of making the name @code{len}
890 known when the declaration of @code{data} is parsed.
891
892 You can write any number of such parameter forward declarations in the
893 parameter list.  They can be separated by commas or semicolons, but the
894 last one must end with a semicolon, which is followed by the ``real''
895 parameter declarations.  Each forward declaration must match a ``real''
896 declaration in parameter name and data type.
897
898 @node Macro Varargs
899 @section Macros with Variable Numbers of Arguments
900 @cindex variable number of arguments
901 @cindex macro with variable arguments
902 @cindex rest argument (in macro)
903
904 In GNU C, a macro can accept a variable number of arguments, much as a
905 function can.  The syntax for defining the macro looks much like that
906 used for a function.  Here is an example:
907
908 @example
909 #define eprintf(format, args...)  \
910  fprintf (stderr, format , ## args)
911 @end example
912
913 Here @code{args} is a @dfn{rest argument}: it takes in zero or more
914 arguments, as many as the call contains.  All of them plus the commas
915 between them form the value of @code{args}, which is substituted into
916 the macro body where @code{args} is used.  Thus, we have this expansion:
917
918 @example
919 eprintf ("%s:%d: ", input_file_name, line_number)
920 @expansion{}
921 fprintf (stderr, "%s:%d: " , input_file_name, line_number)
922 @end example
923
924 @noindent
925 Note that the comma after the string constant comes from the definition
926 of @code{eprintf}, whereas the last comma comes from the value of
927 @code{args}.
928
929 The reason for using @samp{##} is to handle the case when @code{args}
930 matches no arguments at all.  In this case, @code{args} has an empty
931 value.  In this case, the second comma in the definition becomes an
932 embarrassment: if it got through to the expansion of the macro, we would
933 get something like this:
934
935 @example
936 fprintf (stderr, "success!\n" , )
937 @end example
938
939 @noindent
940 which is invalid C syntax.  @samp{##} gets rid of the comma, so we get
941 the following instead:
942
943 @example
944 fprintf (stderr, "success!\n")
945 @end example
946
947 This is a special feature of the GNU C preprocessor: @samp{##} before a
948 rest argument that is empty discards the preceding sequence of
949 non-whitespace characters from the macro definition.  (If another macro
950 argument precedes, none of it is discarded.)
951
952 It might be better to discard the last preprocessor token instead of the
953 last preceding sequence of non-whitespace characters; in fact, we may
954 someday change this feature to do so.  We advise you to write the macro
955 definition so that the preceding sequence of non-whitespace characters
956 is just a single token, so that the meaning will not change if we change
957 the definition of this feature.
958
959 @node Subscripting
960 @section Non-Lvalue Arrays May Have Subscripts
961 @cindex subscripting
962 @cindex arrays, non-lvalue
963
964 @cindex subscripting and function values
965 Subscripting is allowed on arrays that are not lvalues, even though the
966 unary @samp{&} operator is not.  For example, this is valid in GNU C though
967 not valid in other C dialects:
968
969 @example
970 @group
971 struct foo @{int a[4];@};
972
973 struct foo f();
974
975 bar (int index)
976 @{
977   return f().a[index];
978 @}
979 @end group
980 @end example
981
982 @node Pointer Arith
983 @section Arithmetic on @code{void}- and Function-Pointers
984 @cindex void pointers, arithmetic
985 @cindex void, size of pointer to
986 @cindex function pointers, arithmetic
987 @cindex function, size of pointer to
988
989 In GNU C, addition and subtraction operations are supported on pointers to
990 @code{void} and on pointers to functions.  This is done by treating the
991 size of a @code{void} or of a function as 1.
992
993 A consequence of this is that @code{sizeof} is also allowed on @code{void}
994 and on function types, and returns 1.
995
996 The option @samp{-Wpointer-arith} requests a warning if these extensions
997 are used.
998
999 @node Initializers
1000 @section Non-Constant Initializers
1001 @cindex initializers, non-constant
1002 @cindex non-constant initializers
1003
1004 As in standard C++, the elements of an aggregate initializer for an
1005 automatic variable are not required to be constant expressions in GNU C.
1006 Here is an example of an initializer with run-time varying elements:
1007
1008 @example
1009 foo (float f, float g)
1010 @{
1011   float beat_freqs[2] = @{ f-g, f+g @};
1012   @dots{}
1013 @}
1014 @end example
1015
1016 @node Constructors
1017 @section Constructor Expressions
1018 @cindex constructor expressions
1019 @cindex initializations in expressions
1020 @cindex structures, constructor expression
1021 @cindex expressions, constructor
1022
1023 GNU C supports constructor expressions.  A constructor looks like
1024 a cast containing an initializer.  Its value is an object of the
1025 type specified in the cast, containing the elements specified in
1026 the initializer.
1027
1028 Usually, the specified type is a structure.  Assume that
1029 @code{struct foo} and @code{structure} are declared as shown:
1030
1031 @example
1032 struct foo @{int a; char b[2];@} structure;
1033 @end example
1034
1035 @noindent
1036 Here is an example of constructing a @code{struct foo} with a constructor:
1037
1038 @example
1039 structure = ((struct foo) @{x + y, 'a', 0@});
1040 @end example
1041
1042 @noindent
1043 This is equivalent to writing the following:
1044
1045 @example
1046 @{
1047   struct foo temp = @{x + y, 'a', 0@};
1048   structure = temp;
1049 @}
1050 @end example
1051
1052 You can also construct an array.  If all the elements of the constructor
1053 are (made up of) simple constant expressions, suitable for use in
1054 initializers, then the constructor is an lvalue and can be coerced to a
1055 pointer to its first element, as shown here:
1056
1057 @example
1058 char **foo = (char *[]) @{ "x", "y", "z" @};
1059 @end example
1060
1061 Array constructors whose elements are not simple constants are
1062 not very useful, because the constructor is not an lvalue.  There
1063 are only two valid ways to use it: to subscript it, or initialize
1064 an array variable with it.  The former is probably slower than a
1065 @code{switch} statement, while the latter does the same thing an
1066 ordinary C initializer would do.  Here is an example of
1067 subscripting an array constructor:
1068
1069 @example
1070 output = ((int[]) @{ 2, x, 28 @}) [input];
1071 @end example
1072
1073 Constructor expressions for scalar types and union types are is
1074 also allowed, but then the constructor expression is equivalent
1075 to a cast.
1076
1077 @node Labeled Elements
1078 @section Labeled Elements in Initializers
1079 @cindex initializers with labeled elements
1080 @cindex labeled elements in initializers
1081 @cindex case labels in initializers
1082
1083 Standard C requires the elements of an initializer to appear in a fixed
1084 order, the same as the order of the elements in the array or structure
1085 being initialized.
1086
1087 In GNU C you can give the elements in any order, specifying the array
1088 indices or structure field names they apply to.  This extension is not
1089 implemented in GNU C++.
1090
1091 To specify an array index, write @samp{[@var{index}]} or
1092 @samp{[@var{index}] =} before the element value.  For example,
1093
1094 @example
1095 int a[6] = @{ [4] 29, [2] = 15 @};
1096 @end example
1097
1098 @noindent
1099 is equivalent to
1100
1101 @example
1102 int a[6] = @{ 0, 0, 15, 0, 29, 0 @};
1103 @end example
1104
1105 @noindent
1106 The index values must be constant expressions, even if the array being
1107 initialized is automatic.
1108
1109 To initialize a range of elements to the same value, write
1110 @samp{[@var{first} ... @var{last}] = @var{value}}.  For example,
1111
1112 @example
1113 int widths[] = @{ [0 ... 9] = 1, [10 ... 99] = 2, [100] = 3 @};
1114 @end example
1115
1116 @noindent
1117 Note that the length of the array is the highest value specified
1118 plus one.
1119
1120 In a structure initializer, specify the name of a field to initialize
1121 with @samp{@var{fieldname}:} before the element value.  For example,
1122 given the following structure,
1123
1124 @example
1125 struct point @{ int x, y; @};
1126 @end example
1127
1128 @noindent
1129 the following initialization
1130
1131 @example
1132 struct point p = @{ y: yvalue, x: xvalue @};
1133 @end example
1134
1135 @noindent
1136 is equivalent to
1137
1138 @example
1139 struct point p = @{ xvalue, yvalue @};
1140 @end example
1141
1142 Another syntax which has the same meaning is @samp{.@var{fieldname} =}.,
1143 as shown here:
1144
1145 @example
1146 struct point p = @{ .y = yvalue, .x = xvalue @};
1147 @end example
1148
1149 You can also use an element label (with either the colon syntax or the
1150 period-equal syntax) when initializing a union, to specify which element
1151 of the union should be used.  For example,
1152
1153 @example
1154 union foo @{ int i; double d; @};
1155
1156 union foo f = @{ d: 4 @};
1157 @end example
1158
1159 @noindent
1160 will convert 4 to a @code{double} to store it in the union using
1161 the second element.  By contrast, casting 4 to type @code{union foo}
1162 would store it into the union as the integer @code{i}, since it is
1163 an integer.  (@xref{Cast to Union}.)
1164
1165 You can combine this technique of naming elements with ordinary C
1166 initialization of successive elements.  Each initializer element that
1167 does not have a label applies to the next consecutive element of the
1168 array or structure.  For example,
1169
1170 @example
1171 int a[6] = @{ [1] = v1, v2, [4] = v4 @};
1172 @end example
1173
1174 @noindent
1175 is equivalent to
1176
1177 @example
1178 int a[6] = @{ 0, v1, v2, 0, v4, 0 @};
1179 @end example
1180
1181 Labeling the elements of an array initializer is especially useful
1182 when the indices are characters or belong to an @code{enum} type.
1183 For example:
1184
1185 @example
1186 int whitespace[256]
1187   = @{ [' '] = 1, ['\t'] = 1, ['\h'] = 1,
1188       ['\f'] = 1, ['\n'] = 1, ['\r'] = 1 @};
1189 @end example
1190
1191 @node Case Ranges
1192 @section Case Ranges
1193 @cindex case ranges
1194 @cindex ranges in case statements
1195
1196 You can specify a range of consecutive values in a single @code{case} label,
1197 like this:
1198
1199 @example
1200 case @var{low} ... @var{high}:
1201 @end example
1202
1203 @noindent
1204 This has the same effect as the proper number of individual @code{case}
1205 labels, one for each integer value from @var{low} to @var{high}, inclusive.
1206
1207 This feature is especially useful for ranges of ASCII character codes:
1208
1209 @example
1210 case 'A' ... 'Z':
1211 @end example
1212
1213 @strong{Be careful:} Write spaces around the @code{...}, for otherwise
1214 it may be parsed wrong when you use it with integer values.  For example,
1215 write this:
1216
1217 @example
1218 case 1 ... 5:
1219 @end example
1220
1221 @noindent
1222 rather than this:
1223
1224 @example
1225 case 1...5:
1226 @end example
1227
1228 @node Cast to Union
1229 @section Cast to a Union Type
1230 @cindex cast to a union
1231 @cindex union, casting to a
1232
1233 A cast to union type is similar to other casts, except that the type
1234 specified is a union type.  You can specify the type either with
1235 @code{union @var{tag}} or with a typedef name.  A cast to union is actually
1236 a constructor though, not a cast, and hence does not yield an lvalue like
1237 normal casts.  (@xref{Constructors}.)
1238
1239 The types that may be cast to the union type are those of the members
1240 of the union.  Thus, given the following union and variables:
1241
1242 @example
1243 union foo @{ int i; double d; @};
1244 int x;
1245 double y;
1246 @end example
1247
1248 @noindent
1249 both @code{x} and @code{y} can be cast to type @code{union} foo.
1250
1251 Using the cast as the right-hand side of an assignment to a variable of
1252 union type is equivalent to storing in a member of the union:
1253
1254 @example
1255 union foo u;
1256 @dots{}
1257 u = (union foo) x  @equiv{}  u.i = x
1258 u = (union foo) y  @equiv{}  u.d = y
1259 @end example
1260
1261 You can also use the union cast as a function argument:
1262
1263 @example
1264 void hack (union foo);
1265 @dots{}
1266 hack ((union foo) x);
1267 @end example
1268
1269 @node Function Attributes
1270 @section Declaring Attributes of Functions
1271 @cindex function attributes
1272 @cindex declaring attributes of functions
1273 @cindex functions that never return
1274 @cindex functions that have no side effects
1275 @cindex functions in arbitrary sections
1276 @cindex @code{volatile} applied to function
1277 @cindex @code{const} applied to function
1278 @cindex functions with @code{printf}, @code{scanf} or @code{strftime} style arguments
1279 @cindex functions that are passed arguments in registers on the 386
1280 @cindex functions that pop the argument stack on the 386
1281 @cindex functions that do not pop the argument stack on the 386
1282
1283 In GNU C, you declare certain things about functions called in your program
1284 which help the compiler optimize function calls and check your code more
1285 carefully.
1286
1287 The keyword @code{__attribute__} allows you to specify special
1288 attributes when making a declaration.  This keyword is followed by an
1289 attribute specification inside double parentheses.  Eight attributes,
1290 @code{noreturn}, @code{const}, @code{format}, @code{section},
1291 @code{constructor}, @code{destructor}, @code{unused} and @code{weak} are
1292 currently defined for functions.  Other attributes, including
1293 @code{section} are supported for variables declarations (@pxref{Variable
1294 Attributes}) and for types (@pxref{Type Attributes}).
1295
1296 You may also specify attributes with @samp{__} preceding and following
1297 each keyword.  This allows you to use them in header files without
1298 being concerned about a possible macro of the same name.  For example,
1299 you may use @code{__noreturn__} instead of @code{noreturn}.
1300
1301 @table @code
1302 @cindex @code{noreturn} function attribute
1303 @item noreturn
1304 A few standard library functions, such as @code{abort} and @code{exit},
1305 cannot return.  GNU CC knows this automatically.  Some programs define
1306 their own functions that never return.  You can declare them
1307 @code{noreturn} to tell the compiler this fact.  For example,
1308
1309 @smallexample
1310 void fatal () __attribute__ ((noreturn));
1311
1312 void
1313 fatal (@dots{})
1314 @{
1315   @dots{} /* @r{Print error message.} */ @dots{}
1316   exit (1);
1317 @}
1318 @end smallexample
1319
1320 The @code{noreturn} keyword tells the compiler to assume that
1321 @code{fatal} cannot return.  It can then optimize without regard to what
1322 would happen if @code{fatal} ever did return.  This makes slightly
1323 better code.  More importantly, it helps avoid spurious warnings of
1324 uninitialized variables.
1325
1326 Do not assume that registers saved by the calling function are
1327 restored before calling the @code{noreturn} function.
1328
1329 It does not make sense for a @code{noreturn} function to have a return
1330 type other than @code{void}.
1331
1332 The attribute @code{noreturn} is not implemented in GNU C versions
1333 earlier than 2.5.  An alternative way to declare that a function does
1334 not return, which works in the current version and in some older
1335 versions, is as follows:
1336
1337 @smallexample
1338 typedef void voidfn ();
1339
1340 volatile voidfn fatal;
1341 @end smallexample
1342
1343 @cindex @code{const} function attribute
1344 @item const
1345 Many functions do not examine any values except their arguments, and
1346 have no effects except the return value.  Such a function can be subject
1347 to common subexpression elimination and loop optimization just as an
1348 arithmetic operator would be.  These functions should be declared
1349 with the attribute @code{const}.  For example,
1350
1351 @smallexample
1352 int square (int) __attribute__ ((const));
1353 @end smallexample
1354
1355 @noindent
1356 says that the hypothetical function @code{square} is safe to call
1357 fewer times than the program says.
1358
1359 The attribute @code{const} is not implemented in GNU C versions earlier
1360 than 2.5.  An alternative way to declare that a function has no side
1361 effects, which works in the current version and in some older versions,
1362 is as follows:
1363
1364 @smallexample
1365 typedef int intfn ();
1366
1367 extern const intfn square;
1368 @end smallexample
1369
1370 This approach does not work in GNU C++ from 2.6.0 on, since the language
1371 specifies that the @samp{const} must be attached to the return value.
1372
1373 @cindex pointer arguments
1374 Note that a function that has pointer arguments and examines the data
1375 pointed to must @emph{not} be declared @code{const}.  Likewise, a
1376 function that calls a non-@code{const} function usually must not be
1377 @code{const}.  It does not make sense for a @code{const} function to
1378 return @code{void}.
1379
1380 @item format (@var{archetype}, @var{string-index}, @var{first-to-check})
1381 @cindex @code{format} function attribute
1382 The @code{format} attribute specifies that a function takes @code{printf},
1383 @code{scanf}, or @code{strftime} style arguments which should be type-checked
1384 against a format string.  For example, the declaration:
1385
1386 @smallexample
1387 extern int
1388 my_printf (void *my_object, const char *my_format, ...)
1389       __attribute__ ((format (printf, 2, 3)));
1390 @end smallexample
1391
1392 @noindent
1393 causes the compiler to check the arguments in calls to @code{my_printf}
1394 for consistency with the @code{printf} style format string argument
1395 @code{my_format}.
1396
1397 The parameter @var{archetype} determines how the format string is
1398 interpreted, and should be either @code{printf}, @code{scanf}, or
1399 @code{strftime}.  The
1400 parameter @var{string-index} specifies which argument is the format
1401 string argument (starting from 1), while @var{first-to-check} is the
1402 number of the first argument to check against the format string.  For
1403 functions where the arguments are not available to be checked (such as
1404 @code{vprintf}), specify the third parameter as zero.  In this case the
1405 compiler only checks the format string for consistency.
1406
1407 In the example above, the format string (@code{my_format}) is the second
1408 argument of the function @code{my_print}, and the arguments to check
1409 start with the third argument, so the correct parameters for the format
1410 attribute are 2 and 3.
1411
1412 The @code{format} attribute allows you to identify your own functions
1413 which take format strings as arguments, so that GNU CC can check the
1414 calls to these functions for errors.  The compiler always checks formats
1415 for the ANSI library functions @code{printf}, @code{fprintf},
1416 @code{sprintf}, @code{scanf}, @code{fscanf}, @code{sscanf}, @code{strftime},
1417 @code{vprintf}, @code{vfprintf} and @code{vsprintf} whenever such
1418 warnings are requested (using @samp{-Wformat}), so there is no need to
1419 modify the header file @file{stdio.h}.
1420
1421 @item format_arg (@var{string-index})
1422 @cindex @code{format_arg} function attribute
1423 The @code{format_arg} attribute specifies that a function takes
1424 @code{printf} or @code{scanf} style arguments, modifies it (for example,
1425 to translate it into another language), and passes it to a @code{printf}
1426 or @code{scanf} style function.  For example, the declaration:
1427
1428 @smallexample
1429 extern char *
1430 my_dgettext (char *my_domain, const char *my_format)
1431       __attribute__ ((format_arg (2)));
1432 @end smallexample
1433
1434 @noindent
1435 causes the compiler to check the arguments in calls to
1436 @code{my_dgettext} whose result is passed to a @code{printf},
1437 @code{scanf}, or @code{strftime} type function for consistency with the
1438 @code{printf} style format string argument @code{my_format}.
1439
1440 The parameter @var{string-index} specifies which argument is the format
1441 string argument (starting from 1).
1442
1443 The @code{format-arg} attribute allows you to identify your own
1444 functions which modify format strings, so that GNU CC can check the
1445 calls to @code{printf}, @code{scanf}, or @code{strftime} function whose
1446 operands are a call to one of your own function.  The compiler always
1447 treats @code{gettext}, @code{dgettext}, and @code{dcgettext} in this
1448 manner.
1449
1450 @item section ("section-name")
1451 @cindex @code{section} function attribute
1452 Normally, the compiler places the code it generates in the @code{text} section.
1453 Sometimes, however, you need additional sections, or you need certain
1454 particular functions to appear in special sections.  The @code{section}
1455 attribute specifies that a function lives in a particular section.
1456 For example, the declaration:
1457
1458 @smallexample
1459 extern void foobar (void) __attribute__ ((section ("bar")));
1460 @end smallexample
1461
1462 @noindent
1463 puts the function @code{foobar} in the @code{bar} section.
1464
1465 Some file formats do not support arbitrary sections so the @code{section}
1466 attribute is not available on all platforms.
1467 If you need to map the entire contents of a module to a particular
1468 section, consider using the facilities of the linker instead.
1469
1470 @item constructor
1471 @itemx destructor
1472 @cindex @code{constructor} function attribute
1473 @cindex @code{destructor} function attribute
1474 The @code{constructor} attribute causes the function to be called
1475 automatically before execution enters @code{main ()}.  Similarly, the
1476 @code{destructor} attribute causes the function to be called
1477 automatically after @code{main ()} has completed or @code{exit ()} has
1478 been called.  Functions with these attributes are useful for
1479 initializing data that will be used implicitly during the execution of
1480 the program.
1481
1482 These attributes are not currently implemented for Objective C.
1483
1484 @item unused
1485 This attribute, attached to a function, means that the function is meant
1486 to be possibly unused.  GNU CC will not produce a warning for this
1487 function.  GNU C++ does not currently support this attribute as
1488 definitions without parameters are valid in C++.
1489
1490 @item weak
1491 @cindex @code{weak} attribute
1492 The @code{weak} attribute causes the declaration to be emitted as a weak
1493 symbol rather than a global.  This is primarily useful in defining
1494 library functions which can be overridden in user code, though it can
1495 also be used with non-function declarations.  Weak symbols are supported
1496 for ELF targets, and also for a.out targets when using the GNU assembler
1497 and linker.
1498
1499 @item alias ("target")
1500 @cindex @code{alias} attribute
1501 The @code{alias} attribute causes the declaration to be emitted as an
1502 alias for another symbol, which must be specified.  For instance,
1503
1504 @smallexample
1505 void __f () @{ /* do something */; @}
1506 void f () __attribute__ ((weak, alias ("__f")));
1507 @end smallexample
1508
1509 declares @samp{f} to be a weak alias for @samp{__f}.  In C++, the
1510 mangled name for the target must be used.
1511
1512 Not all target machines support this attribute.
1513
1514 @item regparm (@var{number})
1515 @cindex functions that are passed arguments in registers on the 386
1516 On the Intel 386, the @code{regparm} attribute causes the compiler to
1517 pass up to @var{number} integer arguments in registers @var{EAX},
1518 @var{EDX}, and @var{ECX} instead of on the stack.  Functions that take a
1519 variable number of arguments will continue to be passed all of their
1520 arguments on the stack.
1521
1522 @item stdcall
1523 @cindex functions that pop the argument stack on the 386
1524 On the Intel 386, the @code{stdcall} attribute causes the compiler to
1525 assume that the called function will pop off the stack space used to
1526 pass arguments, unless it takes a variable number of arguments.
1527
1528 The PowerPC compiler for Windows NT currently ignores the @code{stdcall}
1529 attribute.
1530
1531 @item cdecl
1532 @cindex functions that do pop the argument stack on the 386
1533 On the Intel 386, the @code{cdecl} attribute causes the compiler to
1534 assume that the calling function will pop off the stack space used to
1535 pass arguments.  This is
1536 useful to override the effects of the @samp{-mrtd} switch.
1537
1538 The PowerPC compiler for Windows NT currently ignores the @code{cdecl}
1539 attribute.
1540
1541 @item longcall
1542 @cindex functions called via pointer on the RS/6000 and PowerPC
1543 On the RS/6000 and PowerPC, the @code{longcall} attribute causes the
1544 compiler to always call the function via a pointer, so that functions
1545 which reside further than 64 megabytes (67,108,864 bytes) from the
1546 current location can be called.
1547
1548 @item dllimport
1549 @cindex functions which are imported from a dll on PowerPC Windows NT
1550 On the PowerPC running Windows NT, the @code{dllimport} attribute causes
1551 the compiler to call the function via a global pointer to the function
1552 pointer that is set up by the Windows NT dll library.  The pointer name
1553 is formed by combining @code{__imp_} and the function name.
1554
1555 @item dllexport
1556 @cindex functions which are exported from a dll on PowerPC Windows NT
1557 On the PowerPC running Windows NT, the @code{dllexport} attribute causes
1558 the compiler to provide a global pointer to the function pointer, so
1559 that it can be called with the @code{dllimport} attribute.  The pointer
1560 name is formed by combining @code{__imp_} and the function name.
1561
1562 @item exception (@var{except-func} [, @var{except-arg}])
1563 @cindex functions which specify exception handling on PowerPC Windows NT
1564 On the PowerPC running Windows NT, the @code{exception} attribute causes
1565 the compiler to modify the structured exception table entry it emits for
1566 the declared function.  The string or identifier @var{except-func} is
1567 placed in the third entry of the structured exception table.  It
1568 represents a function, which is called by the exception handling
1569 mechanism if an exception occurs.  If it was specified, the string or
1570 identifier @var{except-arg} is placed in the fourth entry of the
1571 structured exception table.
1572
1573 @item function_vector
1574 @cindex calling functions through the function vector on the H8/300 processors
1575 Use this option on the H8/300 and H8/300H to indicate that the specified
1576 function should be called through the function vector.  Calling a
1577 function through the function vector will reduce code size, however;
1578 the function vector has a limited size (maximum 128 entries on the H8/300
1579 and 64 entries on the H8/300H) and shares space with the interrupt vector.
1580
1581 You must use GAS and GLD from GNU binutils version 2.7 or later for
1582 this option to work correctly.
1583
1584 @item interrupt_handler
1585 @cindex interrupt handler functions on the H8/300 processors
1586 Use this option on the H8/300 and H8/300H to indicate that the specified
1587 function is an interrupt handler.  The compiler will generate function
1588 entry and exit sequences suitable for use in an interrupt handler when this
1589 attribute is present.
1590
1591 @item eightbit_data
1592 @cindex eight bit data on the H8/300 and H8/300H
1593 Use this option on the H8/300 and H8/300H to indicate that the specified
1594 variable should be placed into the eight bit data section.
1595 The compiler will generate more efficient code for certain operations
1596 on data in the eight bit data area.  Note the eight bit data area is limited to
1597 256 bytes of data.
1598
1599 You must use GAS and GLD from GNU binutils version 2.7 or later for
1600 this option to work correctly.
1601
1602 @item tiny_data
1603 @cindex tiny data section on the H8/300H
1604 Use this option on the H8/300H to indicate that the specified
1605 variable should be placed into the tiny data section.
1606 The compiler will generate more efficient code for loads and stores
1607 on data in the tiny data section.  Note the tiny data area is limited to
1608 slightly under 32kbytes of data.
1609
1610 @item interrupt
1611 @cindex interrupt handlers on the M32R/D
1612 Use this option on the M32R/D to indicate that the specified
1613 function is an interrupt handler.  The compiler will generate function
1614 entry and exit sequences suitable for use in an interrupt handler when this
1615 attribute is present.
1616
1617 @item model (@var{model-name})
1618 @cindex function addressability on the M32R/D
1619 Use this attribute on the M32R/D to set the addressability of an object,
1620 and the code generated for a function.
1621 The identifier @var{model-name} is one of @code{small}, @code{medium},
1622 or @code{large}, representing each of the code models.
1623
1624 Small model objects live in the lower 16MB of memory (so that their
1625 addresses can be loaded with the @code{ld24} instruction), and are
1626 callable with the @code{bl} instruction.
1627
1628 Medium model objects may live anywhere in the 32 bit address space (the
1629 compiler will generate @code{seth/add3} instructions to load their addresses),
1630 and are callable with the @code{bl} instruction.
1631
1632 Large model objects may live anywhere in the 32 bit address space (the
1633 compiler will generate @code{seth/add3} instructions to load their addresses),
1634 and may not be reachable with the @code{bl} instruction (the compiler will
1635 generate the much slower @code{seth/add3/jl} instruction sequence).
1636
1637 @end table
1638
1639 You can specify multiple attributes in a declaration by separating them
1640 by commas within the double parentheses or by immediately following an
1641 attribute declaration with another attribute declaration.
1642
1643 @cindex @code{#pragma}, reason for not using
1644 @cindex pragma, reason for not using
1645 Some people object to the @code{__attribute__} feature, suggesting that ANSI C's
1646 @code{#pragma} should be used instead.  There are two reasons for not
1647 doing this.
1648
1649 @enumerate
1650 @item
1651 It is impossible to generate @code{#pragma} commands from a macro.
1652
1653 @item
1654 There is no telling what the same @code{#pragma} might mean in another
1655 compiler.
1656 @end enumerate
1657
1658 These two reasons apply to almost any application that might be proposed
1659 for @code{#pragma}.  It is basically a mistake to use @code{#pragma} for
1660 @emph{anything}.
1661
1662 @node Function Prototypes
1663 @section Prototypes and Old-Style Function Definitions
1664 @cindex function prototype declarations
1665 @cindex old-style function definitions
1666 @cindex promotion of formal parameters
1667
1668 GNU C extends ANSI C to allow a function prototype to override a later
1669 old-style non-prototype definition.  Consider the following example:
1670
1671 @example
1672 /* @r{Use prototypes unless the compiler is old-fashioned.}  */
1673 #ifdef __STDC__
1674 #define P(x) x
1675 #else
1676 #define P(x) ()
1677 #endif
1678
1679 /* @r{Prototype function declaration.}  */
1680 int isroot P((uid_t));
1681
1682 /* @r{Old-style function definition.}  */
1683 int
1684 isroot (x)   /* ??? lossage here ??? */
1685      uid_t x;
1686 @{
1687   return x == 0;
1688 @}
1689 @end example
1690
1691 Suppose the type @code{uid_t} happens to be @code{short}.  ANSI C does
1692 not allow this example, because subword arguments in old-style
1693 non-prototype definitions are promoted.  Therefore in this example the
1694 function definition's argument is really an @code{int}, which does not
1695 match the prototype argument type of @code{short}.
1696
1697 This restriction of ANSI C makes it hard to write code that is portable
1698 to traditional C compilers, because the programmer does not know
1699 whether the @code{uid_t} type is @code{short}, @code{int}, or
1700 @code{long}.  Therefore, in cases like these GNU C allows a prototype
1701 to override a later old-style definition.  More precisely, in GNU C, a
1702 function prototype argument type overrides the argument type specified
1703 by a later old-style definition if the former type is the same as the
1704 latter type before promotion.  Thus in GNU C the above example is
1705 equivalent to the following:
1706
1707 @example
1708 int isroot (uid_t);
1709
1710 int
1711 isroot (uid_t x)
1712 @{
1713   return x == 0;
1714 @}
1715 @end example
1716
1717 GNU C++ does not support old-style function definitions, so this
1718 extension is irrelevant.
1719
1720 @node C++ Comments
1721 @section C++ Style Comments
1722 @cindex //
1723 @cindex C++ comments
1724 @cindex comments, C++ style
1725
1726 In GNU C, you may use C++ style comments, which start with @samp{//} and
1727 continue until the end of the line.  Many other C implementations allow
1728 such comments, and they are likely to be in a future C standard.
1729 However, C++ style comments are not recognized if you specify
1730 @w{@samp{-ansi}} or @w{@samp{-traditional}}, since they are incompatible
1731 with traditional constructs like @code{dividend//*comment*/divisor}.
1732
1733 @node Dollar Signs
1734 @section Dollar Signs in Identifier Names
1735 @cindex $
1736 @cindex dollar signs in identifier names
1737 @cindex identifier names, dollar signs in
1738
1739 In GNU C, you may normally use dollar signs in identifier names.
1740 This is because many traditional C implementations allow such identifiers.
1741 However, dollar signs in identifiers are not supported on a few target
1742 machines, typically because the target assembler does not allow them.
1743
1744 @node Character Escapes
1745 @section The Character @key{ESC} in Constants
1746
1747 You can use the sequence @samp{\e} in a string or character constant to
1748 stand for the ASCII character @key{ESC}.
1749
1750 @node Alignment
1751 @section Inquiring on Alignment of Types or Variables
1752 @cindex alignment
1753 @cindex type alignment
1754 @cindex variable alignment
1755
1756 The keyword @code{__alignof__} allows you to inquire about how an object
1757 is aligned, or the minimum alignment usually required by a type.  Its
1758 syntax is just like @code{sizeof}.
1759
1760 For example, if the target machine requires a @code{double} value to be
1761 aligned on an 8-byte boundary, then @code{__alignof__ (double)} is 8.
1762 This is true on many RISC machines.  On more traditional machine
1763 designs, @code{__alignof__ (double)} is 4 or even 2.
1764
1765 Some machines never actually require alignment; they allow reference to any
1766 data type even at an odd addresses.  For these machines, @code{__alignof__}
1767 reports the @emph{recommended} alignment of a type.
1768
1769 When the operand of @code{__alignof__} is an lvalue rather than a type, the
1770 value is the largest alignment that the lvalue is known to have.  It may
1771 have this alignment as a result of its data type, or because it is part of
1772 a structure and inherits alignment from that structure.  For example, after
1773 this declaration:
1774
1775 @example
1776 struct foo @{ int x; char y; @} foo1;
1777 @end example
1778
1779 @noindent
1780 the value of @code{__alignof__ (foo1.y)} is probably 2 or 4, the same as
1781 @code{__alignof__ (int)}, even though the data type of @code{foo1.y}
1782 does not itself demand any alignment.@refill
1783
1784 A related feature which lets you specify the alignment of an object is
1785 @code{__attribute__ ((aligned (@var{alignment})))}; see the following
1786 section.
1787
1788 @node Variable Attributes
1789 @section Specifying Attributes of Variables
1790 @cindex attribute of variables
1791 @cindex variable attributes
1792
1793 The keyword @code{__attribute__} allows you to specify special
1794 attributes of variables or structure fields.  This keyword is followed
1795 by an attribute specification inside double parentheses.  Eight
1796 attributes are currently defined for variables: @code{aligned},
1797 @code{mode}, @code{nocommon}, @code{packed}, @code{section},
1798 @code{transparent_union}, @code{unused}, and @code{weak}.  Other
1799 attributes are available for functions (@pxref{Function Attributes}) and
1800 for types (@pxref{Type Attributes}).
1801
1802 You may also specify attributes with @samp{__} preceding and following
1803 each keyword.  This allows you to use them in header files without
1804 being concerned about a possible macro of the same name.  For example,
1805 you may use @code{__aligned__} instead of @code{aligned}.
1806
1807 @table @code
1808 @cindex @code{aligned} attribute
1809 @item aligned (@var{alignment})
1810 This attribute specifies a minimum alignment for the variable or
1811 structure field, measured in bytes.  For example, the declaration:
1812
1813 @smallexample
1814 int x __attribute__ ((aligned (16))) = 0;
1815 @end smallexample
1816
1817 @noindent
1818 causes the compiler to allocate the global variable @code{x} on a
1819 16-byte boundary.  On a 68040, this could be used in conjunction with
1820 an @code{asm} expression to access the @code{move16} instruction which
1821 requires 16-byte aligned operands.
1822
1823 You can also specify the alignment of structure fields.  For example, to
1824 create a double-word aligned @code{int} pair, you could write:
1825
1826 @smallexample
1827 struct foo @{ int x[2] __attribute__ ((aligned (8))); @};
1828 @end smallexample
1829
1830 @noindent
1831 This is an alternative to creating a union with a @code{double} member
1832 that forces the union to be double-word aligned.
1833
1834 It is not possible to specify the alignment of functions; the alignment
1835 of functions is determined by the machine's requirements and cannot be
1836 changed.  You cannot specify alignment for a typedef name because such a
1837 name is just an alias, not a distinct type.
1838
1839 As in the preceding examples, you can explicitly specify the alignment
1840 (in bytes) that you wish the compiler to use for a given variable or
1841 structure field.  Alternatively, you can leave out the alignment factor
1842 and just ask the compiler to align a variable or field to the maximum
1843 useful alignment for the target machine you are compiling for.  For
1844 example, you could write:
1845
1846 @smallexample
1847 short array[3] __attribute__ ((aligned));
1848 @end smallexample
1849
1850 Whenever you leave out the alignment factor in an @code{aligned} attribute
1851 specification, the compiler automatically sets the alignment for the declared
1852 variable or field to the largest alignment which is ever used for any data
1853 type on the target machine you are compiling for.  Doing this can often make
1854 copy operations more efficient, because the compiler can use whatever
1855 instructions copy the biggest chunks of memory when performing copies to
1856 or from the variables or fields that you have aligned this way.
1857
1858 The @code{aligned} attribute can only increase the alignment; but you
1859 can decrease it by specifying @code{packed} as well.  See below.
1860
1861 Note that the effectiveness of @code{aligned} attributes may be limited
1862 by inherent limitations in your linker.  On many systems, the linker is
1863 only able to arrange for variables to be aligned up to a certain maximum
1864 alignment.  (For some linkers, the maximum supported alignment may
1865 be very very small.)  If your linker is only able to align variables
1866 up to a maximum of 8 byte alignment, then specifying @code{aligned(16)}
1867 in an @code{__attribute__} will still only provide you with 8 byte
1868 alignment.  See your linker documentation for further information.
1869
1870 @item mode (@var{mode})
1871 @cindex @code{mode} attribute
1872 This attribute specifies the data type for the declaration---whichever
1873 type corresponds to the mode @var{mode}.  This in effect lets you
1874 request an integer or floating point type according to its width.
1875
1876 You may also specify a mode of @samp{byte} or @samp{__byte__} to
1877 indicate the mode corresponding to a one-byte integer, @samp{word} or
1878 @samp{__word__} for the mode of a one-word integer, and @samp{pointer}
1879 or @samp{__pointer__} for the mode used to represent pointers.
1880
1881 @item nocommon
1882 @cindex @code{nocommon} attribute
1883 This attribute specifies requests GNU CC not to place a variable
1884 ``common'' but instead to allocate space for it directly.  If you
1885 specify the @samp{-fno-common} flag, GNU CC will do this for all
1886 variables.
1887
1888 Specifying the @code{nocommon} attribute for a variable provides an
1889 initialization of zeros.  A variable may only be initialized in one
1890 source file.
1891
1892 @item packed
1893 @cindex @code{packed} attribute
1894 The @code{packed} attribute specifies that a variable or structure field
1895 should have the smallest possible alignment---one byte for a variable,
1896 and one bit for a field, unless you specify a larger value with the
1897 @code{aligned} attribute.
1898
1899 Here is a structure in which the field @code{x} is packed, so that it
1900 immediately follows @code{a}:
1901
1902 @example
1903 struct foo
1904 @{
1905   char a;
1906   int x[2] __attribute__ ((packed));
1907 @};
1908 @end example
1909
1910 @item section ("section-name")
1911 @cindex @code{section} variable attribute
1912 Normally, the compiler places the objects it generates in sections like
1913 @code{data} and @code{bss}.  Sometimes, however, you need additional sections,
1914 or you need certain particular variables to appear in special sections,
1915 for example to map to special hardware.  The @code{section}
1916 attribute specifies that a variable (or function) lives in a particular
1917 section.  For example, this small program uses several specific section names:
1918
1919 @smallexample
1920 struct duart a __attribute__ ((section ("DUART_A"))) = @{ 0 @};
1921 struct duart b __attribute__ ((section ("DUART_B"))) = @{ 0 @};
1922 char stack[10000] __attribute__ ((section ("STACK"))) = @{ 0 @};
1923 int init_data __attribute__ ((section ("INITDATA"))) = 0;
1924
1925 main()
1926 @{
1927   /* Initialize stack pointer */
1928   init_sp (stack + sizeof (stack));
1929
1930   /* Initialize initialized data */
1931   memcpy (&init_data, &data, &edata - &data);
1932
1933   /* Turn on the serial ports */
1934   init_duart (&a);
1935   init_duart (&b);
1936 @}
1937 @end smallexample
1938
1939 @noindent
1940 Use the @code{section} attribute with an @emph{initialized} definition
1941 of a @emph{global} variable, as shown in the example.  GNU CC issues
1942 a warning and otherwise ignores the @code{section} attribute in
1943 uninitialized variable declarations.
1944
1945 You may only use the @code{section} attribute with a fully initialized
1946 global definition because of the way linkers work.  The linker requires
1947 each object be defined once, with the exception that uninitialized
1948 variables tentatively go in the @code{common} (or @code{bss}) section
1949 and can be multiply "defined".  You can force a variable to be
1950 initialized with the @samp{-fno-common} flag or the @code{nocommon}
1951 attribute.
1952
1953 Some file formats do not support arbitrary sections so the @code{section}
1954 attribute is not available on all platforms.
1955 If you need to map the entire contents of a module to a particular
1956 section, consider using the facilities of the linker instead.
1957
1958 @item transparent_union
1959 This attribute, attached to a function parameter which is a union, means
1960 that the corresponding argument may have the type of any union member,
1961 but the argument is passed as if its type were that of the first union
1962 member.  For more details see @xref{Type Attributes}.  You can also use
1963 this attribute on a @code{typedef} for a union data type; then it
1964 applies to all function parameters with that type.
1965
1966 @item unused
1967 This attribute, attached to a variable, means that the variable is meant
1968 to be possibly unused.  GNU CC will not produce a warning for this
1969 variable.
1970
1971 @item weak
1972 The @code{weak} attribute is described in @xref{Function Attributes}.
1973
1974 @item model (@var{model-name})
1975 @cindex variable addressability on the M32R/D
1976 Use this attribute on the M32R/D to set the addressability of an object.
1977 The identifier @var{model-name} is one of @code{small}, @code{medium},
1978 or @code{large}, representing each of the code models.
1979
1980 Small model objects live in the lower 16MB of memory (so that their
1981 addresses can be loaded with the @code{ld24} instruction).
1982
1983 Medium and large model objects may live anywhere in the 32 bit address space
1984 (the compiler will generate @code{seth/add3} instructions to load their
1985 addresses).
1986
1987 @end table
1988
1989 To specify multiple attributes, separate them by commas within the
1990 double parentheses: for example, @samp{__attribute__ ((aligned (16),
1991 packed))}.
1992
1993 @node Type Attributes
1994 @section Specifying Attributes of Types
1995 @cindex attribute of types
1996 @cindex type attributes
1997
1998 The keyword @code{__attribute__} allows you to specify special
1999 attributes of @code{struct} and @code{union} types when you define such
2000 types.  This keyword is followed by an attribute specification inside
2001 double parentheses.  Three attributes are currently defined for types:
2002 @code{aligned}, @code{packed}, and @code{transparent_union}.  Other
2003 attributes are defined for functions (@pxref{Function Attributes}) and
2004 for variables (@pxref{Variable Attributes}).
2005
2006 You may also specify any one of these attributes with @samp{__}
2007 preceding and following its keyword.  This allows you to use these
2008 attributes in header files without being concerned about a possible
2009 macro of the same name.  For example, you may use @code{__aligned__}
2010 instead of @code{aligned}.
2011
2012 You may specify the @code{aligned} and @code{transparent_union}
2013 attributes either in a @code{typedef} declaration or just past the
2014 closing curly brace of a complete enum, struct or union type
2015 @emph{definition} and the @code{packed} attribute only past the closing
2016 brace of a definition.
2017
2018 @table @code
2019 @cindex @code{aligned} attribute
2020 @item aligned (@var{alignment})
2021 This attribute specifies a minimum alignment (in bytes) for variables
2022 of the specified type.  For example, the declarations:
2023
2024 @smallexample
2025 struct S @{ short f[3]; @} __attribute__ ((aligned (8)));
2026 typedef int more_aligned_int __attribute__ ((aligned (8)));
2027 @end smallexample
2028
2029 @noindent
2030 force the compiler to insure (as far as it can) that each variable whose
2031 type is @code{struct S} or @code{more_aligned_int} will be allocated and
2032 aligned @emph{at least} on a 8-byte boundary.  On a Sparc, having all
2033 variables of type @code{struct S} aligned to 8-byte boundaries allows
2034 the compiler to use the @code{ldd} and @code{std} (doubleword load and
2035 store) instructions when copying one variable of type @code{struct S} to
2036 another, thus improving run-time efficiency.
2037
2038 Note that the alignment of any given @code{struct} or @code{union} type
2039 is required by the ANSI C standard to be at least a perfect multiple of
2040 the lowest common multiple of the alignments of all of the members of
2041 the @code{struct} or @code{union} in question.  This means that you @emph{can}
2042 effectively adjust the alignment of a @code{struct} or @code{union}
2043 type by attaching an @code{aligned} attribute to any one of the members
2044 of such a type, but the notation illustrated in the example above is a
2045 more obvious, intuitive, and readable way to request the compiler to
2046 adjust the alignment of an entire @code{struct} or @code{union} type.
2047
2048 As in the preceding example, you can explicitly specify the alignment
2049 (in bytes) that you wish the compiler to use for a given @code{struct}
2050 or @code{union} type.  Alternatively, you can leave out the alignment factor
2051 and just ask the compiler to align a type to the maximum
2052 useful alignment for the target machine you are compiling for.  For
2053 example, you could write:
2054
2055 @smallexample
2056 struct S @{ short f[3]; @} __attribute__ ((aligned));
2057 @end smallexample
2058
2059 Whenever you leave out the alignment factor in an @code{aligned}
2060 attribute specification, the compiler automatically sets the alignment
2061 for the type to the largest alignment which is ever used for any data
2062 type on the target machine you are compiling for.  Doing this can often
2063 make copy operations more efficient, because the compiler can use
2064 whatever instructions copy the biggest chunks of memory when performing
2065 copies to or from the variables which have types that you have aligned
2066 this way.
2067
2068 In the example above, if the size of each @code{short} is 2 bytes, then
2069 the size of the entire @code{struct S} type is 6 bytes.  The smallest
2070 power of two which is greater than or equal to that is 8, so the
2071 compiler sets the alignment for the entire @code{struct S} type to 8
2072 bytes.
2073
2074 Note that although you can ask the compiler to select a time-efficient
2075 alignment for a given type and then declare only individual stand-alone
2076 objects of that type, the compiler's ability to select a time-efficient
2077 alignment is primarily useful only when you plan to create arrays of
2078 variables having the relevant (efficiently aligned) type.  If you
2079 declare or use arrays of variables of an efficiently-aligned type, then
2080 it is likely that your program will also be doing pointer arithmetic (or
2081 subscripting, which amounts to the same thing) on pointers to the
2082 relevant type, and the code that the compiler generates for these
2083 pointer arithmetic operations will often be more efficient for
2084 efficiently-aligned types than for other types.
2085
2086 The @code{aligned} attribute can only increase the alignment; but you
2087 can decrease it by specifying @code{packed} as well.  See below.
2088
2089 Note that the effectiveness of @code{aligned} attributes may be limited
2090 by inherent limitations in your linker.  On many systems, the linker is
2091 only able to arrange for variables to be aligned up to a certain maximum
2092 alignment.  (For some linkers, the maximum supported alignment may
2093 be very very small.)  If your linker is only able to align variables
2094 up to a maximum of 8 byte alignment, then specifying @code{aligned(16)}
2095 in an @code{__attribute__} will still only provide you with 8 byte
2096 alignment.  See your linker documentation for further information.
2097
2098 @item packed
2099 This attribute, attached to an @code{enum}, @code{struct}, or
2100 @code{union} type definition, specified that the minimum required memory
2101 be used to represent the type.
2102
2103 Specifying this attribute for @code{struct} and @code{union} types is
2104 equivalent to specifying the @code{packed} attribute on each of the
2105 structure or union members.  Specifying the @samp{-fshort-enums}
2106 flag on the line is equivalent to specifying the @code{packed}
2107 attribute on all @code{enum} definitions.
2108
2109 You may only specify this attribute after a closing curly brace on an
2110 @code{enum} definition, not in a @code{typedef} declaration, unless that
2111 declaration also contains the definition of the @code{enum}.
2112
2113 @item transparent_union
2114 This attribute, attached to a @code{union} type definition, indicates
2115 that any function parameter having that union type causes calls to that
2116 function to be treated in a special way.
2117
2118 First, the argument corresponding to a transparent union type can be of
2119 any type in the union; no cast is required.  Also, if the union contains
2120 a pointer type, the corresponding argument can be a null pointer
2121 constant or a void pointer expression; and if the union contains a void
2122 pointer type, the corresponding argument can be any pointer expression.
2123 If the union member type is a pointer, qualifiers like @code{const} on
2124 the referenced type must be respected, just as with normal pointer
2125 conversions.
2126
2127 Second, the argument is passed to the function using the calling
2128 conventions of first member of the transparent union, not the calling
2129 conventions of the union itself.  All members of the union must have the
2130 same machine representation; this is necessary for this argument passing
2131 to work properly.
2132
2133 Transparent unions are designed for library functions that have multiple
2134 interfaces for compatibility reasons.  For example, suppose the
2135 @code{wait} function must accept either a value of type @code{int *} to
2136 comply with Posix, or a value of type @code{union wait *} to comply with
2137 the 4.1BSD interface.  If @code{wait}'s parameter were @code{void *},
2138 @code{wait} would accept both kinds of arguments, but it would also
2139 accept any other pointer type and this would make argument type checking
2140 less useful.  Instead, @code{<sys/wait.h>} might define the interface
2141 as follows:
2142
2143 @smallexample
2144 typedef union
2145   @{
2146     int *__ip;
2147     union wait *__up;
2148   @} wait_status_ptr_t __attribute__ ((__transparent_union__));
2149
2150 pid_t wait (wait_status_ptr_t);
2151 @end smallexample
2152
2153 This interface allows either @code{int *} or @code{union wait *}
2154 arguments to be passed, using the @code{int *} calling convention.
2155 The program can call @code{wait} with arguments of either type:
2156
2157 @example
2158 int w1 () @{ int w; return wait (&w); @}
2159 int w2 () @{ union wait w; return wait (&w); @}
2160 @end example
2161
2162 With this interface, @code{wait}'s implementation might look like this:
2163
2164 @example
2165 pid_t wait (wait_status_ptr_t p)
2166 @{
2167   return waitpid (-1, p.__ip, 0);
2168 @}
2169 @end example
2170
2171 @item unused
2172 When attached to a type (including a @code{union} or a @code{struct}),
2173 this attribute means that variables of that type are meant to appear
2174 possibly unused.  GNU CC will not produce a warning for any variables of
2175 that type, even if the variable appears to do nothing.  This is often
2176 the case with lock or thread classes, which are usually defined and then
2177 not referenced, but contain constructors and destructors that have
2178 nontrivial bookkeeping functions.
2179
2180 @end table
2181
2182 To specify multiple attributes, separate them by commas within the
2183 double parentheses: for example, @samp{__attribute__ ((aligned (16),
2184 packed))}.
2185
2186 @node Inline
2187 @section An Inline Function is As Fast As a Macro
2188 @cindex inline functions
2189 @cindex integrating function code
2190 @cindex open coding
2191 @cindex macros, inline alternative
2192
2193 By declaring a function @code{inline}, you can direct GNU CC to
2194 integrate that function's code into the code for its callers.  This
2195 makes execution faster by eliminating the function-call overhead; in
2196 addition, if any of the actual argument values are constant, their known
2197 values may permit simplifications at compile time so that not all of the
2198 inline function's code needs to be included.  The effect on code size is
2199 less predictable; object code may be larger or smaller with function
2200 inlining, depending on the particular case.  Inlining of functions is an
2201 optimization and it really ``works'' only in optimizing compilation.  If
2202 you don't use @samp{-O}, no function is really inline.
2203
2204 To declare a function inline, use the @code{inline} keyword in its
2205 declaration, like this:
2206
2207 @example
2208 inline int
2209 inc (int *a)
2210 @{
2211   (*a)++;
2212 @}
2213 @end example
2214
2215 (If you are writing a header file to be included in ANSI C programs, write
2216 @code{__inline__} instead of @code{inline}.  @xref{Alternate Keywords}.)
2217
2218 You can also make all ``simple enough'' functions inline with the option
2219 @samp{-finline-functions}.  Note that certain usages in a function
2220 definition can make it unsuitable for inline substitution.
2221
2222 Note that in C and Objective C, unlike C++, the @code{inline} keyword
2223 does not affect the linkage of the function.
2224
2225 @cindex automatic @code{inline} for C++ member fns
2226 @cindex @code{inline} automatic for C++ member fns
2227 @cindex member fns, automatically @code{inline}
2228 @cindex C++ member fns, automatically @code{inline}
2229 GNU CC automatically inlines member functions defined within the class
2230 body of C++ programs even if they are not explicitly declared
2231 @code{inline}.  (You can override this with @samp{-fno-default-inline};
2232 @pxref{C++ Dialect Options,,Options Controlling C++ Dialect}.)
2233
2234 @cindex inline functions, omission of
2235 When a function is both inline and @code{static}, if all calls to the
2236 function are integrated into the caller, and the function's address is
2237 never used, then the function's own assembler code is never referenced.
2238 In this case, GNU CC does not actually output assembler code for the
2239 function, unless you specify the option @samp{-fkeep-inline-functions}.
2240 Some calls cannot be integrated for various reasons (in particular,
2241 calls that precede the function's definition cannot be integrated, and
2242 neither can recursive calls within the definition).  If there is a
2243 nonintegrated call, then the function is compiled to assembler code as
2244 usual.  The function must also be compiled as usual if the program
2245 refers to its address, because that can't be inlined.
2246
2247 @cindex non-static inline function
2248 When an inline function is not @code{static}, then the compiler must assume
2249 that there may be calls from other source files; since a global symbol can
2250 be defined only once in any program, the function must not be defined in
2251 the other source files, so the calls therein cannot be integrated.
2252 Therefore, a non-@code{static} inline function is always compiled on its
2253 own in the usual fashion.
2254
2255 If you specify both @code{inline} and @code{extern} in the function
2256 definition, then the definition is used only for inlining.  In no case
2257 is the function compiled on its own, not even if you refer to its
2258 address explicitly.  Such an address becomes an external reference, as
2259 if you had only declared the function, and had not defined it.
2260
2261 This combination of @code{inline} and @code{extern} has almost the
2262 effect of a macro.  The way to use it is to put a function definition in
2263 a header file with these keywords, and put another copy of the
2264 definition (lacking @code{inline} and @code{extern}) in a library file.
2265 The definition in the header file will cause most calls to the function
2266 to be inlined.  If any uses of the function remain, they will refer to
2267 the single copy in the library.
2268
2269 GNU C does not inline any functions when not optimizing.  It is not
2270 clear whether it is better to inline or not, in this case, but we found
2271 that a correct implementation when not optimizing was difficult.  So we
2272 did the easy thing, and turned it off.
2273
2274 @node Extended Asm
2275 @section Assembler Instructions with C Expression Operands
2276 @cindex extended @code{asm}
2277 @cindex @code{asm} expressions
2278 @cindex assembler instructions
2279 @cindex registers
2280
2281 In an assembler instruction using @code{asm}, you can specify the
2282 operands of the instruction using C expressions.  This means you need not
2283 guess which registers or memory locations will contain the data you want
2284 to use.
2285
2286 You must specify an assembler instruction template much like what
2287 appears in a machine description, plus an operand constraint string for
2288 each operand.
2289
2290 For example, here is how to use the 68881's @code{fsinx} instruction:
2291
2292 @example
2293 asm ("fsinx %1,%0" : "=f" (result) : "f" (angle));
2294 @end example
2295
2296 @noindent
2297 Here @code{angle} is the C expression for the input operand while
2298 @code{result} is that of the output operand.  Each has @samp{"f"} as its
2299 operand constraint, saying that a floating point register is required.
2300 The @samp{=} in @samp{=f} indicates that the operand is an output; all
2301 output operands' constraints must use @samp{=}.  The constraints use the
2302 same language used in the machine description (@pxref{Constraints}).
2303
2304 Each operand is described by an operand-constraint string followed by
2305 the C expression in parentheses.  A colon separates the assembler
2306 template from the first output operand and another separates the last
2307 output operand from the first input, if any.  Commas separate the
2308 operands within each group.  The total number of operands is limited to
2309 ten or to the maximum number of operands in any instruction pattern in
2310 the machine description, whichever is greater.
2311
2312 If there are no output operands but there are input operands, you must
2313 place two consecutive colons surrounding the place where the output
2314 operands would go.
2315
2316 Output operand expressions must be lvalues; the compiler can check this.
2317 The input operands need not be lvalues.  The compiler cannot check
2318 whether the operands have data types that are reasonable for the
2319 instruction being executed.  It does not parse the assembler instruction
2320 template and does not know what it means or even whether it is valid
2321 assembler input.  The extended @code{asm} feature is most often used for
2322 machine instructions the compiler itself does not know exist.  If
2323 the output expression cannot be directly addressed (for example, it is a
2324 bit field), your constraint must allow a register.  In that case, GNU CC
2325 will use the register as the output of the @code{asm}, and then store
2326 that register into the output.
2327
2328 The ordinary output operands must be write-only; GNU CC will assume that
2329 the values in these operands before the instruction are dead and need
2330 not be generated.  Extended asm supports input-output or read-write
2331 operands.  Use the constraint character @samp{+} to indicate such an
2332 operand and list it with the output operands.
2333
2334 When the constraints for the read-write operand (or the operand in which
2335 only some of the bits are to be changed) allows a register, you may, as
2336 an alternative, logically split its function into two separate operands,
2337 one input operand and one write-only output operand.  The connection
2338 between them is expressed by constraints which say they need to be in
2339 the same location when the instruction executes.  You can use the same C
2340 expression for both operands, or different expressions.  For example,
2341 here we write the (fictitious) @samp{combine} instruction with
2342 @code{bar} as its read-only source operand and @code{foo} as its
2343 read-write destination:
2344
2345 @example
2346 asm ("combine %2,%0" : "=r" (foo) : "0" (foo), "g" (bar));
2347 @end example
2348
2349 @noindent
2350 The constraint @samp{"0"} for operand 1 says that it must occupy the
2351 same location as operand 0.  A digit in constraint is allowed only in an
2352 input operand and it must refer to an output operand.
2353
2354 Only a digit in the constraint can guarantee that one operand will be in
2355 the same place as another.  The mere fact that @code{foo} is the value
2356 of both operands is not enough to guarantee that they will be in the
2357 same place in the generated assembler code.  The following would not
2358 work reliably:
2359
2360 @example
2361 asm ("combine %2,%0" : "=r" (foo) : "r" (foo), "g" (bar));
2362 @end example
2363
2364 Various optimizations or reloading could cause operands 0 and 1 to be in
2365 different registers; GNU CC knows no reason not to do so.  For example, the
2366 compiler might find a copy of the value of @code{foo} in one register and
2367 use it for operand 1, but generate the output operand 0 in a different
2368 register (copying it afterward to @code{foo}'s own address).  Of course,
2369 since the register for operand 1 is not even mentioned in the assembler
2370 code, the result will not work, but GNU CC can't tell that.
2371
2372 Some instructions clobber specific hard registers.  To describe this,
2373 write a third colon after the input operands, followed by the names of
2374 the clobbered hard registers (given as strings).  Here is a realistic
2375 example for the VAX:
2376
2377 @example
2378 asm volatile ("movc3 %0,%1,%2"
2379               : /* no outputs */
2380               : "g" (from), "g" (to), "g" (count)
2381               : "r0", "r1", "r2", "r3", "r4", "r5");
2382 @end example
2383
2384 If you refer to a particular hardware register from the assembler code,
2385 you will probably have to list the register after the third colon to
2386 tell the compiler the register's value is modified.  In some assemblers,
2387 the register names begin with @samp{%}; to produce one @samp{%} in the
2388 assembler code, you must write @samp{%%} in the input.
2389
2390 If your assembler instruction can alter the condition code register, add
2391 @samp{cc} to the list of clobbered registers.  GNU CC on some machines
2392 represents the condition codes as a specific hardware register;
2393 @samp{cc} serves to name this register.  On other machines, the
2394 condition code is handled differently, and specifying @samp{cc} has no
2395 effect.  But it is valid no matter what the machine.
2396
2397 If your assembler instruction modifies memory in an unpredictable
2398 fashion, add @samp{memory} to the list of clobbered registers.  This
2399 will cause GNU CC to not keep memory values cached in registers across
2400 the assembler instruction.
2401
2402 You can put multiple assembler instructions together in a single
2403 @code{asm} template, separated either with newlines (written as
2404 @samp{\n}) or with semicolons if the assembler allows such semicolons.
2405 The GNU assembler allows semicolons and most Unix assemblers seem to do
2406 so.  The input operands are guaranteed not to use any of the clobbered
2407 registers, and neither will the output operands' addresses, so you can
2408 read and write the clobbered registers as many times as you like.  Here
2409 is an example of multiple instructions in a template; it assumes the
2410 subroutine @code{_foo} accepts arguments in registers 9 and 10:
2411
2412 @example
2413 asm ("movl %0,r9;movl %1,r10;call _foo"
2414      : /* no outputs */
2415      : "g" (from), "g" (to)
2416      : "r9", "r10");
2417 @end example
2418
2419 Unless an output operand has the @samp{&} constraint modifier, GNU CC
2420 may allocate it in the same register as an unrelated input operand, on
2421 the assumption the inputs are consumed before the outputs are produced.
2422 This assumption may be false if the assembler code actually consists of
2423 more than one instruction.  In such a case, use @samp{&} for each output
2424 operand that may not overlap an input.  @xref{Modifiers}.
2425
2426 If you want to test the condition code produced by an assembler
2427 instruction, you must include a branch and a label in the @code{asm}
2428 construct, as follows:
2429
2430 @example
2431 asm ("clr %0;frob %1;beq 0f;mov #1,%0;0:"
2432      : "g" (result)
2433      : "g" (input));
2434 @end example
2435
2436 @noindent
2437 This assumes your assembler supports local labels, as the GNU assembler
2438 and most Unix assemblers do.
2439
2440 Speaking of labels, jumps from one @code{asm} to another are not
2441 supported.  The compiler's optimizers do not know about these jumps, and
2442 therefore they cannot take account of them when deciding how to
2443 optimize.
2444
2445 @cindex macros containing @code{asm}
2446 Usually the most convenient way to use these @code{asm} instructions is to
2447 encapsulate them in macros that look like functions.  For example,
2448
2449 @example
2450 #define sin(x)       \
2451 (@{ double __value, __arg = (x);   \
2452    asm ("fsinx %1,%0": "=f" (__value): "f" (__arg));  \
2453    __value; @})
2454 @end example
2455
2456 @noindent
2457 Here the variable @code{__arg} is used to make sure that the instruction
2458 operates on a proper @code{double} value, and to accept only those
2459 arguments @code{x} which can convert automatically to a @code{double}.
2460
2461 Another way to make sure the instruction operates on the correct data
2462 type is to use a cast in the @code{asm}.  This is different from using a
2463 variable @code{__arg} in that it converts more different types.  For
2464 example, if the desired type were @code{int}, casting the argument to
2465 @code{int} would accept a pointer with no complaint, while assigning the
2466 argument to an @code{int} variable named @code{__arg} would warn about
2467 using a pointer unless the caller explicitly casts it.
2468
2469 If an @code{asm} has output operands, GNU CC assumes for optimization
2470 purposes the instruction has no side effects except to change the output
2471 operands.  This does not mean instructions with a side effect cannot be
2472 used, but you must be careful, because the compiler may eliminate them
2473 if the output operands aren't used, or move them out of loops, or
2474 replace two with one if they constitute a common subexpression.  Also,
2475 if your instruction does have a side effect on a variable that otherwise
2476 appears not to change, the old value of the variable may be reused later
2477 if it happens to be found in a register.
2478
2479 You can prevent an @code{asm} instruction from being deleted, moved
2480 significantly, or combined, by writing the keyword @code{volatile} after
2481 the @code{asm}.  For example:
2482
2483 @example
2484 #define get_and_set_priority(new)  \
2485 (@{ int __old; \
2486    asm volatile ("get_and_set_priority %0, %1": "=g" (__old) : "g" (new)); \
2487    __old; @})
2488 b@end example
2489
2490 @noindent
2491 If you write an @code{asm} instruction with no outputs, GNU CC will know
2492 the instruction has side-effects and will not delete the instruction or
2493 move it outside of loops.  If the side-effects of your instruction are
2494 not purely external, but will affect variables in your program in ways
2495 other than reading the inputs and clobbering the specified registers or
2496 memory, you should write the @code{volatile} keyword to prevent future
2497 versions of GNU CC from moving the instruction around within a core
2498 region.
2499
2500 An @code{asm} instruction without any operands or clobbers (and ``old
2501 style'' @code{asm}) will not be deleted or moved significantly,
2502 regardless, unless it is unreachable, the same wasy as if you had
2503 written a @code{volatile} keyword.
2504
2505 Note that even a volatile @code{asm} instruction can be moved in ways
2506 that appear insignificant to the compiler, such as across jump
2507 instructions.  You can't expect a sequence of volatile @code{asm}
2508 instructions to remain perfectly consecutive.  If you want consecutive
2509 output, use a single @code{asm}.
2510
2511 It is a natural idea to look for a way to give access to the condition
2512 code left by the assembler instruction.  However, when we attempted to
2513 implement this, we found no way to make it work reliably.  The problem
2514 is that output operands might need reloading, which would result in
2515 additional following ``store'' instructions.  On most machines, these
2516 instructions would alter the condition code before there was time to
2517 test it.  This problem doesn't arise for ordinary ``test'' and
2518 ``compare'' instructions because they don't have any output operands.
2519
2520 If you are writing a header file that should be includable in ANSI C
2521 programs, write @code{__asm__} instead of @code{asm}.  @xref{Alternate
2522 Keywords}.
2523
2524 @ifclear INTERNALS
2525 @c Show the details on constraints if they do not appear elsewhere in
2526 @c the manual
2527 @include md.texi
2528 @end ifclear
2529
2530 @node Asm Labels
2531 @section Controlling Names Used in Assembler Code
2532 @cindex assembler names for identifiers
2533 @cindex names used in assembler code
2534 @cindex identifiers, names in assembler code
2535
2536 You can specify the name to be used in the assembler code for a C
2537 function or variable by writing the @code{asm} (or @code{__asm__})
2538 keyword after the declarator as follows:
2539
2540 @example
2541 int foo asm ("myfoo") = 2;
2542 @end example
2543
2544 @noindent
2545 This specifies that the name to be used for the variable @code{foo} in
2546 the assembler code should be @samp{myfoo} rather than the usual
2547 @samp{_foo}.
2548
2549 On systems where an underscore is normally prepended to the name of a C
2550 function or variable, this feature allows you to define names for the
2551 linker that do not start with an underscore.
2552
2553 You cannot use @code{asm} in this way in a function @emph{definition}; but
2554 you can get the same effect by writing a declaration for the function
2555 before its definition and putting @code{asm} there, like this:
2556
2557 @example
2558 extern func () asm ("FUNC");
2559
2560 func (x, y)
2561      int x, y;
2562 @dots{}
2563 @end example
2564
2565 It is up to you to make sure that the assembler names you choose do not
2566 conflict with any other assembler symbols.  Also, you must not use a
2567 register name; that would produce completely invalid assembler code.  GNU
2568 CC does not as yet have the ability to store static variables in registers.
2569 Perhaps that will be added.
2570
2571 @node Explicit Reg Vars
2572 @section Variables in Specified Registers
2573 @cindex explicit register variables
2574 @cindex variables in specified registers
2575 @cindex specified registers
2576 @cindex registers, global allocation
2577
2578 GNU C allows you to put a few global variables into specified hardware
2579 registers.  You can also specify the register in which an ordinary
2580 register variable should be allocated.
2581
2582 @itemize @bullet
2583 @item
2584 Global register variables reserve registers throughout the program.
2585 This may be useful in programs such as programming language
2586 interpreters which have a couple of global variables that are accessed
2587 very often.
2588
2589 @item
2590 Local register variables in specific registers do not reserve the
2591 registers.  The compiler's data flow analysis is capable of determining
2592 where the specified registers contain live values, and where they are
2593 available for other uses.
2594
2595 These local variables are sometimes convenient for use with the extended
2596 @code{asm} feature (@pxref{Extended Asm}), if you want to write one
2597 output of the assembler instruction directly into a particular register.
2598 (This will work provided the register you specify fits the constraints
2599 specified for that operand in the @code{asm}.)
2600 @end itemize
2601
2602 @menu
2603 * Global Reg Vars::
2604 * Local Reg Vars::
2605 @end menu
2606
2607 @node Global Reg Vars
2608 @subsection Defining Global Register Variables
2609 @cindex global register variables
2610 @cindex registers, global variables in
2611
2612 You can define a global register variable in GNU C like this:
2613
2614 @example
2615 register int *foo asm ("a5");
2616 @end example
2617
2618 @noindent
2619 Here @code{a5} is the name of the register which should be used.  Choose a
2620 register which is normally saved and restored by function calls on your
2621 machine, so that library routines will not clobber it.
2622
2623 Naturally the register name is cpu-dependent, so you would need to
2624 conditionalize your program according to cpu type.  The register
2625 @code{a5} would be a good choice on a 68000 for a variable of pointer
2626 type.  On machines with register windows, be sure to choose a ``global''
2627 register that is not affected magically by the function call mechanism.
2628
2629 In addition, operating systems on one type of cpu may differ in how they
2630 name the registers; then you would need additional conditionals.  For
2631 example, some 68000 operating systems call this register @code{%a5}.
2632
2633 Eventually there may be a way of asking the compiler to choose a register
2634 automatically, but first we need to figure out how it should choose and
2635 how to enable you to guide the choice.  No solution is evident.
2636
2637 Defining a global register variable in a certain register reserves that
2638 register entirely for this use, at least within the current compilation.
2639 The register will not be allocated for any other purpose in the functions
2640 in the current compilation.  The register will not be saved and restored by
2641 these functions.  Stores into this register are never deleted even if they
2642 would appear to be dead, but references may be deleted or moved or
2643 simplified.
2644
2645 It is not safe to access the global register variables from signal
2646 handlers, or from more than one thread of control, because the system
2647 library routines may temporarily use the register for other things (unless
2648 you recompile them specially for the task at hand).
2649
2650 @cindex @code{qsort}, and global register variables
2651 It is not safe for one function that uses a global register variable to
2652 call another such function @code{foo} by way of a third function
2653 @code{lose} that was compiled without knowledge of this variable (i.e. in a
2654 different source file in which the variable wasn't declared).  This is
2655 because @code{lose} might save the register and put some other value there.
2656 For example, you can't expect a global register variable to be available in
2657 the comparison-function that you pass to @code{qsort}, since @code{qsort}
2658 might have put something else in that register.  (If you are prepared to
2659 recompile @code{qsort} with the same global register variable, you can
2660 solve this problem.)
2661
2662 If you want to recompile @code{qsort} or other source files which do not
2663 actually use your global register variable, so that they will not use that
2664 register for any other purpose, then it suffices to specify the compiler
2665 option @samp{-ffixed-@var{reg}}.  You need not actually add a global
2666 register declaration to their source code.
2667
2668 A function which can alter the value of a global register variable cannot
2669 safely be called from a function compiled without this variable, because it
2670 could clobber the value the caller expects to find there on return.
2671 Therefore, the function which is the entry point into the part of the
2672 program that uses the global register variable must explicitly save and
2673 restore the value which belongs to its caller.
2674
2675 @cindex register variable after @code{longjmp}
2676 @cindex global register after @code{longjmp}
2677 @cindex value after @code{longjmp}
2678 @findex longjmp
2679 @findex setjmp
2680 On most machines, @code{longjmp} will restore to each global register
2681 variable the value it had at the time of the @code{setjmp}.  On some
2682 machines, however, @code{longjmp} will not change the value of global
2683 register variables.  To be portable, the function that called @code{setjmp}
2684 should make other arrangements to save the values of the global register
2685 variables, and to restore them in a @code{longjmp}.  This way, the same
2686 thing will happen regardless of what @code{longjmp} does.
2687
2688 All global register variable declarations must precede all function
2689 definitions.  If such a declaration could appear after function
2690 definitions, the declaration would be too late to prevent the register from
2691 being used for other purposes in the preceding functions.
2692
2693 Global register variables may not have initial values, because an
2694 executable file has no means to supply initial contents for a register.
2695
2696 On the Sparc, there are reports that g3 @dots{} g7 are suitable
2697 registers, but certain library functions, such as @code{getwd}, as well
2698 as the subroutines for division and remainder, modify g3 and g4.  g1 and
2699 g2 are local temporaries.
2700
2701 On the 68000, a2 @dots{} a5 should be suitable, as should d2 @dots{} d7.
2702 Of course, it will not do to use more than a few of those.
2703
2704 @node Local Reg Vars
2705 @subsection Specifying Registers for Local Variables
2706 @cindex local variables, specifying registers
2707 @cindex specifying registers for local variables
2708 @cindex registers for local variables
2709
2710 You can define a local register variable with a specified register
2711 like this:
2712
2713 @example
2714 register int *foo asm ("a5");
2715 @end example
2716
2717 @noindent
2718 Here @code{a5} is the name of the register which should be used.  Note
2719 that this is the same syntax used for defining global register
2720 variables, but for a local variable it would appear within a function.
2721
2722 Naturally the register name is cpu-dependent, but this is not a
2723 problem, since specific registers are most often useful with explicit
2724 assembler instructions (@pxref{Extended Asm}).  Both of these things
2725 generally require that you conditionalize your program according to
2726 cpu type.
2727
2728 In addition, operating systems on one type of cpu may differ in how they
2729 name the registers; then you would need additional conditionals.  For
2730 example, some 68000 operating systems call this register @code{%a5}.
2731
2732 Defining such a register variable does not reserve the register; it
2733 remains available for other uses in places where flow control determines
2734 the variable's value is not live.  However, these registers are made
2735 unavailable for use in the reload pass; excessive use of this feature
2736 leaves the compiler too few available registers to compile certain
2737 functions.
2738
2739 This option does not guarantee that GNU CC will generate code that has
2740 this variable in the register you specify at all times.  You may not
2741 code an explicit reference to this register in an @code{asm} statement
2742 and assume it will always refer to this variable.
2743
2744 @node Alternate Keywords
2745 @section Alternate Keywords
2746 @cindex alternate keywords
2747 @cindex keywords, alternate
2748
2749 The option @samp{-traditional} disables certain keywords; @samp{-ansi}
2750 disables certain others.  This causes trouble when you want to use GNU C
2751 extensions, or ANSI C features, in a general-purpose header file that
2752 should be usable by all programs, including ANSI C programs and traditional
2753 ones.  The keywords @code{asm}, @code{typeof} and @code{inline} cannot be
2754 used since they won't work in a program compiled with @samp{-ansi}, while
2755 the keywords @code{const}, @code{volatile}, @code{signed}, @code{typeof}
2756 and @code{inline} won't work in a program compiled with
2757 @samp{-traditional}.@refill
2758
2759 The way to solve these problems is to put @samp{__} at the beginning and
2760 end of each problematical keyword.  For example, use @code{__asm__}
2761 instead of @code{asm}, @code{__const__} instead of @code{const}, and
2762 @code{__inline__} instead of @code{inline}.
2763
2764 Other C compilers won't accept these alternative keywords; if you want to
2765 compile with another compiler, you can define the alternate keywords as
2766 macros to replace them with the customary keywords.  It looks like this:
2767
2768 @example
2769 #ifndef __GNUC__
2770 #define __asm__ asm
2771 #endif
2772 @end example
2773
2774 @samp{-pedantic} causes warnings for many GNU C extensions.  You can
2775 prevent such warnings within one expression by writing
2776 @code{__extension__} before the expression.  @code{__extension__} has no
2777 effect aside from this.
2778
2779 @node Incomplete Enums
2780 @section Incomplete @code{enum} Types
2781
2782 You can define an @code{enum} tag without specifying its possible values.
2783 This results in an incomplete type, much like what you get if you write
2784 @code{struct foo} without describing the elements.  A later declaration
2785 which does specify the possible values completes the type.
2786
2787 You can't allocate variables or storage using the type while it is
2788 incomplete.  However, you can work with pointers to that type.
2789
2790 This extension may not be very useful, but it makes the handling of
2791 @code{enum} more consistent with the way @code{struct} and @code{union}
2792 are handled.
2793
2794 This extension is not supported by GNU C++.
2795
2796 @node Function Names
2797 @section Function Names as Strings
2798
2799 GNU CC predefines two string variables to be the name of the current function.
2800 The variable @code{__FUNCTION__} is the name of the function as it appears
2801 in the source.  The variable @code{__PRETTY_FUNCTION__} is the name of
2802 the function pretty printed in a language specific fashion.
2803
2804 These names are always the same in a C function, but in a C++ function
2805 they may be different.  For example, this program:
2806
2807 @smallexample
2808 extern "C" @{
2809 extern int printf (char *, ...);
2810 @}
2811
2812 class a @{
2813  public:
2814   sub (int i)
2815     @{
2816       printf ("__FUNCTION__ = %s\n", __FUNCTION__);
2817       printf ("__PRETTY_FUNCTION__ = %s\n", __PRETTY_FUNCTION__);
2818     @}
2819 @};
2820
2821 int
2822 main (void)
2823 @{
2824   a ax;
2825   ax.sub (0);
2826   return 0;
2827 @}
2828 @end smallexample
2829
2830 @noindent
2831 gives this output:
2832
2833 @smallexample
2834 __FUNCTION__ = sub
2835 __PRETTY_FUNCTION__ = int  a::sub (int)
2836 @end smallexample
2837
2838 These names are not macros: they are predefined string variables.
2839 For example, @samp{#ifdef __FUNCTION__} does not have any special
2840 meaning inside a function, since the preprocessor does not do anything
2841 special with the identifier @code{__FUNCTION__}.
2842
2843 @node Return Address
2844 @section Getting the Return or Frame Address of a Function
2845
2846 These functions may be used to get information about the callers of a
2847 function.
2848
2849 @table @code
2850 @item __builtin_return_address (@var{level})
2851 This function returns the return address of the current function, or of
2852 one of its callers.  The @var{level} argument is number of frames to
2853 scan up the call stack.  A value of @code{0} yields the return address
2854 of the current function, a value of @code{1} yields the return address
2855 of the caller of the current function, and so forth.
2856
2857 The @var{level} argument must be a constant integer.
2858
2859 On some machines it may be impossible to determine the return address of
2860 any function other than the current one; in such cases, or when the top
2861 of the stack has been reached, this function will return @code{0}.
2862
2863 This function should only be used with a non-zero argument for debugging
2864 purposes.
2865
2866 @item __builtin_frame_address (@var{level})
2867 This function is similar to @code{__builtin_return_address}, but it
2868 returns the address of the function frame rather than the return address
2869 of the function.  Calling @code{__builtin_frame_address} with a value of
2870 @code{0} yields the frame address of the current function, a value of
2871 @code{1} yields the frame address of the caller of the current function,
2872 and so forth.
2873
2874 The frame is the area on the stack which holds local variables and saved
2875 registers.  The frame address is normally the address of the first word
2876 pushed on to the stack by the function.  However, the exact definition
2877 depends upon the processor and the calling convention.  If the processor
2878 has a dedicated frame pointer register, and the function has a frame,
2879 then @code{__builtin_frame_address} will return the value of the frame
2880 pointer register.
2881
2882 The caveats that apply to @code{__builtin_return_address} apply to this
2883 function as well.
2884 @end table
2885
2886 @node C++ Extensions
2887 @chapter Extensions to the C++ Language
2888 @cindex extensions, C++ language
2889 @cindex C++ language extensions
2890
2891 The GNU compiler provides these extensions to the C++ language (and you
2892 can also use most of the C language extensions in your C++ programs).  If you
2893 want to write code that checks whether these features are available, you can
2894 test for the GNU compiler the same way as for C programs: check for a
2895 predefined macro @code{__GNUC__}.  You can also use @code{__GNUG__} to
2896 test specifically for GNU C++ (@pxref{Standard Predefined,,Standard
2897 Predefined Macros,cpp.info,The C Preprocessor}).
2898
2899 @menu
2900 * Naming Results::      Giving a name to C++ function return values.
2901 * Min and Max::         C++ Minimum and maximum operators.
2902 * Destructors and Goto:: Goto is safe to use in C++ even when destructors
2903                            are needed.
2904 * C++ Interface::       You can use a single C++ header file for both
2905                          declarations and definitions.
2906 * Template Instantiation:: Methods for ensuring that exactly one copy of
2907                          each needed template instantiation is emitted.
2908 * C++ Signatures::      You can specify abstract types to get subtype
2909                          polymorphism independent from inheritance.
2910 @end menu
2911
2912 @node Naming Results
2913 @section Named Return Values in C++
2914
2915 @cindex @code{return}, in C++ function header
2916 @cindex return value, named, in C++
2917 @cindex named return value in C++
2918 @cindex C++ named return value
2919 GNU C++ extends the function-definition syntax to allow you to specify a
2920 name for the result of a function outside the body of the definition, in
2921 C++ programs:
2922
2923 @example
2924 @group
2925 @var{type}
2926 @var{functionname} (@var{args}) return @var{resultname};
2927 @{
2928   @dots{}
2929   @var{body}
2930   @dots{}
2931 @}
2932 @end group
2933 @end example
2934
2935 You can use this feature to avoid an extra constructor call when
2936 a function result has a class type.  For example, consider a function
2937 @code{m}, declared as @w{@samp{X v = m ();}}, whose result is of class
2938 @code{X}:
2939
2940 @example
2941 X
2942 m ()
2943 @{
2944   X b;
2945   b.a = 23;
2946   return b;
2947 @}
2948 @end example
2949
2950 @cindex implicit argument: return value
2951 Although @code{m} appears to have no arguments, in fact it has one implicit
2952 argument: the address of the return value.  At invocation, the address
2953 of enough space to hold @code{v} is sent in as the implicit argument.
2954 Then @code{b} is constructed and its @code{a} field is set to the value
2955 23.  Finally, a copy constructor (a constructor of the form @samp{X(X&)})
2956 is applied to @code{b}, with the (implicit) return value location as the
2957 target, so that @code{v} is now bound to the return value.
2958
2959 But this is wasteful.  The local @code{b} is declared just to hold
2960 something that will be copied right out.  While a compiler that
2961 combined an ``elision'' algorithm with interprocedural data flow
2962 analysis could conceivably eliminate all of this, it is much more
2963 practical to allow you to assist the compiler in generating
2964 efficient code by manipulating the return value explicitly,
2965 thus avoiding the local variable and copy constructor altogether.
2966
2967 Using the extended GNU C++ function-definition syntax, you can avoid the
2968 temporary allocation and copying by naming @code{r} as your return value
2969 at the outset, and assigning to its @code{a} field directly:
2970
2971 @example
2972 X
2973 m () return r;
2974 @{
2975   r.a = 23;
2976 @}
2977 @end example
2978
2979 @noindent
2980 The declaration of @code{r} is a standard, proper declaration, whose effects
2981 are executed @strong{before} any of the body of @code{m}.
2982
2983 Functions of this type impose no additional restrictions; in particular,
2984 you can execute @code{return} statements, or return implicitly by
2985 reaching the end of the function body (``falling off the edge'').
2986 Cases like
2987
2988 @example
2989 X
2990 m () return r (23);
2991 @{
2992   return;
2993 @}
2994 @end example
2995
2996 @noindent
2997 (or even @w{@samp{X m () return r (23); @{ @}}}) are unambiguous, since
2998 the return value @code{r} has been initialized in either case.  The
2999 following code may be hard to read, but also works predictably:
3000
3001 @example
3002 X
3003 m () return r;
3004 @{
3005   X b;
3006   return b;
3007 @}
3008 @end example
3009
3010 The return value slot denoted by @code{r} is initialized at the outset,
3011 but the statement @samp{return b;} overrides this value.  The compiler
3012 deals with this by destroying @code{r} (calling the destructor if there
3013 is one, or doing nothing if there is not), and then reinitializing
3014 @code{r} with @code{b}.
3015
3016 This extension is provided primarily to help people who use overloaded
3017 operators, where there is a great need to control not just the
3018 arguments, but the return values of functions.  For classes where the
3019 copy constructor incurs a heavy performance penalty (especially in the
3020 common case where there is a quick default constructor), this is a major
3021 savings.  The disadvantage of this extension is that you do not control
3022 when the default constructor for the return value is called: it is
3023 always called at the beginning.
3024
3025 @node Min and Max
3026 @section Minimum and Maximum Operators in C++
3027
3028 It is very convenient to have operators which return the ``minimum'' or the
3029 ``maximum'' of two arguments.  In GNU C++ (but not in GNU C),
3030
3031 @table @code
3032 @item @var{a} <? @var{b}
3033 @findex <?
3034 @cindex minimum operator
3035 is the @dfn{minimum}, returning the smaller of the numeric values
3036 @var{a} and @var{b};
3037
3038 @item @var{a} >? @var{b}
3039 @findex >?
3040 @cindex maximum operator
3041 is the @dfn{maximum}, returning the larger of the numeric values @var{a}
3042 and @var{b}.
3043 @end table
3044
3045 These operations are not primitive in ordinary C++, since you can
3046 use a macro to return the minimum of two things in C++, as in the
3047 following example.
3048
3049 @example
3050 #define MIN(X,Y) ((X) < (Y) ? : (X) : (Y))
3051 @end example
3052
3053 @noindent
3054 You might then use @w{@samp{int min = MIN (i, j);}} to set @var{min} to
3055 the minimum value of variables @var{i} and @var{j}.
3056
3057 However, side effects in @code{X} or @code{Y} may cause unintended
3058 behavior.  For example, @code{MIN (i++, j++)} will fail, incrementing
3059 the smaller counter twice.  A GNU C extension allows you to write safe
3060 macros that avoid this kind of problem (@pxref{Naming Types,,Naming an
3061 Expression's Type}).  However, writing @code{MIN} and @code{MAX} as
3062 macros also forces you to use function-call notation for a
3063 fundamental arithmetic operation.  Using GNU C++ extensions, you can
3064 write @w{@samp{int min = i <? j;}} instead.
3065
3066 Since @code{<?} and @code{>?} are built into the compiler, they properly
3067 handle expressions with side-effects;  @w{@samp{int min = i++ <? j++;}}
3068 works correctly.
3069
3070 @node Destructors and Goto
3071 @section @code{goto} and Destructors in GNU C++
3072
3073 @cindex @code{goto} in C++
3074 @cindex destructors vs @code{goto}
3075 In C++ programs, you can safely use the @code{goto} statement.  When you
3076 use it to exit a block which contains aggregates requiring destructors,
3077 the destructors will run before the @code{goto} transfers control.
3078
3079 @cindex constructors vs @code{goto}
3080 The compiler still forbids using @code{goto} to @emph{enter} a scope
3081 that requires constructors.
3082
3083 @node C++ Interface
3084 @section Declarations and Definitions in One Header
3085
3086 @cindex interface and implementation headers, C++
3087 @cindex C++ interface and implementation headers
3088 C++ object definitions can be quite complex.  In principle, your source
3089 code will need two kinds of things for each object that you use across
3090 more than one source file.  First, you need an @dfn{interface}
3091 specification, describing its structure with type declarations and
3092 function prototypes.  Second, you need the @dfn{implementation} itself.
3093 It can be tedious to maintain a separate interface description in a
3094 header file, in parallel to the actual implementation.  It is also
3095 dangerous, since separate interface and implementation definitions may
3096 not remain parallel.
3097
3098 @cindex pragmas, interface and implementation
3099 With GNU C++, you can use a single header file for both purposes.
3100
3101 @quotation
3102 @emph{Warning:} The mechanism to specify this is in transition.  For the
3103 nonce, you must use one of two @code{#pragma} commands; in a future
3104 release of GNU C++, an alternative mechanism will make these
3105 @code{#pragma} commands unnecessary.
3106 @end quotation
3107
3108 The header file contains the full definitions, but is marked with
3109 @samp{#pragma interface} in the source code.  This allows the compiler
3110 to use the header file only as an interface specification when ordinary
3111 source files incorporate it with @code{#include}.  In the single source
3112 file where the full implementation belongs, you can use either a naming
3113 convention or @samp{#pragma implementation} to indicate this alternate
3114 use of the header file.
3115
3116 @table @code
3117 @item #pragma interface
3118 @itemx #pragma interface "@var{subdir}/@var{objects}.h"
3119 @kindex #pragma interface
3120 Use this directive in @emph{header files} that define object classes, to save
3121 space in most of the object files that use those classes.  Normally,
3122 local copies of certain information (backup copies of inline member
3123 functions, debugging information, and the internal tables that implement
3124 virtual functions) must be kept in each object file that includes class
3125 definitions.  You can use this pragma to avoid such duplication.  When a
3126 header file containing @samp{#pragma interface} is included in a
3127 compilation, this auxiliary information will not be generated (unless
3128 the main input source file itself uses @samp{#pragma implementation}).
3129 Instead, the object files will contain references to be resolved at link
3130 time.
3131
3132 The second form of this directive is useful for the case where you have
3133 multiple headers with the same name in different directories.  If you
3134 use this form, you must specify the same string to @samp{#pragma
3135 implementation}.
3136
3137 @item #pragma implementation
3138 @itemx #pragma implementation "@var{objects}.h"
3139 @kindex #pragma implementation
3140 Use this pragma in a @emph{main input file}, when you want full output from
3141 included header files to be generated (and made globally visible).  The
3142 included header file, in turn, should use @samp{#pragma interface}.
3143 Backup copies of inline member functions, debugging information, and the
3144 internal tables used to implement virtual functions are all generated in
3145 implementation files.
3146
3147 @cindex implied @code{#pragma implementation}
3148 @cindex @code{#pragma implementation}, implied
3149 @cindex naming convention, implementation headers
3150 If you use @samp{#pragma implementation} with no argument, it applies to
3151 an include file with the same basename@footnote{A file's @dfn{basename}
3152 was the name stripped of all leading path information and of trailing
3153 suffixes, such as @samp{.h} or @samp{.C} or @samp{.cc}.} as your source
3154 file.  For example, in @file{allclass.cc}, giving just
3155 @samp{#pragma implementation}
3156 by itself is equivalent to @samp{#pragma implementation "allclass.h"}.
3157
3158 In versions of GNU C++ prior to 2.6.0 @file{allclass.h} was treated as
3159 an implementation file whenever you would include it from
3160 @file{allclass.cc} even if you never specified @samp{#pragma
3161 implementation}.  This was deemed to be more trouble than it was worth,
3162 however, and disabled.
3163
3164 If you use an explicit @samp{#pragma implementation}, it must appear in
3165 your source file @emph{before} you include the affected header files.
3166
3167 Use the string argument if you want a single implementation file to
3168 include code from multiple header files.  (You must also use
3169 @samp{#include} to include the header file; @samp{#pragma
3170 implementation} only specifies how to use the file---it doesn't actually
3171 include it.)
3172
3173 There is no way to split up the contents of a single header file into
3174 multiple implementation files.
3175 @end table
3176
3177 @cindex inlining and C++ pragmas
3178 @cindex C++ pragmas, effect on inlining
3179 @cindex pragmas in C++, effect on inlining
3180 @samp{#pragma implementation} and @samp{#pragma interface} also have an
3181 effect on function inlining.
3182
3183 If you define a class in a header file marked with @samp{#pragma
3184 interface}, the effect on a function defined in that class is similar to
3185 an explicit @code{extern} declaration---the compiler emits no code at
3186 all to define an independent version of the function.  Its definition
3187 is used only for inlining with its callers.
3188
3189 Conversely, when you include the same header file in a main source file
3190 that declares it as @samp{#pragma implementation}, the compiler emits
3191 code for the function itself; this defines a version of the function
3192 that can be found via pointers (or by callers compiled without
3193 inlining).  If all calls to the function can be inlined, you can avoid
3194 emitting the function by compiling with @samp{-fno-implement-inlines}.
3195 If any calls were not inlined, you will get linker errors.
3196
3197 @node Template Instantiation
3198 @section Where's the Template?
3199
3200 @cindex template instantiation
3201
3202 C++ templates are the first language feature to require more
3203 intelligence from the environment than one usually finds on a UNIX
3204 system.  Somehow the compiler and linker have to make sure that each
3205 template instance occurs exactly once in the executable if it is needed,
3206 and not at all otherwise.  There are two basic approaches to this
3207 problem, which I will refer to as the Borland model and the Cfront model.
3208
3209 @table @asis
3210 @item Borland model
3211 Borland C++ solved the template instantiation problem by adding the code
3212 equivalent of common blocks to their linker; the compiler emits template
3213 instances in each translation unit that uses them, and the linker
3214 collapses them together.  The advantage of this model is that the linker
3215 only has to consider the object files themselves; there is no external
3216 complexity to worry about.  This disadvantage is that compilation time
3217 is increased because the template code is being compiled repeatedly.
3218 Code written for this model tends to include definitions of all
3219 templates in the header file, since they must be seen to be
3220 instantiated.
3221
3222 @item Cfront model
3223 The AT&T C++ translator, Cfront, solved the template instantiation
3224 problem by creating the notion of a template repository, an
3225 automatically maintained place where template instances are stored.  A
3226 more modern version of the repository works as follows: As individual
3227 object files are built, the compiler places any template definitions and
3228 instantiations encountered in the repository.  At link time, the link
3229 wrapper adds in the objects in the repository and compiles any needed
3230 instances that were not previously emitted.  The advantages of this
3231 model are more optimal compilation speed and the ability to use the
3232 system linker; to implement the Borland model a compiler vendor also
3233 needs to replace the linker.  The disadvantages are vastly increased
3234 complexity, and thus potential for error; for some code this can be
3235 just as transparent, but in practice it can been very difficult to build
3236 multiple programs in one directory and one program in multiple
3237 directories.  Code written for this model tends to separate definitions
3238 of non-inline member templates into a separate file, which should be
3239 compiled separately.
3240 @end table
3241
3242 When used with GNU ld version 2.8 or later on an ELF system such as
3243 Linux/GNU or Solaris 2, or on Microsoft Windows, g++ supports the
3244 Borland model.  On other systems, g++ implements neither automatic
3245 model.
3246
3247 A future version of g++ will support a hybrid model whereby the compiler
3248 will emit any instantiations for which the template definition is
3249 included in the compile, and store template definitions and
3250 instantiation context information into the object file for the rest.
3251 The link wrapper will extract that information as necessary and invoke
3252 the compiler to produce the remaining instantiations.  The linker will
3253 then combine duplicate instantiations.
3254
3255 In the mean time, you have the following options for dealing with
3256 template instantiations:
3257
3258 @enumerate
3259 @item
3260 Compile your template-using code with @samp{-frepo}.  The compiler will
3261 generate files with the extension @samp{.rpo} listing all of the
3262 template instantiations used in the corresponding object files which
3263 could be instantiated there; the link wrapper, @samp{collect2}, will
3264 then update the @samp{.rpo} files to tell the compiler where to place
3265 those instantiations and rebuild any affected object files.  The
3266 link-time overhead is negligible after the first pass, as the compiler
3267 will continue to place the instantiations in the same files.
3268
3269 This is your best option for application code written for the Borland
3270 model, as it will just work.  Code written for the Cfront model will
3271 need to be modified so that the template definitions are available at
3272 one or more points of instantiation; usually this is as simple as adding
3273 @code{#include <tmethods.cc>} to the end of each template header.
3274
3275 For library code, if you want the library to provide all of the template
3276 instantiations it needs, just try to link all of its object files
3277 together; the link will fail, but cause the instantiations to be
3278 generated as a side effect.  Be warned, however, that this may cause
3279 conflicts if multiple libraries try to provide the same instantiations.
3280 For greater control, use explicit instantiation as described in the next
3281 option.
3282
3283 @item
3284 Compile your code with @samp{-fno-implicit-templates} to disable the
3285 implicit generation of template instances, and explicitly instantiate
3286 all the ones you use.  This approach requires more knowledge of exactly
3287 which instances you need than do the others, but it's less
3288 mysterious and allows greater control.  You can scatter the explicit
3289 instantiations throughout your program, perhaps putting them in the
3290 translation units where the instances are used or the translation units
3291 that define the templates themselves; you can put all of the explicit
3292 instantiations you need into one big file; or you can create small files
3293 like
3294
3295 @example
3296 #include "Foo.h"
3297 #include "Foo.cc"
3298
3299 template class Foo<int>;
3300 template ostream& operator <<
3301                 (ostream&, const Foo<int>&);
3302 @end example
3303
3304 for each of the instances you need, and create a template instantiation
3305 library from those.
3306
3307 If you are using Cfront-model code, you can probably get away with not
3308 using @samp{-fno-implicit-templates} when compiling files that don't
3309 @samp{#include} the member template definitions.
3310
3311 If you use one big file to do the instantiations, you may want to
3312 compile it without @samp{-fno-implicit-templates} so you get all of the
3313 instances required by your explicit instantiations (but not by any
3314 other files) without having to specify them as well.
3315
3316 g++ has extended the template instantiation syntax outlined in the
3317 Working Paper to allow forward declaration of explicit instantiations,
3318 explicit instantiation of members of template classes and instantiation
3319 of the compiler support data for a template class (i.e. the vtable)
3320 without instantiating any of its members:
3321
3322 @example
3323 extern template int max (int, int);
3324 template void Foo<int>::f ();
3325 inline template class Foo<int>;
3326 @end example
3327
3328 @item
3329 Do nothing.  Pretend g++ does implement automatic instantiation
3330 management.  Code written for the Borland model will work fine, but
3331 each translation unit will contain instances of each of the templates it
3332 uses.  In a large program, this can lead to an unacceptable amount of code
3333 duplication.
3334
3335 @item
3336 Add @samp{#pragma interface} to all files containing template
3337 definitions.  For each of these files, add @samp{#pragma implementation
3338 "@var{filename}"} to the top of some @samp{.C} file which
3339 @samp{#include}s it.  Then compile everything with
3340 @samp{-fexternal-templates}.  The templates will then only be expanded
3341 in the translation unit which implements them (i.e. has a @samp{#pragma
3342 implementation} line for the file where they live); all other files will
3343 use external references.  If you're lucky, everything should work
3344 properly.  If you get undefined symbol errors, you need to make sure
3345 that each template instance which is used in the program is used in the
3346 file which implements that template.  If you don't have any use for a
3347 particular instance in that file, you can just instantiate it
3348 explicitly, using the syntax from the latest C++ working paper:
3349
3350 @example
3351 template class A<int>;
3352 template ostream& operator << (ostream&, const A<int>&);
3353 @end example
3354
3355 This strategy will work with code written for either model.  If you are
3356 using code written for the Cfront model, the file containing a class
3357 template and the file containing its member templates should be
3358 implemented in the same translation unit.
3359
3360 A slight variation on this approach is to instead use the flag
3361 @samp{-falt-external-templates}; this flag causes template
3362 instances to be emitted in the translation unit that implements the
3363 header where they are first instantiated, rather than the one which
3364 implements the file where the templates are defined.  This header must
3365 be the same in all translation units, or things are likely to break.
3366
3367 @xref{C++ Interface,,Declarations and Definitions in One Header}, for
3368 more discussion of these pragmas.
3369 @end enumerate
3370
3371 @node C++ Signatures
3372 @section Type Abstraction using Signatures
3373
3374 @findex signature
3375 @cindex type abstraction, C++
3376 @cindex C++ type abstraction
3377 @cindex subtype polymorphism, C++
3378 @cindex C++ subtype polymorphism
3379 @cindex signatures, C++
3380 @cindex C++ signatures
3381
3382 In GNU C++, you can use the keyword @code{signature} to define a
3383 completely abstract class interface as a datatype.  You can connect this
3384 abstraction with actual classes using signature pointers.  If you want
3385 to use signatures, run the GNU compiler with the
3386 @samp{-fhandle-signatures} command-line option.  (With this option, the
3387 compiler reserves a second keyword @code{sigof} as well, for a future
3388 extension.)
3389
3390 Roughly, signatures are type abstractions or interfaces of classes.
3391 Some other languages have similar facilities.  C++ signatures are
3392 related to ML's signatures, Haskell's type classes, definition modules
3393 in Modula-2, interface modules in Modula-3, abstract types in Emerald,
3394 type modules in Trellis/Owl, categories in Scratchpad II, and types in
3395 POOL-I.  For a more detailed discussion of signatures, see
3396 @cite{Signatures: A Language Extension for Improving Type Abstraction and
3397 Subtype Polymorphism in C++}
3398 by @w{Gerald} Baumgartner and Vincent F. Russo (Tech report
3399 CSD--TR--95--051, Dept. of Computer Sciences, Purdue University,
3400 August 1995, a slightly improved version appeared in
3401 @emph{Software---Practice & Experience}, @b{25}(8), pp. 863--889,
3402 August 1995).  You can get the tech report by anonymous FTP from
3403 @code{ftp.cs.purdue.edu} in @file{pub/gb/Signature-design.ps.gz}.
3404
3405 Syntactically, a signature declaration is a collection of
3406 member function declarations and nested type declarations.
3407 For example, this signature declaration defines a new abstract type
3408 @code{S} with member functions @samp{int foo ()} and @samp{int bar (int)}:
3409
3410 @example
3411 signature S
3412 @{
3413   int foo ();
3414   int bar (int);
3415 @};
3416 @end example
3417
3418 Since signature types do not include implementation definitions, you
3419 cannot write an instance of a signature directly.  Instead, you can
3420 define a pointer to any class that contains the required interfaces as a
3421 @dfn{signature pointer}.  Such a class @dfn{implements} the signature
3422 type.
3423 @c Eventually signature references should work too.
3424
3425 To use a class as an implementation of @code{S}, you must ensure that
3426 the class has public member functions @samp{int foo ()} and @samp{int
3427 bar (int)}.  The class can have other member functions as well, public
3428 or not; as long as it offers what's declared in the signature, it is
3429 suitable as an implementation of that signature type.
3430
3431 For example, suppose that @code{C} is a class that meets the
3432 requirements of signature @code{S} (@code{C} @dfn{conforms to}
3433 @code{S}).  Then
3434
3435 @example
3436 C obj;
3437 S * p = &obj;
3438 @end example
3439
3440 @noindent
3441 defines a signature pointer @code{p} and initializes it to point to an
3442 object of type @code{C}.
3443 The member function call @w{@samp{int i = p->foo ();}}
3444 executes @samp{obj.foo ()}.
3445
3446 @cindex @code{signature} in C++, advantages
3447 Abstract virtual classes provide somewhat similar facilities in standard
3448 C++.  There are two main advantages to using signatures instead:
3449
3450 @enumerate
3451 @item
3452 Subtyping becomes independent from inheritance.  A class or signature
3453 type @code{T} is a subtype of a signature type @code{S} independent of
3454 any inheritance hierarchy as long as all the member functions declared
3455 in @code{S} are also found in @code{T}.  So you can define a subtype
3456 hierarchy that is completely independent from any inheritance
3457 (implementation) hierarchy, instead of being forced to use types that
3458 mirror the class inheritance hierarchy.
3459
3460 @item
3461 Signatures allow you to work with existing class hierarchies as
3462 implementations of a signature type.  If those class hierarchies are
3463 only available in compiled form, you're out of luck with abstract virtual
3464 classes, since an abstract virtual class cannot be retrofitted on top of
3465 existing class hierarchies.  So you would be required to write interface
3466 classes as subtypes of the abstract virtual class.
3467 @end enumerate
3468
3469 @cindex default implementation, signature member function
3470 @cindex signature member function default implementation
3471 There is one more detail about signatures.  A signature declaration can
3472 contain member function @emph{definitions} as well as member function
3473 declarations.  A signature member function with a full definition is
3474 called a @emph{default implementation}; classes need not contain that
3475 particular interface in order to conform.  For example, a
3476 class @code{C} can conform to the signature
3477
3478 @example
3479 signature T
3480 @{
3481   int f (int);
3482   int f0 () @{ return f (0); @};
3483 @};
3484 @end example
3485
3486 @noindent
3487 whether or not @code{C} implements the member function @samp{int f0 ()}.
3488 If you define @code{C::f0}, that definition takes precedence;
3489 otherwise, the default implementation @code{S::f0} applies.
3490
3491 @ignore
3492 There will be more support for signatures in the future.
3493 Add to this doc as the implementation grows.
3494 In particular, the following features are planned but not yet
3495 implemented:
3496 @itemize @bullet
3497 @item signature references,
3498 @item signature inheritance,
3499 @item the @code{sigof} construct for extracting the signature information
3500       of a class,
3501 @item views for renaming member functions when matching a class type
3502       with a signature type,
3503 @item specifying exceptions with signature member functions, and
3504 @item signature templates.
3505 @end itemize
3506 This list is roughly in the order in which we intend to implement
3507 them.  Watch this space for updates.
3508 @end ignore