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