OSDN Git Service

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