1 @c Copyright (C) 1988,89,92,93,94,96 Free Software Foundation, Inc.
2 @c This is part of the GCC manual.
3 @c For copying conditions, see the file gcc.texi.
6 @chapter Extensions to the C Language Family
7 @cindex extensions, C language
8 @cindex C language extensions
10 GNU C provides several language features not found in ANSI standard C.
11 (The @samp{-pedantic} option directs GNU CC to print a warning message if
12 any of these features is used.) To test for the availability of these
13 features in conditional compilation, check for a predefined macro
14 @code{__GNUC__}, which is always defined under GNU CC.
16 These extensions are available in C and Objective C. Most of them are
17 also available in C++. @xref{C++ Extensions,,Extensions to the
18 C++ Language}, for extensions that apply @emph{only} to C++.
20 @c The only difference between the two versions of this menu is that the
21 @c version for clear INTERNALS has an extra node, "Constraints" (which
22 @c appears in a separate chapter in the other version of the manual).
25 * Statement Exprs:: Putting statements and declarations inside expressions.
26 * Local Labels:: Labels local to a statement-expression.
27 * Labels as Values:: Getting pointers to labels, and computed gotos.
28 * Nested Functions:: As in Algol and Pascal, lexical scoping of functions.
29 * Constructing Calls:: Dispatching a call to another function.
30 * Naming Types:: Giving a name to the type of some expression.
31 * Typeof:: @code{typeof}: referring to the type of an expression.
32 * Lvalues:: Using @samp{?:}, @samp{,} and casts in lvalues.
33 * Conditionals:: Omitting the middle operand of a @samp{?:} expression.
34 * Long Long:: Double-word integers---@code{long long int}.
35 * Complex:: Data types for complex numbers.
36 * Zero Length:: Zero-length arrays.
37 * Variable Length:: Arrays whose length is computed at run time.
38 * Macro Varargs:: Macros with variable number of arguments.
39 * Subscripting:: Any array can be subscripted, even if not an lvalue.
40 * Pointer Arith:: Arithmetic on @code{void}-pointers and function pointers.
41 * Initializers:: Non-constant initializers.
42 * Constructors:: Constructor expressions give structures, unions
44 * Labeled Elements:: Labeling elements of initializers.
45 * Cast to Union:: Casting to union type from any member of the union.
46 * Case Ranges:: `case 1 ... 9' and such.
47 * Function Attributes:: Declaring that functions have no side effects,
48 or that they can never return.
49 * Function Prototypes:: Prototype declarations and old-style definitions.
50 * C++ Comments:: C++ comments are recognized.
51 * Dollar Signs:: Dollar sign is allowed in identifiers.
52 * Character Escapes:: @samp{\e} stands for the character @key{ESC}.
53 * Variable Attributes:: Specifying attributes of variables.
54 * Type Attributes:: Specifying attributes of types.
55 * Alignment:: Inquiring about the alignment of a type or variable.
56 * Inline:: Defining inline functions (as fast as macros).
57 * Extended Asm:: Assembler instructions with C expressions as operands.
58 (With them you can define ``built-in'' functions.)
59 * Asm Labels:: Specifying the assembler name to use for a C symbol.
60 * Explicit Reg Vars:: Defining variables residing in specified registers.
61 * Alternate Keywords:: @code{__const__}, @code{__asm__}, etc., for header files.
62 * Incomplete Enums:: @code{enum foo;}, with details to follow.
63 * Function Names:: Printable strings which are the name of the current
65 * Return Address:: Getting the return or frame address of a function.
70 * Statement Exprs:: Putting statements and declarations inside expressions.
71 * Local Labels:: Labels local to a statement-expression.
72 * Labels as Values:: Getting pointers to labels, and computed gotos.
73 * Nested Functions:: As in Algol and Pascal, lexical scoping of functions.
74 * Constructing Calls:: Dispatching a call to another function.
75 * Naming Types:: Giving a name to the type of some expression.
76 * Typeof:: @code{typeof}: referring to the type of an expression.
77 * Lvalues:: Using @samp{?:}, @samp{,} and casts in lvalues.
78 * Conditionals:: Omitting the middle operand of a @samp{?:} expression.
79 * Long Long:: Double-word integers---@code{long long int}.
80 * Complex:: Data types for complex numbers.
81 * Zero Length:: Zero-length arrays.
82 * Variable Length:: Arrays whose length is computed at run time.
83 * Macro Varargs:: Macros with variable number of arguments.
84 * Subscripting:: Any array can be subscripted, even if not an lvalue.
85 * Pointer Arith:: Arithmetic on @code{void}-pointers and function pointers.
86 * Initializers:: Non-constant initializers.
87 * Constructors:: Constructor expressions give structures, unions
89 * Labeled Elements:: Labeling elements of initializers.
90 * Cast to Union:: Casting to union type from any member of the union.
91 * Case Ranges:: `case 1 ... 9' and such.
92 * Function Attributes:: Declaring that functions have no side effects,
93 or that they can never return.
94 * Function Prototypes:: Prototype declarations and old-style definitions.
95 * C++ Comments:: C++ comments are recognized.
96 * Dollar Signs:: Dollar sign is allowed in identifiers.
97 * Character Escapes:: @samp{\e} stands for the character @key{ESC}.
98 * Variable Attributes:: Specifying attributes of variables.
99 * Type Attributes:: Specifying attributes of types.
100 * Alignment:: Inquiring about the alignment of a type or variable.
101 * Inline:: Defining inline functions (as fast as macros).
102 * Extended Asm:: Assembler instructions with C expressions as operands.
103 (With them you can define ``built-in'' functions.)
104 * Constraints:: Constraints for asm operands
105 * Asm Labels:: Specifying the assembler name to use for a C symbol.
106 * Explicit Reg Vars:: Defining variables residing in specified registers.
107 * Alternate Keywords:: @code{__const__}, @code{__asm__}, etc., for header files.
108 * Incomplete Enums:: @code{enum foo;}, with details to follow.
109 * Function Names:: Printable strings which are the name of the current
111 * Return Address:: Getting the return or frame address of a function.
115 @node Statement Exprs
116 @section Statements and Declarations in Expressions
117 @cindex statements inside expressions
118 @cindex declarations inside expressions
119 @cindex expressions containing statements
120 @cindex macros, statements in expressions
122 @c the above section title wrapped and causes an underfull hbox.. i
123 @c changed it from "within" to "in". --mew 4feb93
125 A compound statement enclosed in parentheses may appear as an expression
126 in GNU C. This allows you to use loops, switches, and local variables
127 within an expression.
129 Recall that a compound statement is a sequence of statements surrounded
130 by braces; in this construct, parentheses go around the braces. For
134 (@{ int y = foo (); int z;
141 is a valid (though slightly more complex than necessary) expression
142 for the absolute value of @code{foo ()}.
144 The last thing in the compound statement should be an expression
145 followed by a semicolon; the value of this subexpression serves as the
146 value of the entire construct. (If you use some other kind of statement
147 last within the braces, the construct has type @code{void}, and thus
148 effectively no value.)
150 This feature is especially useful in making macro definitions ``safe'' (so
151 that they evaluate each operand exactly once). For example, the
152 ``maximum'' function is commonly defined as a macro in standard C as
156 #define max(a,b) ((a) > (b) ? (a) : (b))
160 @cindex side effects, macro argument
161 But this definition computes either @var{a} or @var{b} twice, with bad
162 results if the operand has side effects. In GNU C, if you know the
163 type of the operands (here let's assume @code{int}), you can define
164 the macro safely as follows:
167 #define maxint(a,b) \
168 (@{int _a = (a), _b = (b); _a > _b ? _a : _b; @})
171 Embedded statements are not allowed in constant expressions, such as
172 the value of an enumeration constant, the width of a bit field, or
173 the initial value of a static variable.
175 If you don't know the type of the operand, you can still do this, but you
176 must use @code{typeof} (@pxref{Typeof}) or type naming (@pxref{Naming
180 @section Locally Declared Labels
182 @cindex macros, local labels
184 Each statement expression is a scope in which @dfn{local labels} can be
185 declared. A local label is simply an identifier; you can jump to it
186 with an ordinary @code{goto} statement, but only from within the
187 statement expression it belongs to.
189 A local label declaration looks like this:
192 __label__ @var{label};
199 __label__ @var{label1}, @var{label2}, @dots{};
202 Local label declarations must come at the beginning of the statement
203 expression, right after the @samp{(@{}, before any ordinary
206 The label declaration defines the label @emph{name}, but does not define
207 the label itself. You must do this in the usual way, with
208 @code{@var{label}:}, within the statements of the statement expression.
210 The local label feature is useful because statement expressions are
211 often used in macros. If the macro contains nested loops, a @code{goto}
212 can be useful for breaking out of them. However, an ordinary label
213 whose scope is the whole function cannot be used: if the macro can be
214 expanded several times in one function, the label will be multiply
215 defined in that function. A local label avoids this problem. For
219 #define SEARCH(array, target) \
222 typeof (target) _SEARCH_target = (target); \
223 typeof (*(array)) *_SEARCH_array = (array); \
226 for (i = 0; i < max; i++) \
227 for (j = 0; j < max; j++) \
228 if (_SEARCH_array[i][j] == _SEARCH_target) \
229 @{ value = i; goto found; @} \
236 @node Labels as Values
237 @section Labels as Values
238 @cindex labels as values
239 @cindex computed gotos
240 @cindex goto with computed label
241 @cindex address of a label
243 You can get the address of a label defined in the current function
244 (or a containing function) with the unary operator @samp{&&}. The
245 value has type @code{void *}. This value is a constant and can be used
246 wherever a constant of that type is valid. For example:
254 To use these values, you need to be able to jump to one. This is done
255 with the computed goto statement@footnote{The analogous feature in
256 Fortran is called an assigned goto, but that name seems inappropriate in
257 C, where one can do more than simply store label addresses in label
258 variables.}, @code{goto *@var{exp};}. For example,
265 Any expression of type @code{void *} is allowed.
267 One way of using these constants is in initializing a static array that
268 will serve as a jump table:
271 static void *array[] = @{ &&foo, &&bar, &&hack @};
274 Then you can select a label with indexing, like this:
281 Note that this does not check whether the subscript is in bounds---array
282 indexing in C never does that.
284 Such an array of label values serves a purpose much like that of the
285 @code{switch} statement. The @code{switch} statement is cleaner, so
286 use that rather than an array unless the problem does not fit a
287 @code{switch} statement very well.
289 Another use of label values is in an interpreter for threaded code.
290 The labels within the interpreter function can be stored in the
291 threaded code for super-fast dispatching.
293 You can use this mechanism to jump to code in a different function. If
294 you do that, totally unpredictable things will happen. The best way to
295 avoid this is to store the label address only in automatic variables and
296 never pass it as an argument.
298 @node Nested Functions
299 @section Nested Functions
300 @cindex nested functions
301 @cindex downward funargs
304 A @dfn{nested function} is a function defined inside another function.
305 (Nested functions are not supported for GNU C++.) The nested function's
306 name is local to the block where it is defined. For example, here we
307 define a nested function named @code{square}, and call it twice:
311 foo (double a, double b)
313 double square (double z) @{ return z * z; @}
315 return square (a) + square (b);
320 The nested function can access all the variables of the containing
321 function that are visible at the point of its definition. This is
322 called @dfn{lexical scoping}. For example, here we show a nested
323 function which uses an inherited variable named @code{offset}:
326 bar (int *array, int offset, int size)
328 int access (int *array, int index)
329 @{ return array[index + offset]; @}
332 for (i = 0; i < size; i++)
333 @dots{} access (array, i) @dots{}
337 Nested function definitions are permitted within functions in the places
338 where variable definitions are allowed; that is, in any block, before
339 the first statement in the block.
341 It is possible to call the nested function from outside the scope of its
342 name by storing its address or passing the address to another function:
345 hack (int *array, int size)
347 void store (int index, int value)
348 @{ array[index] = value; @}
350 intermediate (store, size);
354 Here, the function @code{intermediate} receives the address of
355 @code{store} as an argument. If @code{intermediate} calls @code{store},
356 the arguments given to @code{store} are used to store into @code{array}.
357 But this technique works only so long as the containing function
358 (@code{hack}, in this example) does not exit.
360 If you try to call the nested function through its address after the
361 containing function has exited, all hell will break loose. If you try
362 to call it after a containing scope level has exited, and if it refers
363 to some of the variables that are no longer in scope, you may be lucky,
364 but it's not wise to take the risk. If, however, the nested function
365 does not refer to anything that has gone out of scope, you should be
368 GNU CC implements taking the address of a nested function using a
369 technique called @dfn{trampolines}. A paper describing them is
370 available from @samp{maya.idiap.ch} in directory @file{pub/tmb},
371 file @file{usenix88-lexic.ps.Z}.
373 A nested function can jump to a label inherited from a containing
374 function, provided the label was explicitly declared in the containing
375 function (@pxref{Local Labels}). Such a jump returns instantly to the
376 containing function, exiting the nested function which did the
377 @code{goto} and any intermediate functions as well. Here is an example:
381 bar (int *array, int offset, int size)
384 int access (int *array, int index)
388 return array[index + offset];
392 for (i = 0; i < size; i++)
393 @dots{} access (array, i) @dots{}
397 /* @r{Control comes here from @code{access}
398 if it detects an error.} */
405 A nested function always has internal linkage. Declaring one with
406 @code{extern} is erroneous. If you need to declare the nested function
407 before its definition, use @code{auto} (which is otherwise meaningless
408 for function declarations).
411 bar (int *array, int offset, int size)
414 auto int access (int *, int);
416 int access (int *array, int index)
420 return array[index + offset];
426 @node Constructing Calls
427 @section Constructing Function Calls
428 @cindex constructing calls
429 @cindex forwarding calls
431 Using the built-in functions described below, you can record
432 the arguments a function received, and call another function
433 with the same arguments, without knowing the number or types
436 You can also record the return value of that function call,
437 and later return that value, without knowing what data type
438 the function tried to return (as long as your caller expects
442 @findex __builtin_apply_args
443 @item __builtin_apply_args ()
444 This built-in function returns a pointer of type @code{void *} to data
445 describing how to perform a call with the same arguments as were passed
446 to the current function.
448 The function saves the arg pointer register, structure value address,
449 and all registers that might be used to pass arguments to a function
450 into a block of memory allocated on the stack. Then it returns the
451 address of that block.
453 @findex __builtin_apply
454 @item __builtin_apply (@var{function}, @var{arguments}, @var{size})
455 This built-in function invokes @var{function} (type @code{void (*)()})
456 with a copy of the parameters described by @var{arguments} (type
457 @code{void *}) and @var{size} (type @code{int}).
459 The value of @var{arguments} should be the value returned by
460 @code{__builtin_apply_args}. The argument @var{size} specifies the size
461 of the stack argument data, in bytes.
463 This function returns a pointer of type @code{void *} to data describing
464 how to return whatever value was returned by @var{function}. The data
465 is saved in a block of memory allocated on the stack.
467 It is not always simple to compute the proper value for @var{size}. The
468 value is used by @code{__builtin_apply} to compute the amount of data
469 that should be pushed on the stack and copied from the incoming argument
472 @findex __builtin_return
473 @item __builtin_return (@var{result})
474 This built-in function returns the value described by @var{result} from
475 the containing function. You should specify, for @var{result}, a value
476 returned by @code{__builtin_apply}.
480 @section Naming an Expression's Type
483 You can give a name to the type of an expression using a @code{typedef}
484 declaration with an initializer. Here is how to define @var{name} as a
485 type name for the type of @var{exp}:
488 typedef @var{name} = @var{exp};
491 This is useful in conjunction with the statements-within-expressions
492 feature. Here is how the two together can be used to define a safe
493 ``maximum'' macro that operates on any arithmetic type:
497 (@{typedef _ta = (a), _tb = (b); \
498 _ta _a = (a); _tb _b = (b); \
499 _a > _b ? _a : _b; @})
502 @cindex underscores in variables in macros
503 @cindex @samp{_} in variables in macros
504 @cindex local variables in macros
505 @cindex variables, local, in macros
506 @cindex macros, local variables in
508 The reason for using names that start with underscores for the local
509 variables is to avoid conflicts with variable names that occur within the
510 expressions that are substituted for @code{a} and @code{b}. Eventually we
511 hope to design a new form of declaration syntax that allows you to declare
512 variables whose scopes start only after their initializers; this will be a
513 more reliable way to prevent such conflicts.
516 @section Referring to a Type with @code{typeof}
519 @cindex macros, types of arguments
521 Another way to refer to the type of an expression is with @code{typeof}.
522 The syntax of using of this keyword looks like @code{sizeof}, but the
523 construct acts semantically like a type name defined with @code{typedef}.
525 There are two ways of writing the argument to @code{typeof}: with an
526 expression or with a type. Here is an example with an expression:
533 This assumes that @code{x} is an array of functions; the type described
534 is that of the values of the functions.
536 Here is an example with a typename as the argument:
543 Here the type described is that of pointers to @code{int}.
545 If you are writing a header file that must work when included in ANSI C
546 programs, write @code{__typeof__} instead of @code{typeof}.
547 @xref{Alternate Keywords}.
549 A @code{typeof}-construct can be used anywhere a typedef name could be
550 used. For example, you can use it in a declaration, in a cast, or inside
551 of @code{sizeof} or @code{typeof}.
555 This declares @code{y} with the type of what @code{x} points to.
562 This declares @code{y} as an array of such values.
569 This declares @code{y} as an array of pointers to characters:
572 typeof (typeof (char *)[4]) y;
576 It is equivalent to the following traditional C declaration:
582 To see the meaning of the declaration using @code{typeof}, and why it
583 might be a useful way to write, let's rewrite it with these macros:
586 #define pointer(T) typeof(T *)
587 #define array(T, N) typeof(T [N])
591 Now the declaration can be rewritten this way:
594 array (pointer (char), 4) y;
598 Thus, @code{array (pointer (char), 4)} is the type of arrays of 4
599 pointers to @code{char}.
603 @section Generalized Lvalues
604 @cindex compound expressions as lvalues
605 @cindex expressions, compound, as lvalues
606 @cindex conditional expressions as lvalues
607 @cindex expressions, conditional, as lvalues
608 @cindex casts as lvalues
609 @cindex generalized lvalues
610 @cindex lvalues, generalized
611 @cindex extensions, @code{?:}
612 @cindex @code{?:} extensions
613 Compound expressions, conditional expressions and casts are allowed as
614 lvalues provided their operands are lvalues. This means that you can take
615 their addresses or store values into them.
617 Standard C++ allows compound expressions and conditional expressions as
618 lvalues, and permits casts to reference type, so use of this extension
619 is deprecated for C++ code.
621 For example, a compound expression can be assigned, provided the last
622 expression in the sequence is an lvalue. These two expressions are
630 Similarly, the address of the compound expression can be taken. These two
631 expressions are equivalent:
638 A conditional expression is a valid lvalue if its type is not void and the
639 true and false branches are both valid lvalues. For example, these two
640 expressions are equivalent:
644 (a ? b = 5 : (c = 5))
647 A cast is a valid lvalue if its operand is an lvalue. A simple
648 assignment whose left-hand side is a cast works by converting the
649 right-hand side first to the specified type, then to the type of the
650 inner left-hand side expression. After this is stored, the value is
651 converted back to the specified type to become the value of the
652 assignment. Thus, if @code{a} has type @code{char *}, the following two
653 expressions are equivalent:
657 (int)(a = (char *)(int)5)
660 An assignment-with-arithmetic operation such as @samp{+=} applied to a cast
661 performs the arithmetic using the type resulting from the cast, and then
662 continues as in the previous case. Therefore, these two expressions are
667 (int)(a = (char *)(int) ((int)a + 5))
670 You cannot take the address of an lvalue cast, because the use of its
671 address would not work out coherently. Suppose that @code{&(int)f} were
672 permitted, where @code{f} has type @code{float}. Then the following
673 statement would try to store an integer bit-pattern where a floating
674 point number belongs:
680 This is quite different from what @code{(int)f = 1} would do---that
681 would convert 1 to floating point and store it. Rather than cause this
682 inconsistency, we think it is better to prohibit use of @samp{&} on a cast.
684 If you really do want an @code{int *} pointer with the address of
685 @code{f}, you can simply write @code{(int *)&f}.
688 @section Conditionals with Omitted Operands
689 @cindex conditional expressions, extensions
690 @cindex omitted middle-operands
691 @cindex middle-operands, omitted
692 @cindex extensions, @code{?:}
693 @cindex @code{?:} extensions
695 The middle operand in a conditional expression may be omitted. Then
696 if the first operand is nonzero, its value is the value of the conditional
699 Therefore, the expression
706 has the value of @code{x} if that is nonzero; otherwise, the value of
709 This example is perfectly equivalent to
715 @cindex side effect in ?:
716 @cindex ?: side effect
718 In this simple case, the ability to omit the middle operand is not
719 especially useful. When it becomes useful is when the first operand does,
720 or may (if it is a macro argument), contain a side effect. Then repeating
721 the operand in the middle would perform the side effect twice. Omitting
722 the middle operand uses the value already computed without the undesirable
723 effects of recomputing it.
726 @section Double-Word Integers
727 @cindex @code{long long} data types
728 @cindex double-word arithmetic
729 @cindex multiprecision arithmetic
731 GNU C supports data types for integers that are twice as long as
732 @code{int}. Simply write @code{long long int} for a signed integer, or
733 @code{unsigned long long int} for an unsigned integer. To make an
734 integer constant of type @code{long long int}, add the suffix @code{LL}
735 to the integer. To make an integer constant of type @code{unsigned long
736 long int}, add the suffix @code{ULL} to the integer.
738 You can use these types in arithmetic like any other integer types.
739 Addition, subtraction, and bitwise boolean operations on these types
740 are open-coded on all types of machines. Multiplication is open-coded
741 if the machine supports fullword-to-doubleword a widening multiply
742 instruction. Division and shifts are open-coded only on machines that
743 provide special support. The operations that are not open-coded use
744 special library routines that come with GNU CC.
746 There may be pitfalls when you use @code{long long} types for function
747 arguments, unless you declare function prototypes. If a function
748 expects type @code{int} for its argument, and you pass a value of type
749 @code{long long int}, confusion will result because the caller and the
750 subroutine will disagree about the number of bytes for the argument.
751 Likewise, if the function expects @code{long long int} and you pass
752 @code{int}. The best way to avoid such problems is to use prototypes.
755 @section Complex Numbers
756 @cindex complex numbers
758 GNU C supports complex data types. You can declare both complex integer
759 types and complex floating types, using the keyword @code{__complex__}.
761 For example, @samp{__complex__ double x;} declares @code{x} as a
762 variable whose real part and imaginary part are both of type
763 @code{double}. @samp{__complex__ short int y;} declares @code{y} to
764 have real and imaginary parts of type @code{short int}; this is not
765 likely to be useful, but it shows that the set of complex types is
768 To write a constant with a complex data type, use the suffix @samp{i} or
769 @samp{j} (either one; they are equivalent). For example, @code{2.5fi}
770 has type @code{__complex__ float} and @code{3i} has type
771 @code{__complex__ int}. Such a constant always has a pure imaginary
772 value, but you can form any complex value you like by adding one to a
775 To extract the real part of a complex-valued expression @var{exp}, write
776 @code{__real__ @var{exp}}. Likewise, use @code{__imag__} to
777 extract the imaginary part.
779 The operator @samp{~} performs complex conjugation when used on a value
782 GNU CC can allocate complex automatic variables in a noncontiguous
783 fashion; it's even possible for the real part to be in a register while
784 the imaginary part is on the stack (or vice-versa). None of the
785 supported debugging info formats has a way to represent noncontiguous
786 allocation like this, so GNU CC describes a noncontiguous complex
787 variable as if it were two separate variables of noncomplex type.
788 If the variable's actual name is @code{foo}, the two fictitious
789 variables are named @code{foo$real} and @code{foo$imag}. You can
790 examine and set these two fictitious variables with your debugger.
792 A future version of GDB will know how to recognize such pairs and treat
793 them as a single variable with a complex type.
796 @section Arrays of Length Zero
797 @cindex arrays of length zero
798 @cindex zero-length arrays
799 @cindex length-zero arrays
801 Zero-length arrays are allowed in GNU C. They are very useful as the last
802 element of a structure which is really a header for a variable-length
812 struct line *thisline = (struct line *)
813 malloc (sizeof (struct line) + this_length);
814 thisline->length = this_length;
818 In standard C, you would have to give @code{contents} a length of 1, which
819 means either you waste space or complicate the argument to @code{malloc}.
821 @node Variable Length
822 @section Arrays of Variable Length
823 @cindex variable-length arrays
824 @cindex arrays of variable length
826 Variable-length automatic arrays are allowed in GNU C. These arrays are
827 declared like any other automatic arrays, but with a length that is not
828 a constant expression. The storage is allocated at the point of
829 declaration and deallocated when the brace-level is exited. For
834 concat_fopen (char *s1, char *s2, char *mode)
836 char str[strlen (s1) + strlen (s2) + 1];
839 return fopen (str, mode);
843 @cindex scope of a variable length array
844 @cindex variable-length array scope
845 @cindex deallocating variable length arrays
846 Jumping or breaking out of the scope of the array name deallocates the
847 storage. Jumping into the scope is not allowed; you get an error
850 @cindex @code{alloca} vs variable-length arrays
851 You can use the function @code{alloca} to get an effect much like
852 variable-length arrays. The function @code{alloca} is available in
853 many other C implementations (but not in all). On the other hand,
854 variable-length arrays are more elegant.
856 There are other differences between these two methods. Space allocated
857 with @code{alloca} exists until the containing @emph{function} returns.
858 The space for a variable-length array is deallocated as soon as the array
859 name's scope ends. (If you use both variable-length arrays and
860 @code{alloca} in the same function, deallocation of a variable-length array
861 will also deallocate anything more recently allocated with @code{alloca}.)
863 You can also use variable-length arrays as arguments to functions:
867 tester (int len, char data[len][len])
873 The length of an array is computed once when the storage is allocated
874 and is remembered for the scope of the array in case you access it with
877 If you want to pass the array first and the length afterward, you can
878 use a forward declaration in the parameter list---another GNU extension.
882 tester (int len; char data[len][len], int len)
888 @cindex parameter forward declaration
889 The @samp{int len} before the semicolon is a @dfn{parameter forward
890 declaration}, and it serves the purpose of making the name @code{len}
891 known when the declaration of @code{data} is parsed.
893 You can write any number of such parameter forward declarations in the
894 parameter list. They can be separated by commas or semicolons, but the
895 last one must end with a semicolon, which is followed by the ``real''
896 parameter declarations. Each forward declaration must match a ``real''
897 declaration in parameter name and data type.
900 @section Macros with Variable Numbers of Arguments
901 @cindex variable number of arguments
902 @cindex macro with variable arguments
903 @cindex rest argument (in macro)
905 In GNU C, a macro can accept a variable number of arguments, much as a
906 function can. The syntax for defining the macro looks much like that
907 used for a function. Here is an example:
910 #define eprintf(format, args...) \
911 fprintf (stderr, format , ## args)
914 Here @code{args} is a @dfn{rest argument}: it takes in zero or more
915 arguments, as many as the call contains. All of them plus the commas
916 between them form the value of @code{args}, which is substituted into
917 the macro body where @code{args} is used. Thus, we have this expansion:
920 eprintf ("%s:%d: ", input_file_name, line_number)
922 fprintf (stderr, "%s:%d: " , input_file_name, line_number)
926 Note that the comma after the string constant comes from the definition
927 of @code{eprintf}, whereas the last comma comes from the value of
930 The reason for using @samp{##} is to handle the case when @code{args}
931 matches no arguments at all. In this case, @code{args} has an empty
932 value. In this case, the second comma in the definition becomes an
933 embarrassment: if it got through to the expansion of the macro, we would
934 get something like this:
937 fprintf (stderr, "success!\n" , )
941 which is invalid C syntax. @samp{##} gets rid of the comma, so we get
942 the following instead:
945 fprintf (stderr, "success!\n")
948 This is a special feature of the GNU C preprocessor: @samp{##} before a
949 rest argument that is empty discards the preceding sequence of
950 non-whitespace characters from the macro definition. (If another macro
951 argument precedes, none of it is discarded.)
953 It might be better to discard the last preprocessor token instead of the
954 last preceding sequence of non-whitespace characters; in fact, we may
955 someday change this feature to do so. We advise you to write the macro
956 definition so that the preceding sequence of non-whitespace characters
957 is just a single token, so that the meaning will not change if we change
958 the definition of this feature.
961 @section Non-Lvalue Arrays May Have Subscripts
963 @cindex arrays, non-lvalue
965 @cindex subscripting and function values
966 Subscripting is allowed on arrays that are not lvalues, even though the
967 unary @samp{&} operator is not. For example, this is valid in GNU C though
968 not valid in other C dialects:
972 struct foo @{int a[4];@};
984 @section Arithmetic on @code{void}- and Function-Pointers
985 @cindex void pointers, arithmetic
986 @cindex void, size of pointer to
987 @cindex function pointers, arithmetic
988 @cindex function, size of pointer to
990 In GNU C, addition and subtraction operations are supported on pointers to
991 @code{void} and on pointers to functions. This is done by treating the
992 size of a @code{void} or of a function as 1.
994 A consequence of this is that @code{sizeof} is also allowed on @code{void}
995 and on function types, and returns 1.
997 The option @samp{-Wpointer-arith} requests a warning if these extensions
1001 @section Non-Constant Initializers
1002 @cindex initializers, non-constant
1003 @cindex non-constant initializers
1005 As in standard C++, the elements of an aggregate initializer for an
1006 automatic variable are not required to be constant expressions in GNU C.
1007 Here is an example of an initializer with run-time varying elements:
1010 foo (float f, float g)
1012 float beat_freqs[2] = @{ f-g, f+g @};
1018 @section Constructor Expressions
1019 @cindex constructor expressions
1020 @cindex initializations in expressions
1021 @cindex structures, constructor expression
1022 @cindex expressions, constructor
1024 GNU C supports constructor expressions. A constructor looks like
1025 a cast containing an initializer. Its value is an object of the
1026 type specified in the cast, containing the elements specified in
1029 Usually, the specified type is a structure. Assume that
1030 @code{struct foo} and @code{structure} are declared as shown:
1033 struct foo @{int a; char b[2];@} structure;
1037 Here is an example of constructing a @code{struct foo} with a constructor:
1040 structure = ((struct foo) @{x + y, 'a', 0@});
1044 This is equivalent to writing the following:
1048 struct foo temp = @{x + y, 'a', 0@};
1053 You can also construct an array. If all the elements of the constructor
1054 are (made up of) simple constant expressions, suitable for use in
1055 initializers, then the constructor is an lvalue and can be coerced to a
1056 pointer to its first element, as shown here:
1059 char **foo = (char *[]) @{ "x", "y", "z" @};
1062 Array constructors whose elements are not simple constants are
1063 not very useful, because the constructor is not an lvalue. There
1064 are only two valid ways to use it: to subscript it, or initialize
1065 an array variable with it. The former is probably slower than a
1066 @code{switch} statement, while the latter does the same thing an
1067 ordinary C initializer would do. Here is an example of
1068 subscripting an array constructor:
1071 output = ((int[]) @{ 2, x, 28 @}) [input];
1074 Constructor expressions for scalar types and union types are is
1075 also allowed, but then the constructor expression is equivalent
1078 @node Labeled Elements
1079 @section Labeled Elements in Initializers
1080 @cindex initializers with labeled elements
1081 @cindex labeled elements in initializers
1082 @cindex case labels in initializers
1084 Standard C requires the elements of an initializer to appear in a fixed
1085 order, the same as the order of the elements in the array or structure
1088 In GNU C you can give the elements in any order, specifying the array
1089 indices or structure field names they apply to. This extension is not
1090 implemented in GNU C++.
1092 To specify an array index, write @samp{[@var{index}]} or
1093 @samp{[@var{index}] =} before the element value. For example,
1096 int a[6] = @{ [4] 29, [2] = 15 @};
1103 int a[6] = @{ 0, 0, 15, 0, 29, 0 @};
1107 The index values must be constant expressions, even if the array being
1108 initialized is automatic.
1110 To initialize a range of elements to the same value, write
1111 @samp{[@var{first} ... @var{last}] = @var{value}}. For example,
1114 int widths[] = @{ [0 ... 9] = 1, [10 ... 99] = 2, [100] = 3 @};
1118 Note that the length of the array is the highest value specified
1121 In a structure initializer, specify the name of a field to initialize
1122 with @samp{@var{fieldname}:} before the element value. For example,
1123 given the following structure,
1126 struct point @{ int x, y; @};
1130 the following initialization
1133 struct point p = @{ y: yvalue, x: xvalue @};
1140 struct point p = @{ xvalue, yvalue @};
1143 Another syntax which has the same meaning is @samp{.@var{fieldname} =}.,
1147 struct point p = @{ .y = yvalue, .x = xvalue @};
1150 You can also use an element label (with either the colon syntax or the
1151 period-equal syntax) when initializing a union, to specify which element
1152 of the union should be used. For example,
1155 union foo @{ int i; double d; @};
1157 union foo f = @{ d: 4 @};
1161 will convert 4 to a @code{double} to store it in the union using
1162 the second element. By contrast, casting 4 to type @code{union foo}
1163 would store it into the union as the integer @code{i}, since it is
1164 an integer. (@xref{Cast to Union}.)
1166 You can combine this technique of naming elements with ordinary C
1167 initialization of successive elements. Each initializer element that
1168 does not have a label applies to the next consecutive element of the
1169 array or structure. For example,
1172 int a[6] = @{ [1] = v1, v2, [4] = v4 @};
1179 int a[6] = @{ 0, v1, v2, 0, v4, 0 @};
1182 Labeling the elements of an array initializer is especially useful
1183 when the indices are characters or belong to an @code{enum} type.
1188 = @{ [' '] = 1, ['\t'] = 1, ['\h'] = 1,
1189 ['\f'] = 1, ['\n'] = 1, ['\r'] = 1 @};
1193 @section Case Ranges
1195 @cindex ranges in case statements
1197 You can specify a range of consecutive values in a single @code{case} label,
1201 case @var{low} ... @var{high}:
1205 This has the same effect as the proper number of individual @code{case}
1206 labels, one for each integer value from @var{low} to @var{high}, inclusive.
1208 This feature is especially useful for ranges of ASCII character codes:
1214 @strong{Be careful:} Write spaces around the @code{...}, for otherwise
1215 it may be parsed wrong when you use it with integer values. For example,
1230 @section Cast to a Union Type
1231 @cindex cast to a union
1232 @cindex union, casting to a
1234 A cast to union type is similar to other casts, except that the type
1235 specified is a union type. You can specify the type either with
1236 @code{union @var{tag}} or with a typedef name. A cast to union is actually
1237 a constructor though, not a cast, and hence does not yield an lvalue like
1238 normal casts. (@xref{Constructors}.)
1240 The types that may be cast to the union type are those of the members
1241 of the union. Thus, given the following union and variables:
1244 union foo @{ int i; double d; @};
1250 both @code{x} and @code{y} can be cast to type @code{union} foo.
1252 Using the cast as the right-hand side of an assignment to a variable of
1253 union type is equivalent to storing in a member of the union:
1258 u = (union foo) x @equiv{} u.i = x
1259 u = (union foo) y @equiv{} u.d = y
1262 You can also use the union cast as a function argument:
1265 void hack (union foo);
1267 hack ((union foo) x);
1270 @node Function Attributes
1271 @section Declaring Attributes of Functions
1272 @cindex function attributes
1273 @cindex declaring attributes of functions
1274 @cindex functions that never return
1275 @cindex functions that have no side effects
1276 @cindex functions in arbitrary sections
1277 @cindex @code{volatile} applied to function
1278 @cindex @code{const} applied to function
1279 @cindex functions with @code{printf} or @code{scanf} style arguments
1280 @cindex functions that are passed arguments in registers on the 386
1281 @cindex functions that pop the argument stack on the 386
1282 @cindex functions that do not pop the argument stack on the 386
1284 In GNU C, you declare certain things about functions called in your program
1285 which help the compiler optimize function calls and check your code more
1288 The keyword @code{__attribute__} allows you to specify special
1289 attributes when making a declaration. This keyword is followed by an
1290 attribute specification inside double parentheses. Eight attributes,
1291 @code{noreturn}, @code{const}, @code{format}, @code{section},
1292 @code{constructor}, @code{destructor}, @code{unused} and @code{weak} are
1293 currently defined for functions. Other attributes, including
1294 @code{section} are supported for variables declarations (@pxref{Variable
1295 Attributes}) and for types (@pxref{Type Attributes}).
1297 You may also specify attributes with @samp{__} preceding and following
1298 each keyword. This allows you to use them in header files without
1299 being concerned about a possible macro of the same name. For example,
1300 you may use @code{__noreturn__} instead of @code{noreturn}.
1303 @cindex @code{noreturn} function attribute
1305 A few standard library functions, such as @code{abort} and @code{exit},
1306 cannot return. GNU CC knows this automatically. Some programs define
1307 their own functions that never return. You can declare them
1308 @code{noreturn} to tell the compiler this fact. For example,
1311 void fatal () __attribute__ ((noreturn));
1316 @dots{} /* @r{Print error message.} */ @dots{}
1321 The @code{noreturn} keyword tells the compiler to assume that
1322 @code{fatal} cannot return. It can then optimize without regard to what
1323 would happen if @code{fatal} ever did return. This makes slightly
1324 better code. More importantly, it helps avoid spurious warnings of
1325 uninitialized variables.
1327 Do not assume that registers saved by the calling function are
1328 restored before calling the @code{noreturn} function.
1330 It does not make sense for a @code{noreturn} function to have a return
1331 type other than @code{void}.
1333 The attribute @code{noreturn} is not implemented in GNU C versions
1334 earlier than 2.5. An alternative way to declare that a function does
1335 not return, which works in the current version and in some older
1336 versions, is as follows:
1339 typedef void voidfn ();
1341 volatile voidfn fatal;
1344 @cindex @code{const} function attribute
1346 Many functions do not examine any values except their arguments, and
1347 have no effects except the return value. Such a function can be subject
1348 to common subexpression elimination and loop optimization just as an
1349 arithmetic operator would be. These functions should be declared
1350 with the attribute @code{const}. For example,
1353 int square (int) __attribute__ ((const));
1357 says that the hypothetical function @code{square} is safe to call
1358 fewer times than the program says.
1360 The attribute @code{const} is not implemented in GNU C versions earlier
1361 than 2.5. An alternative way to declare that a function has no side
1362 effects, which works in the current version and in some older versions,
1366 typedef int intfn ();
1368 extern const intfn square;
1371 This approach does not work in GNU C++ from 2.6.0 on, since the language
1372 specifies that the @samp{const} must be attached to the return value.
1374 @cindex pointer arguments
1375 Note that a function that has pointer arguments and examines the data
1376 pointed to must @emph{not} be declared @code{const}. Likewise, a
1377 function that calls a non-@code{const} function usually must not be
1378 @code{const}. It does not make sense for a @code{const} function to
1381 @item format (@var{archetype}, @var{string-index}, @var{first-to-check})
1382 @cindex @code{format} function attribute
1383 The @code{format} attribute specifies that a function takes @code{printf}
1384 or @code{scanf} style arguments which should be type-checked against a
1385 format string. For example, the declaration:
1389 my_printf (void *my_object, const char *my_format, ...)
1390 __attribute__ ((format (printf, 2, 3)));
1394 causes the compiler to check the arguments in calls to @code{my_printf}
1395 for consistency with the @code{printf} style format string argument
1398 The parameter @var{archetype} determines how the format string is
1399 interpreted, and should be either @code{printf} or @code{scanf}. The
1400 parameter @var{string-index} specifies which argument is the format
1401 string argument (starting from 1), while @var{first-to-check} is the
1402 number of the first argument to check against the format string. For
1403 functions where the arguments are not available to be checked (such as
1404 @code{vprintf}), specify the third parameter as zero. In this case the
1405 compiler only checks the format string for consistency.
1407 In the example above, the format string (@code{my_format}) is the second
1408 argument of the function @code{my_print}, and the arguments to check
1409 start with the third argument, so the correct parameters for the format
1410 attribute are 2 and 3.
1412 The @code{format} attribute allows you to identify your own functions
1413 which take format strings as arguments, so that GNU CC can check the
1414 calls to these functions for errors. The compiler always checks formats
1415 for the ANSI library functions @code{printf}, @code{fprintf},
1416 @code{sprintf}, @code{scanf}, @code{fscanf}, @code{sscanf},
1417 @code{vprintf}, @code{vfprintf} and @code{vsprintf} whenever such
1418 warnings are requested (using @samp{-Wformat}), so there is no need to
1419 modify the header file @file{stdio.h}.
1421 @item format_arg (@var{string-index})
1422 @cindex @code{format_arg} function attribute
1423 The @code{format_arg} attribute specifies that a function takes
1424 @code{printf} or @code{scanf} style arguments, modifies it (for example,
1425 to translate it into another language), and passes it to a @code{printf}
1426 or @code{scanf} style function. For example, the declaration:
1430 my_dgettext (char *my_domain, const char *my_format)
1431 __attribute__ ((format_arg (2)));
1435 causes the compiler to check the arguments in calls to
1436 @code{my_dgettext} whose result is passed to a @code{printf} or
1437 @code{scanf} type function for consistency with the @code{printf} style
1438 format string argument @code{my_format}.
1440 The parameter @var{string-index} specifies which argument is the format
1441 string argument (starting from 1).
1443 The @code{format-arg} attribute allows you to identify your own
1444 functions which modify format strings, so that GNU CC can check the
1445 calls to @code{printf} and @code{scanf} function whose operands are a
1446 call to one of your own function. The compiler always treats
1447 @code{gettext}, @code{dgettext}, and @code{dcgettext} in this manner.
1449 @item section ("section-name")
1450 @cindex @code{section} function attribute
1451 Normally, the compiler places the code it generates in the @code{text} section.
1452 Sometimes, however, you need additional sections, or you need certain
1453 particular functions to appear in special sections. The @code{section}
1454 attribute specifies that a function lives in a particular section.
1455 For example, the declaration:
1458 extern void foobar (void) __attribute__ ((section ("bar")));
1462 puts the function @code{foobar} in the @code{bar} section.
1464 Some file formats do not support arbitrary sections so the @code{section}
1465 attribute is not available on all platforms.
1466 If you need to map the entire contents of a module to a particular
1467 section, consider using the facilities of the linker instead.
1471 @cindex @code{constructor} function attribute
1472 @cindex @code{destructor} function attribute
1473 The @code{constructor} attribute causes the function to be called
1474 automatically before execution enters @code{main ()}. Similarly, the
1475 @code{destructor} attribute causes the function to be called
1476 automatically after @code{main ()} has completed or @code{exit ()} has
1477 been called. Functions with these attributes are useful for
1478 initializing data that will be used implicitly during the execution of
1481 These attributes are not currently implemented for Objective C.
1484 This attribute, attached to a function, means that the function is meant
1485 to be possibly unused. GNU CC will not produce a warning for this
1486 function. GNU C++ does not currently support this attribute as
1487 definitions without parameters are valid in C++.
1490 @cindex @code{weak} attribute
1491 The @code{weak} attribute causes the declaration to be emitted as a weak
1492 symbol rather than a global. This is primarily useful in defining
1493 library functions which can be overridden in user code, though it can
1494 also be used with non-function declarations. Weak symbols are supported
1495 for ELF targets, and also for a.out targets when using the GNU assembler
1498 @item alias ("target")
1499 @cindex @code{alias} attribute
1500 The @code{alias} attribute causes the declaration to be emitted as an
1501 alias for another symbol, which must be specified. For instance,
1504 void __f () @{ /* do something */; @}
1505 void f () __attribute__ ((weak, alias ("__f")));
1508 declares @samp{f} to be a weak alias for @samp{__f}. In C++, the
1509 mangled name for the target must be used.
1511 @item regparm (@var{number})
1512 @cindex functions that are passed arguments in registers on the 386
1513 On the Intel 386, the @code{regparm} attribute causes the compiler to
1514 pass up to @var{number} integer arguments in registers @var{EAX},
1515 @var{EDX}, and @var{ECX} instead of on the stack. Functions that take a
1516 variable number of arguments will continue to be passed all of their
1517 arguments on the stack.
1520 @cindex functions that pop the argument stack on the 386
1521 On the Intel 386, the @code{stdcall} attribute causes the compiler to
1522 assume that the called function will pop off the stack space used to
1523 pass arguments, unless it takes a variable number of arguments.
1525 The PowerPC compiler for Windows NT currently ignores the @code{stdcall}
1529 @cindex functions that do pop the argument stack on the 386
1530 On the Intel 386, the @code{cdecl} attribute causes the compiler to
1531 assume that the calling function will pop off the stack space used to
1532 pass arguments. This is
1533 useful to override the effects of the @samp{-mrtd} switch.
1535 The PowerPC compiler for Windows NT currently ignores the @code{cdecl}
1539 @cindex functions called via pointer on the RS/6000 and PowerPC
1540 On the RS/6000 and PowerPC, the @code{longcall} attribute causes the
1541 compiler to always call the function via a pointer, so that functions
1542 which reside further than 64 megabytes (67,108,864 bytes) from the
1543 current location can be called.
1546 @cindex functions which are imported from a dll on PowerPC Windows NT
1547 On the PowerPC running Windows NT, the @code{dllimport} attribute causes
1548 the compiler to call the function via a global pointer to the function
1549 pointer that is set up by the Windows NT dll library. The pointer name
1550 is formed by combining @code{__imp_} and the function name.
1553 @cindex functions which are exported from a dll on PowerPC Windows NT
1554 On the PowerPC running Windows NT, the @code{dllexport} attribute causes
1555 the compiler to provide a global pointer to the function pointer, so
1556 that it can be called with the @code{dllimport} attribute. The pointer
1557 name is formed by combining @code{__imp_} and the function name.
1559 @item exception (@var{except-func} [, @var{except-arg}])
1560 @cindex functions which specify exception handling on PowerPC Windows NT
1561 On the PowerPC running Windows NT, the @code{exception} attribute causes
1562 the compiler to modify the structured exception table entry it emits for
1563 the declared function. The string or identifier @var{except-func} is
1564 placed in the third entry of the structured exception table. It
1565 represents a function, which is called by the exception handling
1566 mechanism if an exception occurs. If it was specified, the string or
1567 identifier @var{except-arg} is placed in the fourth entry of the
1568 structured exception table.
1570 @item function_vector
1571 @cindex calling functions through the function vector on the H8/300 processors
1572 Use this option on the H8/300 and H8/300H to indicate that the specified
1573 function should be called through the function vector. Calling a
1574 function through the function vector will reduce code size, however;
1575 the function vector has a limited size (maximum 128 entries on the H8/300
1576 and 64 entries on the H8/300H) and shares space with the interrupt vector.
1578 You must use GAS and GLD from GNU binutils version 2.7 or later for
1579 this option to work correctly.
1581 @item interrupt_handler
1582 @cindex interrupt handler functions on the H8/300 processors
1583 Use this option on the H8/300 and H8/300H to indicate that the specified
1584 function is an interrupt handler. The compiler will generate function
1585 entry and exit sequences suitable for use in an interrupt handler when this
1586 attribute is present.
1589 @cindex eight bit data on the H8/300 and H8/300H
1590 Use this option on the H8/300 and H8/300H to indicate that the specified
1591 variable should be placed into the eight bit data section.
1592 The compiler will generate more efficient code for certain operations
1593 on data in the eight bit data area. Note the eight bit data area is limited to
1596 You must use GAS and GLD from GNU binutils version 2.7 or later for
1597 this option to work correctly.
1600 @cindex tiny data section on the H8/300H
1601 Use this option on the H8/300H to indicate that the specified
1602 variable should be placed into the tiny data section.
1603 The compiler will generate more efficient code for loads and stores
1604 on data in the tiny data section. Note the tiny data area is limited to
1605 slightly under 32kbytes of data.
1608 You can specify multiple attributes in a declaration by separating them
1609 by commas within the double parentheses or by immediately following an
1610 attribute declaration with another attribute declaration.
1612 @cindex @code{#pragma}, reason for not using
1613 @cindex pragma, reason for not using
1614 Some people object to the @code{__attribute__} feature, suggesting that ANSI C's
1615 @code{#pragma} should be used instead. There are two reasons for not
1620 It is impossible to generate @code{#pragma} commands from a macro.
1623 There is no telling what the same @code{#pragma} might mean in another
1627 These two reasons apply to almost any application that might be proposed
1628 for @code{#pragma}. It is basically a mistake to use @code{#pragma} for
1631 @node Function Prototypes
1632 @section Prototypes and Old-Style Function Definitions
1633 @cindex function prototype declarations
1634 @cindex old-style function definitions
1635 @cindex promotion of formal parameters
1637 GNU C extends ANSI C to allow a function prototype to override a later
1638 old-style non-prototype definition. Consider the following example:
1641 /* @r{Use prototypes unless the compiler is old-fashioned.} */
1648 /* @r{Prototype function declaration.} */
1649 int isroot P((uid_t));
1651 /* @r{Old-style function definition.} */
1653 isroot (x) /* ??? lossage here ??? */
1660 Suppose the type @code{uid_t} happens to be @code{short}. ANSI C does
1661 not allow this example, because subword arguments in old-style
1662 non-prototype definitions are promoted. Therefore in this example the
1663 function definition's argument is really an @code{int}, which does not
1664 match the prototype argument type of @code{short}.
1666 This restriction of ANSI C makes it hard to write code that is portable
1667 to traditional C compilers, because the programmer does not know
1668 whether the @code{uid_t} type is @code{short}, @code{int}, or
1669 @code{long}. Therefore, in cases like these GNU C allows a prototype
1670 to override a later old-style definition. More precisely, in GNU C, a
1671 function prototype argument type overrides the argument type specified
1672 by a later old-style definition if the former type is the same as the
1673 latter type before promotion. Thus in GNU C the above example is
1674 equivalent to the following:
1686 GNU C++ does not support old-style function definitions, so this
1687 extension is irrelevant.
1690 @section C++ Style Comments
1692 @cindex C++ comments
1693 @cindex comments, C++ style
1695 In GNU C, you may use C++ style comments, which start with @samp{//} and
1696 continue until the end of the line. Many other C implementations allow
1697 such comments, and they are likely to be in a future C standard.
1698 However, C++ style comments are not recognized if you specify
1699 @w{@samp{-ansi}} or @w{@samp{-traditional}}, since they are incompatible
1700 with traditional constructs like @code{dividend//*comment*/divisor}.
1703 @section Dollar Signs in Identifier Names
1705 @cindex dollar signs in identifier names
1706 @cindex identifier names, dollar signs in
1708 In GNU C, you may normally use dollar signs in identifier names.
1709 This is because many traditional C implementations allow such identifiers.
1710 However, dollar signs in identifiers are not supported on a few target
1711 machines, typically because the target assembler does not allow them.
1713 @node Character Escapes
1714 @section The Character @key{ESC} in Constants
1716 You can use the sequence @samp{\e} in a string or character constant to
1717 stand for the ASCII character @key{ESC}.
1720 @section Inquiring on Alignment of Types or Variables
1722 @cindex type alignment
1723 @cindex variable alignment
1725 The keyword @code{__alignof__} allows you to inquire about how an object
1726 is aligned, or the minimum alignment usually required by a type. Its
1727 syntax is just like @code{sizeof}.
1729 For example, if the target machine requires a @code{double} value to be
1730 aligned on an 8-byte boundary, then @code{__alignof__ (double)} is 8.
1731 This is true on many RISC machines. On more traditional machine
1732 designs, @code{__alignof__ (double)} is 4 or even 2.
1734 Some machines never actually require alignment; they allow reference to any
1735 data type even at an odd addresses. For these machines, @code{__alignof__}
1736 reports the @emph{recommended} alignment of a type.
1738 When the operand of @code{__alignof__} is an lvalue rather than a type, the
1739 value is the largest alignment that the lvalue is known to have. It may
1740 have this alignment as a result of its data type, or because it is part of
1741 a structure and inherits alignment from that structure. For example, after
1745 struct foo @{ int x; char y; @} foo1;
1749 the value of @code{__alignof__ (foo1.y)} is probably 2 or 4, the same as
1750 @code{__alignof__ (int)}, even though the data type of @code{foo1.y}
1751 does not itself demand any alignment.@refill
1753 A related feature which lets you specify the alignment of an object is
1754 @code{__attribute__ ((aligned (@var{alignment})))}; see the following
1757 @node Variable Attributes
1758 @section Specifying Attributes of Variables
1759 @cindex attribute of variables
1760 @cindex variable attributes
1762 The keyword @code{__attribute__} allows you to specify special
1763 attributes of variables or structure fields. This keyword is followed
1764 by an attribute specification inside double parentheses. Eight
1765 attributes are currently defined for variables: @code{aligned},
1766 @code{mode}, @code{nocommon}, @code{packed}, @code{section},
1767 @code{transparent_union}, @code{unused}, and @code{weak}. Other
1768 attributes are available for functions (@pxref{Function Attributes}) and
1769 for types (@pxref{Type Attributes}).
1771 You may also specify attributes with @samp{__} preceding and following
1772 each keyword. This allows you to use them in header files without
1773 being concerned about a possible macro of the same name. For example,
1774 you may use @code{__aligned__} instead of @code{aligned}.
1777 @cindex @code{aligned} attribute
1778 @item aligned (@var{alignment})
1779 This attribute specifies a minimum alignment for the variable or
1780 structure field, measured in bytes. For example, the declaration:
1783 int x __attribute__ ((aligned (16))) = 0;
1787 causes the compiler to allocate the global variable @code{x} on a
1788 16-byte boundary. On a 68040, this could be used in conjunction with
1789 an @code{asm} expression to access the @code{move16} instruction which
1790 requires 16-byte aligned operands.
1792 You can also specify the alignment of structure fields. For example, to
1793 create a double-word aligned @code{int} pair, you could write:
1796 struct foo @{ int x[2] __attribute__ ((aligned (8))); @};
1800 This is an alternative to creating a union with a @code{double} member
1801 that forces the union to be double-word aligned.
1803 It is not possible to specify the alignment of functions; the alignment
1804 of functions is determined by the machine's requirements and cannot be
1805 changed. You cannot specify alignment for a typedef name because such a
1806 name is just an alias, not a distinct type.
1808 As in the preceding examples, you can explicitly specify the alignment
1809 (in bytes) that you wish the compiler to use for a given variable or
1810 structure field. Alternatively, you can leave out the alignment factor
1811 and just ask the compiler to align a variable or field to the maximum
1812 useful alignment for the target machine you are compiling for. For
1813 example, you could write:
1816 short array[3] __attribute__ ((aligned));
1819 Whenever you leave out the alignment factor in an @code{aligned} attribute
1820 specification, the compiler automatically sets the alignment for the declared
1821 variable or field to the largest alignment which is ever used for any data
1822 type on the target machine you are compiling for. Doing this can often make
1823 copy operations more efficient, because the compiler can use whatever
1824 instructions copy the biggest chunks of memory when performing copies to
1825 or from the variables or fields that you have aligned this way.
1827 The @code{aligned} attribute can only increase the alignment; but you
1828 can decrease it by specifying @code{packed} as well. See below.
1830 Note that the effectiveness of @code{aligned} attributes may be limited
1831 by inherent limitations in your linker. On many systems, the linker is
1832 only able to arrange for variables to be aligned up to a certain maximum
1833 alignment. (For some linkers, the maximum supported alignment may
1834 be very very small.) If your linker is only able to align variables
1835 up to a maximum of 8 byte alignment, then specifying @code{aligned(16)}
1836 in an @code{__attribute__} will still only provide you with 8 byte
1837 alignment. See your linker documentation for further information.
1839 @item mode (@var{mode})
1840 @cindex @code{mode} attribute
1841 This attribute specifies the data type for the declaration---whichever
1842 type corresponds to the mode @var{mode}. This in effect lets you
1843 request an integer or floating point type according to its width.
1845 You may also specify a mode of @samp{byte} or @samp{__byte__} to
1846 indicate the mode corresponding to a one-byte integer, @samp{word} or
1847 @samp{__word__} for the mode of a one-word integer, and @samp{pointer}
1848 or @samp{__pointer__} for the mode used to represent pointers.
1851 @cindex @code{nocommon} attribute
1852 This attribute specifies requests GNU CC not to place a variable
1853 ``common'' but instead to allocate space for it directly. If you
1854 specify the @samp{-fno-common} flag, GNU CC will do this for all
1857 Specifying the @code{nocommon} attribute for a variable provides an
1858 initialization of zeros. A variable may only be initialized in one
1862 @cindex @code{packed} attribute
1863 The @code{packed} attribute specifies that a variable or structure field
1864 should have the smallest possible alignment---one byte for a variable,
1865 and one bit for a field, unless you specify a larger value with the
1866 @code{aligned} attribute.
1868 Here is a structure in which the field @code{x} is packed, so that it
1869 immediately follows @code{a}:
1875 int x[2] __attribute__ ((packed));
1879 @item section ("section-name")
1880 @cindex @code{section} variable attribute
1881 Normally, the compiler places the objects it generates in sections like
1882 @code{data} and @code{bss}. Sometimes, however, you need additional sections,
1883 or you need certain particular variables to appear in special sections,
1884 for example to map to special hardware. The @code{section}
1885 attribute specifies that a variable (or function) lives in a particular
1886 section. For example, this small program uses several specific section names:
1889 struct duart a __attribute__ ((section ("DUART_A"))) = @{ 0 @};
1890 struct duart b __attribute__ ((section ("DUART_B"))) = @{ 0 @};
1891 char stack[10000] __attribute__ ((section ("STACK"))) = @{ 0 @};
1892 int init_data __attribute__ ((section ("INITDATA"))) = 0;
1896 /* Initialize stack pointer */
1897 init_sp (stack + sizeof (stack));
1899 /* Initialize initialized data */
1900 memcpy (&init_data, &data, &edata - &data);
1902 /* Turn on the serial ports */
1909 Use the @code{section} attribute with an @emph{initialized} definition
1910 of a @emph{global} variable, as shown in the example. GNU CC issues
1911 a warning and otherwise ignores the @code{section} attribute in
1912 uninitialized variable declarations.
1914 You may only use the @code{section} attribute with a fully initialized
1915 global definition because of the way linkers work. The linker requires
1916 each object be defined once, with the exception that uninitialized
1917 variables tentatively go in the @code{common} (or @code{bss}) section
1918 and can be multiply "defined". You can force a variable to be
1919 initialized with the @samp{-fno-common} flag or the @code{nocommon}
1922 Some file formats do not support arbitrary sections so the @code{section}
1923 attribute is not available on all platforms.
1924 If you need to map the entire contents of a module to a particular
1925 section, consider using the facilities of the linker instead.
1927 @item transparent_union
1928 This attribute, attached to a function parameter which is a union, means
1929 that the corresponding argument may have the type of any union member,
1930 but the argument is passed as if its type were that of the first union
1931 member. For more details see @xref{Type Attributes}. You can also use
1932 this attribute on a @code{typedef} for a union data type; then it
1933 applies to all function parameters with that type.
1936 This attribute, attached to a variable, means that the variable is meant
1937 to be possibly unused. GNU CC will not produce a warning for this
1941 The @code{weak} attribute is described in @xref{Function Attributes}.
1944 To specify multiple attributes, separate them by commas within the
1945 double parentheses: for example, @samp{__attribute__ ((aligned (16),
1948 @node Type Attributes
1949 @section Specifying Attributes of Types
1950 @cindex attribute of types
1951 @cindex type attributes
1953 The keyword @code{__attribute__} allows you to specify special
1954 attributes of @code{struct} and @code{union} types when you define such
1955 types. This keyword is followed by an attribute specification inside
1956 double parentheses. Three attributes are currently defined for types:
1957 @code{aligned}, @code{packed}, and @code{transparent_union}. Other
1958 attributes are defined for functions (@pxref{Function Attributes}) and
1959 for variables (@pxref{Variable Attributes}).
1961 You may also specify any one of these attributes with @samp{__}
1962 preceding and following its keyword. This allows you to use these
1963 attributes in header files without being concerned about a possible
1964 macro of the same name. For example, you may use @code{__aligned__}
1965 instead of @code{aligned}.
1967 You may specify the @code{aligned} and @code{transparent_union}
1968 attributes either in a @code{typedef} declaration or just past the
1969 closing curly brace of a complete enum, struct or union type
1970 @emph{definition} and the @code{packed} attribute only past the closing
1971 brace of a definition.
1974 @cindex @code{aligned} attribute
1975 @item aligned (@var{alignment})
1976 This attribute specifies a minimum alignment (in bytes) for variables
1977 of the specified type. For example, the declarations:
1980 struct S @{ short f[3]; @} __attribute__ ((aligned (8));
1981 typedef int more_aligned_int __attribute__ ((aligned (8));
1985 force the compiler to insure (as fas as it can) that each variable whose
1986 type is @code{struct S} or @code{more_aligned_int} will be allocated and
1987 aligned @emph{at least} on a 8-byte boundary. On a Sparc, having all
1988 variables of type @code{struct S} aligned to 8-byte boundaries allows
1989 the compiler to use the @code{ldd} and @code{std} (doubleword load and
1990 store) instructions when copying one variable of type @code{struct S} to
1991 another, thus improving run-time efficiency.
1993 Note that the alignment of any given @code{struct} or @code{union} type
1994 is required by the ANSI C standard to be at least a perfect multiple of
1995 the lowest common multiple of the alignments of all of the members of
1996 the @code{struct} or @code{union} in question. This means that you @emph{can}
1997 effectively adjust the alignment of a @code{struct} or @code{union}
1998 type by attaching an @code{aligned} attribute to any one of the members
1999 of such a type, but the notation illustrated in the example above is a
2000 more obvious, intuitive, and readable way to request the compiler to
2001 adjust the alignment of an entire @code{struct} or @code{union} type.
2003 As in the preceding example, you can explicitly specify the alignment
2004 (in bytes) that you wish the compiler to use for a given @code{struct}
2005 or @code{union} type. Alternatively, you can leave out the alignment factor
2006 and just ask the compiler to align a type to the maximum
2007 useful alignment for the target machine you are compiling for. For
2008 example, you could write:
2011 struct S @{ short f[3]; @} __attribute__ ((aligned));
2014 Whenever you leave out the alignment factor in an @code{aligned}
2015 attribute specification, the compiler automatically sets the alignment
2016 for the type to the largest alignment which is ever used for any data
2017 type on the target machine you are compiling for. Doing this can often
2018 make copy operations more efficient, because the compiler can use
2019 whatever instructions copy the biggest chunks of memory when performing
2020 copies to or from the variables which have types that you have aligned
2023 In the example above, if the size of each @code{short} is 2 bytes, then
2024 the size of the entire @code{struct S} type is 6 bytes. The smallest
2025 power of two which is greater than or equal to that is 8, so the
2026 compiler sets the alignment for the entire @code{struct S} type to 8
2029 Note that although you can ask the compiler to select a time-efficient
2030 alignment for a given type and then declare only individual stand-alone
2031 objects of that type, the compiler's ability to select a time-efficient
2032 alignment is primarily useful only when you plan to create arrays of
2033 variables having the relevant (efficiently aligned) type. If you
2034 declare or use arrays of variables of an efficiently-aligned type, then
2035 it is likely that your program will also be doing pointer arithmetic (or
2036 subscripting, which amounts to the same thing) on pointers to the
2037 relevant type, and the code that the compiler generates for these
2038 pointer arithmetic operations will often be more efficient for
2039 efficiently-aligned types than for other types.
2041 The @code{aligned} attribute can only increase the alignment; but you
2042 can decrease it by specifying @code{packed} as well. See below.
2044 Note that the effectiveness of @code{aligned} attributes may be limited
2045 by inherent limitations in your linker. On many systems, the linker is
2046 only able to arrange for variables to be aligned up to a certain maximum
2047 alignment. (For some linkers, the maximum supported alignment may
2048 be very very small.) If your linker is only able to align variables
2049 up to a maximum of 8 byte alignment, then specifying @code{aligned(16)}
2050 in an @code{__attribute__} will still only provide you with 8 byte
2051 alignment. See your linker documentation for further information.
2054 This attribute, attached to an @code{enum}, @code{struct}, or
2055 @code{union} type definition, specified that the minimum required memory
2056 be used to represent the type.
2058 Specifying this attribute for @code{struct} and @code{union} types is
2059 equivalent to specifying the @code{packed} attribute on each of the
2060 structure or union members. Specifying the @samp{-fshort-enums}
2061 flag on the line is equivalent to specifying the @code{packed}
2062 attribute on all @code{enum} definitions.
2064 You may only specify this attribute after a closing curly brace on an
2065 @code{enum} definition, not in a @code{typedef} declaration.
2067 @item transparent_union
2068 This attribute, attached to a @code{union} type definition, indicates
2069 that any function parameter having that union type causes calls to that
2070 function to be treated in a special way.
2072 First, the argument corresponding to a transparent union type can be of
2073 any type in the union; no cast is required. Also, if the union contains
2074 a pointer type, the corresponding argument can be a null pointer
2075 constant or a void pointer expression; and if the union contains a void
2076 pointer type, the corresponding argument can be any pointer expression.
2077 If the union member type is a pointer, qualifiers like @code{const} on
2078 the referenced type must be respected, just as with normal pointer
2081 Second, the argument is passed to the function using the calling
2082 conventions of first member of the transparent union, not the calling
2083 conventions of the union itself. All members of the union must have the
2084 same machine representation; this is necessary for this argument passing
2087 Transparent unions are designed for library functions that have multiple
2088 interfaces for compatibility reasons. For example, suppose the
2089 @code{wait} function must accept either a value of type @code{int *} to
2090 comply with Posix, or a value of type @code{union wait *} to comply with
2091 the 4.1BSD interface. If @code{wait}'s parameter were @code{void *},
2092 @code{wait} would accept both kinds of arguments, but it would also
2093 accept any other pointer type and this would make argument type checking
2094 less useful. Instead, @code{<sys/wait.h>} might define the interface
2102 @} wait_status_ptr_t __attribute__ ((__transparent_union__));
2104 pid_t wait (wait_status_ptr_t);
2107 This interface allows either @code{int *} or @code{union wait *}
2108 arguments to be passed, using the @code{int *} calling convention.
2109 The program can call @code{wait} with arguments of either type:
2112 int w1 () @{ int w; return wait (&w); @}
2113 int w2 () @{ union wait w; return wait (&w); @}
2116 With this interface, @code{wait}'s implementation might look like this:
2119 pid_t wait (wait_status_ptr_t p)
2121 return waitpid (-1, p.__ip, 0);
2126 To specify multiple attributes, separate them by commas within the
2127 double parentheses: for example, @samp{__attribute__ ((aligned (16),
2131 @section An Inline Function is As Fast As a Macro
2132 @cindex inline functions
2133 @cindex integrating function code
2135 @cindex macros, inline alternative
2137 By declaring a function @code{inline}, you can direct GNU CC to
2138 integrate that function's code into the code for its callers. This
2139 makes execution faster by eliminating the function-call overhead; in
2140 addition, if any of the actual argument values are constant, their known
2141 values may permit simplifications at compile time so that not all of the
2142 inline function's code needs to be included. The effect on code size is
2143 less predictable; object code may be larger or smaller with function
2144 inlining, depending on the particular case. Inlining of functions is an
2145 optimization and it really ``works'' only in optimizing compilation. If
2146 you don't use @samp{-O}, no function is really inline.
2148 To declare a function inline, use the @code{inline} keyword in its
2149 declaration, like this:
2159 (If you are writing a header file to be included in ANSI C programs, write
2160 @code{__inline__} instead of @code{inline}. @xref{Alternate Keywords}.)
2162 You can also make all ``simple enough'' functions inline with the option
2163 @samp{-finline-functions}. Note that certain usages in a function
2164 definition can make it unsuitable for inline substitution.
2166 Note that in C and Objective C, unlike C++, the @code{inline} keyword
2167 does not affect the linkage of the function.
2169 @cindex automatic @code{inline} for C++ member fns
2170 @cindex @code{inline} automatic for C++ member fns
2171 @cindex member fns, automatically @code{inline}
2172 @cindex C++ member fns, automatically @code{inline}
2173 GNU CC automatically inlines member functions defined within the class
2174 body of C++ programs even if they are not explicitly declared
2175 @code{inline}. (You can override this with @samp{-fno-default-inline};
2176 @pxref{C++ Dialect Options,,Options Controlling C++ Dialect}.)
2178 @cindex inline functions, omission of
2179 When a function is both inline and @code{static}, if all calls to the
2180 function are integrated into the caller, and the function's address is
2181 never used, then the function's own assembler code is never referenced.
2182 In this case, GNU CC does not actually output assembler code for the
2183 function, unless you specify the option @samp{-fkeep-inline-functions}.
2184 Some calls cannot be integrated for various reasons (in particular,
2185 calls that precede the function's definition cannot be integrated, and
2186 neither can recursive calls within the definition). If there is a
2187 nonintegrated call, then the function is compiled to assembler code as
2188 usual. The function must also be compiled as usual if the program
2189 refers to its address, because that can't be inlined.
2191 @cindex non-static inline function
2192 When an inline function is not @code{static}, then the compiler must assume
2193 that there may be calls from other source files; since a global symbol can
2194 be defined only once in any program, the function must not be defined in
2195 the other source files, so the calls therein cannot be integrated.
2196 Therefore, a non-@code{static} inline function is always compiled on its
2197 own in the usual fashion.
2199 If you specify both @code{inline} and @code{extern} in the function
2200 definition, then the definition is used only for inlining. In no case
2201 is the function compiled on its own, not even if you refer to its
2202 address explicitly. Such an address becomes an external reference, as
2203 if you had only declared the function, and had not defined it.
2205 This combination of @code{inline} and @code{extern} has almost the
2206 effect of a macro. The way to use it is to put a function definition in
2207 a header file with these keywords, and put another copy of the
2208 definition (lacking @code{inline} and @code{extern}) in a library file.
2209 The definition in the header file will cause most calls to the function
2210 to be inlined. If any uses of the function remain, they will refer to
2211 the single copy in the library.
2213 GNU C does not inline any functions when not optimizing. It is not
2214 clear whether it is better to inline or not, in this case, but we found
2215 that a correct implementation when not optimizing was difficult. So we
2216 did the easy thing, and turned it off.
2219 @section Assembler Instructions with C Expression Operands
2220 @cindex extended @code{asm}
2221 @cindex @code{asm} expressions
2222 @cindex assembler instructions
2225 In an assembler instruction using @code{asm}, you can now specify the
2226 operands of the instruction using C expressions. This means no more
2227 guessing which registers or memory locations will contain the data you want
2230 You must specify an assembler instruction template much like what appears
2231 in a machine description, plus an operand constraint string for each
2234 For example, here is how to use the 68881's @code{fsinx} instruction:
2237 asm ("fsinx %1,%0" : "=f" (result) : "f" (angle));
2241 Here @code{angle} is the C expression for the input operand while
2242 @code{result} is that of the output operand. Each has @samp{"f"} as its
2243 operand constraint, saying that a floating point register is required. The
2244 @samp{=} in @samp{=f} indicates that the operand is an output; all output
2245 operands' constraints must use @samp{=}. The constraints use the same
2246 language used in the machine description (@pxref{Constraints}).
2248 Each operand is described by an operand-constraint string followed by the C
2249 expression in parentheses. A colon separates the assembler template from
2250 the first output operand, and another separates the last output operand
2251 from the first input, if any. Commas separate output operands and separate
2252 inputs. The total number of operands is limited to ten or to the maximum
2253 number of operands in any instruction pattern in the machine description,
2254 whichever is greater.
2256 If there are no output operands, and there are input operands, then there
2257 must be two consecutive colons surrounding the place where the output
2260 Output operand expressions must be lvalues; the compiler can check this.
2261 The input operands need not be lvalues. The compiler cannot check whether
2262 the operands have data types that are reasonable for the instruction being
2263 executed. It does not parse the assembler instruction template and does
2264 not know what it means, or whether it is valid assembler input. The
2265 extended @code{asm} feature is most often used for machine instructions
2266 that the compiler itself does not know exist. If the output expression
2267 cannot be directly addressed (for example, it is a bit field), your
2268 constraint must allow a register. In that case, GNU CC will use
2269 the register as the output of the @code{asm}, and then store that
2270 register into the output.
2272 The ordinary output operands must be write-only; GNU CC will assume
2273 that the values in these operands before the instruction are dead and
2274 need not be generated. Extended asm supports input-output or
2275 read-write operands. Use the constraint character @samp{+} to indicate
2276 such an operand and list it with the output operands.
2278 When the constraints for the read-write operand
2279 (or the operand in which only some of the bits are to be changed)
2280 allows a register, you may, as an alternative, logically
2281 split its function into two separate operands, one input operand and one
2282 write-only output operand. The connection between them is expressed by
2283 constraints which say they need to be in the same location when the
2284 instruction executes. You can use the same C expression for both
2285 operands, or different expressions. For example, here we write the
2286 (fictitious) @samp{combine} instruction with @code{bar} as its read-only
2287 source operand and @code{foo} as its read-write destination:
2290 asm ("combine %2,%0" : "=r" (foo) : "0" (foo), "g" (bar));
2294 The constraint @samp{"0"} for operand 1 says that it must occupy the same
2295 location as operand 0. A digit in constraint is allowed only in an input
2296 operand, and it must refer to an output operand.
2298 Only a digit in the constraint can guarantee that one operand will be in
2299 the same place as another. The mere fact that @code{foo} is the value of
2300 both operands is not enough to guarantee that they will be in the same
2301 place in the generated assembler code. The following would not work:
2304 asm ("combine %2,%0" : "=r" (foo) : "r" (foo), "g" (bar));
2307 Various optimizations or reloading could cause operands 0 and 1 to be in
2308 different registers; GNU CC knows no reason not to do so. For example, the
2309 compiler might find a copy of the value of @code{foo} in one register and
2310 use it for operand 1, but generate the output operand 0 in a different
2311 register (copying it afterward to @code{foo}'s own address). Of course,
2312 since the register for operand 1 is not even mentioned in the assembler
2313 code, the result will not work, but GNU CC can't tell that.
2315 Some instructions clobber specific hard registers. To describe this, write
2316 a third colon after the input operands, followed by the names of the
2317 clobbered hard registers (given as strings). Here is a realistic example
2321 asm volatile ("movc3 %0,%1,%2"
2323 : "g" (from), "g" (to), "g" (count)
2324 : "r0", "r1", "r2", "r3", "r4", "r5");
2327 If you refer to a particular hardware register from the assembler code,
2328 then you will probably have to list the register after the third colon
2329 to tell the compiler that the register's value is modified. In many
2330 assemblers, the register names begin with @samp{%}; to produce one
2331 @samp{%} in the assembler code, you must write @samp{%%} in the input.
2333 If your assembler instruction can alter the condition code register,
2334 add @samp{cc} to the list of clobbered registers. GNU CC on some
2335 machines represents the condition codes as a specific hardware
2336 register; @samp{cc} serves to name this register. On other machines,
2337 the condition code is handled differently, and specifying @samp{cc}
2338 has no effect. But it is valid no matter what the machine.
2340 If your assembler instruction modifies memory in an unpredictable
2341 fashion, add @samp{memory} to the list of clobbered registers.
2342 This will cause GNU CC to not keep memory values cached in
2343 registers across the assembler instruction.
2345 You can put multiple assembler instructions together in a single @code{asm}
2346 template, separated either with newlines (written as @samp{\n}) or with
2347 semicolons if the assembler allows such semicolons. The GNU assembler
2348 allows semicolons and all Unix assemblers seem to do so. The input
2349 operands are guaranteed not to use any of the clobbered registers, and
2350 neither will the output operands' addresses, so you can read and write the
2351 clobbered registers as many times as you like. Here is an example of
2352 multiple instructions in a template; it assumes that the subroutine
2353 @code{_foo} accepts arguments in registers 9 and 10:
2356 asm ("movl %0,r9;movl %1,r10;call _foo"
2358 : "g" (from), "g" (to)
2362 Unless an output operand has the @samp{&} constraint modifier, GNU CC may
2363 allocate it in the same register as an unrelated input operand, on the
2364 assumption that the inputs are consumed before the outputs are produced.
2365 This assumption may be false if the assembler code actually consists of
2366 more than one instruction. In such a case, use @samp{&} for each output
2367 operand that may not overlap an input.
2370 If you want to test the condition code produced by an assembler instruction,
2371 you must include a branch and a label in the @code{asm} construct, as follows:
2374 asm ("clr %0;frob %1;beq 0f;mov #1,%0;0:"
2380 This assumes your assembler supports local labels, as the GNU assembler
2381 and most Unix assemblers do.
2383 Speaking of labels, jumps from one @code{asm} to another are not
2384 supported. The compiler's optimizers do not know about these jumps,
2385 and therefore they cannot take account of them when deciding how to
2388 @cindex macros containing @code{asm}
2389 Usually the most convenient way to use these @code{asm} instructions is to
2390 encapsulate them in macros that look like functions. For example,
2394 (@{ double __value, __arg = (x); \
2395 asm ("fsinx %1,%0": "=f" (__value): "f" (__arg)); \
2400 Here the variable @code{__arg} is used to make sure that the instruction
2401 operates on a proper @code{double} value, and to accept only those
2402 arguments @code{x} which can convert automatically to a @code{double}.
2404 Another way to make sure the instruction operates on the correct data type
2405 is to use a cast in the @code{asm}. This is different from using a
2406 variable @code{__arg} in that it converts more different types. For
2407 example, if the desired type were @code{int}, casting the argument to
2408 @code{int} would accept a pointer with no complaint, while assigning the
2409 argument to an @code{int} variable named @code{__arg} would warn about
2410 using a pointer unless the caller explicitly casts it.
2412 If an @code{asm} has output operands, GNU CC assumes for optimization
2413 purposes that the instruction has no side effects except to change the
2414 output operands. This does not mean that instructions with a side effect
2415 cannot be used, but you must be careful, because the compiler may eliminate
2416 them if the output operands aren't used, or move them out of loops, or
2417 replace two with one if they constitute a common subexpression. Also, if
2418 your instruction does have a side effect on a variable that otherwise
2419 appears not to change, the old value of the variable may be reused later if
2420 it happens to be found in a register.
2422 You can prevent an @code{asm} instruction from being deleted, moved
2423 significantly, or combined, by writing the keyword @code{volatile} after
2424 the @code{asm}. For example:
2427 #define set_priority(x) \
2428 asm volatile ("set_priority %0": /* no outputs */ : "g" (x))
2432 An instruction without output operands will not be deleted or moved
2433 significantly, regardless, unless it is unreachable.
2435 Note that even a volatile @code{asm} instruction can be moved in ways
2436 that appear insignificant to the compiler, such as across jump
2437 instructions. You can't expect a sequence of volatile @code{asm}
2438 instructions to remain perfectly consecutive. If you want consecutive
2439 output, use a single @code{asm}.
2441 It is a natural idea to look for a way to give access to the condition
2442 code left by the assembler instruction. However, when we attempted to
2443 implement this, we found no way to make it work reliably. The problem
2444 is that output operands might need reloading, which would result in
2445 additional following ``store'' instructions. On most machines, these
2446 instructions would alter the condition code before there was time to
2447 test it. This problem doesn't arise for ordinary ``test'' and
2448 ``compare'' instructions because they don't have any output operands.
2450 If you are writing a header file that should be includable in ANSI C
2451 programs, write @code{__asm__} instead of @code{asm}. @xref{Alternate
2455 @c Show the details on constraints if they do not appear elsewhere in
2461 @section Controlling Names Used in Assembler Code
2462 @cindex assembler names for identifiers
2463 @cindex names used in assembler code
2464 @cindex identifiers, names in assembler code
2466 You can specify the name to be used in the assembler code for a C
2467 function or variable by writing the @code{asm} (or @code{__asm__})
2468 keyword after the declarator as follows:
2471 int foo asm ("myfoo") = 2;
2475 This specifies that the name to be used for the variable @code{foo} in
2476 the assembler code should be @samp{myfoo} rather than the usual
2479 On systems where an underscore is normally prepended to the name of a C
2480 function or variable, this feature allows you to define names for the
2481 linker that do not start with an underscore.
2483 You cannot use @code{asm} in this way in a function @emph{definition}; but
2484 you can get the same effect by writing a declaration for the function
2485 before its definition and putting @code{asm} there, like this:
2488 extern func () asm ("FUNC");
2495 It is up to you to make sure that the assembler names you choose do not
2496 conflict with any other assembler symbols. Also, you must not use a
2497 register name; that would produce completely invalid assembler code. GNU
2498 CC does not as yet have the ability to store static variables in registers.
2499 Perhaps that will be added.
2501 @node Explicit Reg Vars
2502 @section Variables in Specified Registers
2503 @cindex explicit register variables
2504 @cindex variables in specified registers
2505 @cindex specified registers
2506 @cindex registers, global allocation
2508 GNU C allows you to put a few global variables into specified hardware
2509 registers. You can also specify the register in which an ordinary
2510 register variable should be allocated.
2514 Global register variables reserve registers throughout the program.
2515 This may be useful in programs such as programming language
2516 interpreters which have a couple of global variables that are accessed
2520 Local register variables in specific registers do not reserve the
2521 registers. The compiler's data flow analysis is capable of determining
2522 where the specified registers contain live values, and where they are
2523 available for other uses.
2525 These local variables are sometimes convenient for use with the extended
2526 @code{asm} feature (@pxref{Extended Asm}), if you want to write one
2527 output of the assembler instruction directly into a particular register.
2528 (This will work provided the register you specify fits the constraints
2529 specified for that operand in the @code{asm}.)
2537 @node Global Reg Vars
2538 @subsection Defining Global Register Variables
2539 @cindex global register variables
2540 @cindex registers, global variables in
2542 You can define a global register variable in GNU C like this:
2545 register int *foo asm ("a5");
2549 Here @code{a5} is the name of the register which should be used. Choose a
2550 register which is normally saved and restored by function calls on your
2551 machine, so that library routines will not clobber it.
2553 Naturally the register name is cpu-dependent, so you would need to
2554 conditionalize your program according to cpu type. The register
2555 @code{a5} would be a good choice on a 68000 for a variable of pointer
2556 type. On machines with register windows, be sure to choose a ``global''
2557 register that is not affected magically by the function call mechanism.
2559 In addition, operating systems on one type of cpu may differ in how they
2560 name the registers; then you would need additional conditionals. For
2561 example, some 68000 operating systems call this register @code{%a5}.
2563 Eventually there may be a way of asking the compiler to choose a register
2564 automatically, but first we need to figure out how it should choose and
2565 how to enable you to guide the choice. No solution is evident.
2567 Defining a global register variable in a certain register reserves that
2568 register entirely for this use, at least within the current compilation.
2569 The register will not be allocated for any other purpose in the functions
2570 in the current compilation. The register will not be saved and restored by
2571 these functions. Stores into this register are never deleted even if they
2572 would appear to be dead, but references may be deleted or moved or
2575 It is not safe to access the global register variables from signal
2576 handlers, or from more than one thread of control, because the system
2577 library routines may temporarily use the register for other things (unless
2578 you recompile them specially for the task at hand).
2580 @cindex @code{qsort}, and global register variables
2581 It is not safe for one function that uses a global register variable to
2582 call another such function @code{foo} by way of a third function
2583 @code{lose} that was compiled without knowledge of this variable (i.e. in a
2584 different source file in which the variable wasn't declared). This is
2585 because @code{lose} might save the register and put some other value there.
2586 For example, you can't expect a global register variable to be available in
2587 the comparison-function that you pass to @code{qsort}, since @code{qsort}
2588 might have put something else in that register. (If you are prepared to
2589 recompile @code{qsort} with the same global register variable, you can
2590 solve this problem.)
2592 If you want to recompile @code{qsort} or other source files which do not
2593 actually use your global register variable, so that they will not use that
2594 register for any other purpose, then it suffices to specify the compiler
2595 option @samp{-ffixed-@var{reg}}. You need not actually add a global
2596 register declaration to their source code.
2598 A function which can alter the value of a global register variable cannot
2599 safely be called from a function compiled without this variable, because it
2600 could clobber the value the caller expects to find there on return.
2601 Therefore, the function which is the entry point into the part of the
2602 program that uses the global register variable must explicitly save and
2603 restore the value which belongs to its caller.
2605 @cindex register variable after @code{longjmp}
2606 @cindex global register after @code{longjmp}
2607 @cindex value after @code{longjmp}
2610 On most machines, @code{longjmp} will restore to each global register
2611 variable the value it had at the time of the @code{setjmp}. On some
2612 machines, however, @code{longjmp} will not change the value of global
2613 register variables. To be portable, the function that called @code{setjmp}
2614 should make other arrangements to save the values of the global register
2615 variables, and to restore them in a @code{longjmp}. This way, the same
2616 thing will happen regardless of what @code{longjmp} does.
2618 All global register variable declarations must precede all function
2619 definitions. If such a declaration could appear after function
2620 definitions, the declaration would be too late to prevent the register from
2621 being used for other purposes in the preceding functions.
2623 Global register variables may not have initial values, because an
2624 executable file has no means to supply initial contents for a register.
2626 On the Sparc, there are reports that g3 @dots{} g7 are suitable
2627 registers, but certain library functions, such as @code{getwd}, as well
2628 as the subroutines for division and remainder, modify g3 and g4. g1 and
2629 g2 are local temporaries.
2631 On the 68000, a2 @dots{} a5 should be suitable, as should d2 @dots{} d7.
2632 Of course, it will not do to use more than a few of those.
2634 @node Local Reg Vars
2635 @subsection Specifying Registers for Local Variables
2636 @cindex local variables, specifying registers
2637 @cindex specifying registers for local variables
2638 @cindex registers for local variables
2640 You can define a local register variable with a specified register
2644 register int *foo asm ("a5");
2648 Here @code{a5} is the name of the register which should be used. Note
2649 that this is the same syntax used for defining global register
2650 variables, but for a local variable it would appear within a function.
2652 Naturally the register name is cpu-dependent, but this is not a
2653 problem, since specific registers are most often useful with explicit
2654 assembler instructions (@pxref{Extended Asm}). Both of these things
2655 generally require that you conditionalize your program according to
2658 In addition, operating systems on one type of cpu may differ in how they
2659 name the registers; then you would need additional conditionals. For
2660 example, some 68000 operating systems call this register @code{%a5}.
2662 Eventually there may be a way of asking the compiler to choose a register
2663 automatically, but first we need to figure out how it should choose and
2664 how to enable you to guide the choice. No solution is evident.
2666 Defining such a register variable does not reserve the register; it
2667 remains available for other uses in places where flow control determines
2668 the variable's value is not live. However, these registers are made
2669 unavailable for use in the reload pass. I would not be surprised if
2670 excessive use of this feature leaves the compiler too few available
2671 registers to compile certain functions.
2673 @node Alternate Keywords
2674 @section Alternate Keywords
2675 @cindex alternate keywords
2676 @cindex keywords, alternate
2678 The option @samp{-traditional} disables certain keywords; @samp{-ansi}
2679 disables certain others. This causes trouble when you want to use GNU C
2680 extensions, or ANSI C features, in a general-purpose header file that
2681 should be usable by all programs, including ANSI C programs and traditional
2682 ones. The keywords @code{asm}, @code{typeof} and @code{inline} cannot be
2683 used since they won't work in a program compiled with @samp{-ansi}, while
2684 the keywords @code{const}, @code{volatile}, @code{signed}, @code{typeof}
2685 and @code{inline} won't work in a program compiled with
2686 @samp{-traditional}.@refill
2688 The way to solve these problems is to put @samp{__} at the beginning and
2689 end of each problematical keyword. For example, use @code{__asm__}
2690 instead of @code{asm}, @code{__const__} instead of @code{const}, and
2691 @code{__inline__} instead of @code{inline}.
2693 Other C compilers won't accept these alternative keywords; if you want to
2694 compile with another compiler, you can define the alternate keywords as
2695 macros to replace them with the customary keywords. It looks like this:
2703 @samp{-pedantic} causes warnings for many GNU C extensions. You can
2704 prevent such warnings within one expression by writing
2705 @code{__extension__} before the expression. @code{__extension__} has no
2706 effect aside from this.
2708 @node Incomplete Enums
2709 @section Incomplete @code{enum} Types
2711 You can define an @code{enum} tag without specifying its possible values.
2712 This results in an incomplete type, much like what you get if you write
2713 @code{struct foo} without describing the elements. A later declaration
2714 which does specify the possible values completes the type.
2716 You can't allocate variables or storage using the type while it is
2717 incomplete. However, you can work with pointers to that type.
2719 This extension may not be very useful, but it makes the handling of
2720 @code{enum} more consistent with the way @code{struct} and @code{union}
2723 This extension is not supported by GNU C++.
2725 @node Function Names
2726 @section Function Names as Strings
2728 GNU CC predefines two string variables to be the name of the current function.
2729 The variable @code{__FUNCTION__} is the name of the function as it appears
2730 in the source. The variable @code{__PRETTY_FUNCTION__} is the name of
2731 the function pretty printed in a language specific fashion.
2733 These names are always the same in a C function, but in a C++ function
2734 they may be different. For example, this program:
2738 extern int printf (char *, ...);
2745 printf ("__FUNCTION__ = %s\n", __FUNCTION__);
2746 printf ("__PRETTY_FUNCTION__ = %s\n", __PRETTY_FUNCTION__);
2764 __PRETTY_FUNCTION__ = int a::sub (int)
2767 These names are not macros: they are predefined string variables.
2768 For example, @samp{#ifdef __FUNCTION__} does not have any special
2769 meaning inside a function, since the preprocessor does not do anything
2770 special with the identifier @code{__FUNCTION__}.
2772 @node Return Address
2773 @section Getting the Return or Frame Address of a Function
2775 These functions may be used to get information about the callers of a
2779 @item __builtin_return_address (@var{level})
2780 This function returns the return address of the current function, or of
2781 one of its callers. The @var{level} argument is number of frames to
2782 scan up the call stack. A value of @code{0} yields the return address
2783 of the current function, a value of @code{1} yields the return address
2784 of the caller of the current function, and so forth.
2786 The @var{level} argument must be a constant integer.
2788 On some machines it may be impossible to determine the return address of
2789 any function other than the current one; in such cases, or when the top
2790 of the stack has been reached, this function will return @code{0}.
2792 This function should only be used with a non-zero argument for debugging
2795 @item __builtin_frame_address (@var{level})
2796 This function is similar to @code{__builtin_return_address}, but it
2797 returns the address of the function frame rather than the return address
2798 of the function. Calling @code{__builtin_frame_address} with a value of
2799 @code{0} yields the frame address of the current function, a value of
2800 @code{1} yields the frame address of the caller of the current function,
2803 The frame is the area on the stack which holds local variables and saved
2804 registers. The frame address is normally the address of the first word
2805 pushed on to the stack by the function. However, the exact definition
2806 depends upon the processor and the calling convention. If the processor
2807 has a dedicated frame pointer register, and the function has a frame,
2808 then @code{__builtin_frame_address} will return the value of the frame
2811 The caveats that apply to @code{__builtin_return_address} apply to this
2815 @node C++ Extensions
2816 @chapter Extensions to the C++ Language
2817 @cindex extensions, C++ language
2818 @cindex C++ language extensions
2820 The GNU compiler provides these extensions to the C++ language (and you
2821 can also use most of the C language extensions in your C++ programs). If you
2822 want to write code that checks whether these features are available, you can
2823 test for the GNU compiler the same way as for C programs: check for a
2824 predefined macro @code{__GNUC__}. You can also use @code{__GNUG__} to
2825 test specifically for GNU C++ (@pxref{Standard Predefined,,Standard
2826 Predefined Macros,cpp.info,The C Preprocessor}).
2829 * Naming Results:: Giving a name to C++ function return values.
2830 * Min and Max:: C++ Minimum and maximum operators.
2831 * Destructors and Goto:: Goto is safe to use in C++ even when destructors
2833 * C++ Interface:: You can use a single C++ header file for both
2834 declarations and definitions.
2835 * Template Instantiation:: Methods for ensuring that exactly one copy of
2836 each needed template instantiation is emitted.
2837 * C++ Signatures:: You can specify abstract types to get subtype
2838 polymorphism independent from inheritance.
2841 @node Naming Results
2842 @section Named Return Values in C++
2844 @cindex @code{return}, in C++ function header
2845 @cindex return value, named, in C++
2846 @cindex named return value in C++
2847 @cindex C++ named return value
2848 GNU C++ extends the function-definition syntax to allow you to specify a
2849 name for the result of a function outside the body of the definition, in
2855 @var{functionname} (@var{args}) return @var{resultname};
2864 You can use this feature to avoid an extra constructor call when
2865 a function result has a class type. For example, consider a function
2866 @code{m}, declared as @w{@samp{X v = m ();}}, whose result is of class
2879 @cindex implicit argument: return value
2880 Although @code{m} appears to have no arguments, in fact it has one implicit
2881 argument: the address of the return value. At invocation, the address
2882 of enough space to hold @code{v} is sent in as the implicit argument.
2883 Then @code{b} is constructed and its @code{a} field is set to the value
2884 23. Finally, a copy constructor (a constructor of the form @samp{X(X&)})
2885 is applied to @code{b}, with the (implicit) return value location as the
2886 target, so that @code{v} is now bound to the return value.
2888 But this is wasteful. The local @code{b} is declared just to hold
2889 something that will be copied right out. While a compiler that
2890 combined an ``elision'' algorithm with interprocedural data flow
2891 analysis could conceivably eliminate all of this, it is much more
2892 practical to allow you to assist the compiler in generating
2893 efficient code by manipulating the return value explicitly,
2894 thus avoiding the local variable and copy constructor altogether.
2896 Using the extended GNU C++ function-definition syntax, you can avoid the
2897 temporary allocation and copying by naming @code{r} as your return value
2898 at the outset, and assigning to its @code{a} field directly:
2909 The declaration of @code{r} is a standard, proper declaration, whose effects
2910 are executed @strong{before} any of the body of @code{m}.
2912 Functions of this type impose no additional restrictions; in particular,
2913 you can execute @code{return} statements, or return implicitly by
2914 reaching the end of the function body (``falling off the edge'').
2926 (or even @w{@samp{X m () return r (23); @{ @}}}) are unambiguous, since
2927 the return value @code{r} has been initialized in either case. The
2928 following code may be hard to read, but also works predictably:
2939 The return value slot denoted by @code{r} is initialized at the outset,
2940 but the statement @samp{return b;} overrides this value. The compiler
2941 deals with this by destroying @code{r} (calling the destructor if there
2942 is one, or doing nothing if there is not), and then reinitializing
2943 @code{r} with @code{b}.
2945 This extension is provided primarily to help people who use overloaded
2946 operators, where there is a great need to control not just the
2947 arguments, but the return values of functions. For classes where the
2948 copy constructor incurs a heavy performance penalty (especially in the
2949 common case where there is a quick default constructor), this is a major
2950 savings. The disadvantage of this extension is that you do not control
2951 when the default constructor for the return value is called: it is
2952 always called at the beginning.
2955 @section Minimum and Maximum Operators in C++
2957 It is very convenient to have operators which return the ``minimum'' or the
2958 ``maximum'' of two arguments. In GNU C++ (but not in GNU C),
2961 @item @var{a} <? @var{b}
2963 @cindex minimum operator
2964 is the @dfn{minimum}, returning the smaller of the numeric values
2965 @var{a} and @var{b};
2967 @item @var{a} >? @var{b}
2969 @cindex maximum operator
2970 is the @dfn{maximum}, returning the larger of the numeric values @var{a}
2974 These operations are not primitive in ordinary C++, since you can
2975 use a macro to return the minimum of two things in C++, as in the
2979 #define MIN(X,Y) ((X) < (Y) ? : (X) : (Y))
2983 You might then use @w{@samp{int min = MIN (i, j);}} to set @var{min} to
2984 the minimum value of variables @var{i} and @var{j}.
2986 However, side effects in @code{X} or @code{Y} may cause unintended
2987 behavior. For example, @code{MIN (i++, j++)} will fail, incrementing
2988 the smaller counter twice. A GNU C extension allows you to write safe
2989 macros that avoid this kind of problem (@pxref{Naming Types,,Naming an
2990 Expression's Type}). However, writing @code{MIN} and @code{MAX} as
2991 macros also forces you to use function-call notation for a
2992 fundamental arithmetic operation. Using GNU C++ extensions, you can
2993 write @w{@samp{int min = i <? j;}} instead.
2995 Since @code{<?} and @code{>?} are built into the compiler, they properly
2996 handle expressions with side-effects; @w{@samp{int min = i++ <? j++;}}
2999 @node Destructors and Goto
3000 @section @code{goto} and Destructors in GNU C++
3002 @cindex @code{goto} in C++
3003 @cindex destructors vs @code{goto}
3004 In C++ programs, you can safely use the @code{goto} statement. When you
3005 use it to exit a block which contains aggregates requiring destructors,
3006 the destructors will run before the @code{goto} transfers control.
3008 @cindex constructors vs @code{goto}
3009 The compiler still forbids using @code{goto} to @emph{enter} a scope
3010 that requires constructors.
3013 @section Declarations and Definitions in One Header
3015 @cindex interface and implementation headers, C++
3016 @cindex C++ interface and implementation headers
3017 C++ object definitions can be quite complex. In principle, your source
3018 code will need two kinds of things for each object that you use across
3019 more than one source file. First, you need an @dfn{interface}
3020 specification, describing its structure with type declarations and
3021 function prototypes. Second, you need the @dfn{implementation} itself.
3022 It can be tedious to maintain a separate interface description in a
3023 header file, in parallel to the actual implementation. It is also
3024 dangerous, since separate interface and implementation definitions may
3025 not remain parallel.
3027 @cindex pragmas, interface and implementation
3028 With GNU C++, you can use a single header file for both purposes.
3031 @emph{Warning:} The mechanism to specify this is in transition. For the
3032 nonce, you must use one of two @code{#pragma} commands; in a future
3033 release of GNU C++, an alternative mechanism will make these
3034 @code{#pragma} commands unnecessary.
3037 The header file contains the full definitions, but is marked with
3038 @samp{#pragma interface} in the source code. This allows the compiler
3039 to use the header file only as an interface specification when ordinary
3040 source files incorporate it with @code{#include}. In the single source
3041 file where the full implementation belongs, you can use either a naming
3042 convention or @samp{#pragma implementation} to indicate this alternate
3043 use of the header file.
3046 @item #pragma interface
3047 @itemx #pragma interface "@var{subdir}/@var{objects}.h"
3048 @kindex #pragma interface
3049 Use this directive in @emph{header files} that define object classes, to save
3050 space in most of the object files that use those classes. Normally,
3051 local copies of certain information (backup copies of inline member
3052 functions, debugging information, and the internal tables that implement
3053 virtual functions) must be kept in each object file that includes class
3054 definitions. You can use this pragma to avoid such duplication. When a
3055 header file containing @samp{#pragma interface} is included in a
3056 compilation, this auxiliary information will not be generated (unless
3057 the main input source file itself uses @samp{#pragma implementation}).
3058 Instead, the object files will contain references to be resolved at link
3061 The second form of this directive is useful for the case where you have
3062 multiple headers with the same name in different directories. If you
3063 use this form, you must specify the same string to @samp{#pragma
3066 @item #pragma implementation
3067 @itemx #pragma implementation "@var{objects}.h"
3068 @kindex #pragma implementation
3069 Use this pragma in a @emph{main input file}, when you want full output from
3070 included header files to be generated (and made globally visible). The
3071 included header file, in turn, should use @samp{#pragma interface}.
3072 Backup copies of inline member functions, debugging information, and the
3073 internal tables used to implement virtual functions are all generated in
3074 implementation files.
3076 @cindex implied @code{#pragma implementation}
3077 @cindex @code{#pragma implementation}, implied
3078 @cindex naming convention, implementation headers
3079 If you use @samp{#pragma implementation} with no argument, it applies to
3080 an include file with the same basename@footnote{A file's @dfn{basename}
3081 was the name stripped of all leading path information and of trailing
3082 suffixes, such as @samp{.h} or @samp{.C} or @samp{.cc}.} as your source
3083 file. For example, in @file{allclass.cc}, giving just
3084 @samp{#pragma implementation}
3085 by itself is equivalent to @samp{#pragma implementation "allclass.h"}.
3087 In versions of GNU C++ prior to 2.6.0 @file{allclass.h} was treated as
3088 an implementation file whenever you would include it from
3089 @file{allclass.cc} even if you never specified @samp{#pragma
3090 implementation}. This was deemed to be more trouble than it was worth,
3091 however, and disabled.
3093 If you use an explicit @samp{#pragma implementation}, it must appear in
3094 your source file @emph{before} you include the affected header files.
3096 Use the string argument if you want a single implementation file to
3097 include code from multiple header files. (You must also use
3098 @samp{#include} to include the header file; @samp{#pragma
3099 implementation} only specifies how to use the file---it doesn't actually
3102 There is no way to split up the contents of a single header file into
3103 multiple implementation files.
3106 @cindex inlining and C++ pragmas
3107 @cindex C++ pragmas, effect on inlining
3108 @cindex pragmas in C++, effect on inlining
3109 @samp{#pragma implementation} and @samp{#pragma interface} also have an
3110 effect on function inlining.
3112 If you define a class in a header file marked with @samp{#pragma
3113 interface}, the effect on a function defined in that class is similar to
3114 an explicit @code{extern} declaration---the compiler emits no code at
3115 all to define an independent version of the function. Its definition
3116 is used only for inlining with its callers.
3118 Conversely, when you include the same header file in a main source file
3119 that declares it as @samp{#pragma implementation}, the compiler emits
3120 code for the function itself; this defines a version of the function
3121 that can be found via pointers (or by callers compiled without
3122 inlining). If all calls to the function can be inlined, you can avoid
3123 emitting the function by compiling with @samp{-fno-implement-inlines}.
3124 If any calls were not inlined, you will get linker errors.
3126 @node Template Instantiation
3127 @section Where's the Template?
3129 @cindex template instantiation
3131 C++ templates are the first language feature to require more
3132 intelligence from the environment than one usually finds on a UNIX
3133 system. Somehow the compiler and linker have to make sure that each
3134 template instance occurs exactly once in the executable if it is needed,
3135 and not at all otherwise. There are two basic approaches to this
3136 problem, which I will refer to as the Borland model and the Cfront model.
3140 Borland C++ solved the template instantiation problem by adding the code
3141 equivalent of common blocks to their linker; template instances
3142 are emitted in each translation unit that uses them, and they are
3143 collapsed together at run time. The advantage of this model is that the
3144 linker only has to consider the object files themselves; there is no
3145 external complexity to worry about. This disadvantage is that
3146 compilation time is increased because the template code is being
3147 compiled repeatedly. Code written for this model tends to include
3148 definitions of all member templates in the header file, since they must
3149 be seen to be compiled.
3152 The AT&T C++ translator, Cfront, solved the template instantiation
3153 problem by creating the notion of a template repository, an
3154 automatically maintained place where template instances are stored. As
3155 individual object files are built, notes are placed in the repository to
3156 record where templates and potential type arguments were seen so that
3157 the subsequent instantiation step knows where to find them. At link
3158 time, any needed instances are generated and linked in. The advantages
3159 of this model are more optimal compilation speed and the ability to use
3160 the system linker; to implement the Borland model a compiler vendor also
3161 needs to replace the linker. The disadvantages are vastly increased
3162 complexity, and thus potential for error; theoretically, this should be
3163 just as transparent, but in practice it has been very difficult to build
3164 multiple programs in one directory and one program in multiple
3165 directories using Cfront. Code written for this model tends to separate
3166 definitions of non-inline member templates into a separate file, which
3167 is magically found by the link preprocessor when a template needs to be
3171 Currently, g++ implements neither automatic model. In the mean time,
3172 you have three options for dealing with template instantiations:
3176 Compile your code with @samp{-fno-implicit-templates} to disable the
3177 implicit generation of template instances, and explicitly instantiate
3178 all the ones you use. This approach requires more knowledge of exactly
3179 which instances you need than do the others, but it's less
3180 mysterious and allows greater control. You can scatter the explicit
3181 instantiations throughout your program, perhaps putting them in the
3182 translation units where the instances are used or the translation units
3183 that define the templates themselves; you can put all of the explicit
3184 instantiations you need into one big file; or you can create small files
3191 template class Foo<int>;
3192 template ostream& operator <<
3193 (ostream&, const Foo<int>&);
3196 for each of the instances you need, and create a template instantiation
3199 If you are using Cfront-model code, you can probably get away with not
3200 using @samp{-fno-implicit-templates} when compiling files that don't
3201 @samp{#include} the member template definitions.
3203 If you use one big file to do the instantiations, you may want to
3204 compile it without @samp{-fno-implicit-templates} so you get all of the
3205 instances required by your explicit instantiations (but not by any
3206 other files) without having to specify them as well.
3208 g++ has extended the template instantiation syntax outlined in the
3209 Working Paper to allow forward declaration of explicit instantiations,
3210 explicit instantiation of members of template classes and instantiation
3211 of the compiler support data for a template class (i.e. the vtable)
3212 without instantiating any of its members:
3215 extern template int max (int, int);
3216 template void Foo<int>::f ();
3217 inline template class Foo<int>;
3221 Do nothing. Pretend g++ does implement automatic instantiation
3222 management. Code written for the Borland model will work fine, but
3223 each translation unit will contain instances of each of the templates it
3224 uses. In a large program, this can lead to an unacceptable amount of code
3228 Add @samp{#pragma interface} to all files containing template
3229 definitions. For each of these files, add @samp{#pragma implementation
3230 "@var{filename}"} to the top of some @samp{.C} file which
3231 @samp{#include}s it. Then compile everything with
3232 @samp{-fexternal-templates}. The templates will then only be expanded
3233 in the translation unit which implements them (i.e. has a @samp{#pragma
3234 implementation} line for the file where they live); all other files will
3235 use external references. If you're lucky, everything should work
3236 properly. If you get undefined symbol errors, you need to make sure
3237 that each template instance which is used in the program is used in the
3238 file which implements that template. If you don't have any use for a
3239 particular instance in that file, you can just instantiate it
3240 explicitly, using the syntax from the latest C++ working paper:
3243 template class A<int>;
3244 template ostream& operator << (ostream&, const A<int>&);
3247 This strategy will work with code written for either model. If you are
3248 using code written for the Cfront model, the file containing a class
3249 template and the file containing its member templates should be
3250 implemented in the same translation unit.
3252 A slight variation on this approach is to instead use the flag
3253 @samp{-falt-external-templates}; this flag causes template
3254 instances to be emitted in the translation unit that implements the
3255 header where they are first instantiated, rather than the one which
3256 implements the file where the templates are defined. This header must
3257 be the same in all translation units, or things are likely to break.
3259 @xref{C++ Interface,,Declarations and Definitions in One Header}, for
3260 more discussion of these pragmas.
3263 @node C++ Signatures
3264 @section Type Abstraction using Signatures
3267 @cindex type abstraction, C++
3268 @cindex C++ type abstraction
3269 @cindex subtype polymorphism, C++
3270 @cindex C++ subtype polymorphism
3271 @cindex signatures, C++
3272 @cindex C++ signatures
3274 In GNU C++, you can use the keyword @code{signature} to define a
3275 completely abstract class interface as a datatype. You can connect this
3276 abstraction with actual classes using signature pointers. If you want
3277 to use signatures, run the GNU compiler with the
3278 @samp{-fhandle-signatures} command-line option. (With this option, the
3279 compiler reserves a second keyword @code{sigof} as well, for a future
3282 Roughly, signatures are type abstractions or interfaces of classes.
3283 Some other languages have similar facilities. C++ signatures are
3284 related to ML's signatures, Haskell's type classes, definition modules
3285 in Modula-2, interface modules in Modula-3, abstract types in Emerald,
3286 type modules in Trellis/Owl, categories in Scratchpad II, and types in
3287 POOL-I. For a more detailed discussion of signatures, see
3288 @cite{Signatures: A Language Extension for Improving Type Abstraction and
3289 Subtype Polymorphism in C++}
3290 by @w{Gerald} Baumgartner and Vincent F. Russo (Tech report
3291 CSD--TR--95--051, Dept. of Computer Sciences, Purdue University,
3292 August 1995, a slightly improved version appeared in
3293 @emph{Software---Practice & Experience}, @b{25}(8), pp. 863--889,
3294 August 1995). You can get the tech report by anonymous FTP from
3295 @code{ftp.cs.purdue.edu} in @file{pub/gb/Signature-design.ps.gz}.
3297 Syntactically, a signature declaration is a collection of
3298 member function declarations and nested type declarations.
3299 For example, this signature declaration defines a new abstract type
3300 @code{S} with member functions @samp{int foo ()} and @samp{int bar (int)}:
3310 Since signature types do not include implementation definitions, you
3311 cannot write an instance of a signature directly. Instead, you can
3312 define a pointer to any class that contains the required interfaces as a
3313 @dfn{signature pointer}. Such a class @dfn{implements} the signature
3315 @c Eventually signature references should work too.
3317 To use a class as an implementation of @code{S}, you must ensure that
3318 the class has public member functions @samp{int foo ()} and @samp{int
3319 bar (int)}. The class can have other member functions as well, public
3320 or not; as long as it offers what's declared in the signature, it is
3321 suitable as an implementation of that signature type.
3323 For example, suppose that @code{C} is a class that meets the
3324 requirements of signature @code{S} (@code{C} @dfn{conforms to}
3333 defines a signature pointer @code{p} and initializes it to point to an
3334 object of type @code{C}.
3335 The member function call @w{@samp{int i = p->foo ();}}
3336 executes @samp{obj.foo ()}.
3338 @cindex @code{signature} in C++, advantages
3339 Abstract virtual classes provide somewhat similar facilities in standard
3340 C++. There are two main advantages to using signatures instead:
3344 Subtyping becomes independent from inheritance. A class or signature
3345 type @code{T} is a subtype of a signature type @code{S} independent of
3346 any inheritance hierarchy as long as all the member functions declared
3347 in @code{S} are also found in @code{T}. So you can define a subtype
3348 hierarchy that is completely independent from any inheritance
3349 (implementation) hierarchy, instead of being forced to use types that
3350 mirror the class inheritance hierarchy.
3353 Signatures allow you to work with existing class hierarchies as
3354 implementations of a signature type. If those class hierarchies are
3355 only available in compiled form, you're out of luck with abstract virtual
3356 classes, since an abstract virtual class cannot be retrofitted on top of
3357 existing class hierarchies. So you would be required to write interface
3358 classes as subtypes of the abstract virtual class.
3361 @cindex default implementation, signature member function
3362 @cindex signature member function default implementation
3363 There is one more detail about signatures. A signature declaration can
3364 contain member function @emph{definitions} as well as member function
3365 declarations. A signature member function with a full definition is
3366 called a @emph{default implementation}; classes need not contain that
3367 particular interface in order to conform. For example, a
3368 class @code{C} can conform to the signature
3374 int f0 () @{ return f (0); @};
3379 whether or not @code{C} implements the member function @samp{int f0 ()}.
3380 If you define @code{C::f0}, that definition takes precedence;
3381 otherwise, the default implementation @code{S::f0} applies.
3384 There will be more support for signatures in the future.
3385 Add to this doc as the implementation grows.
3386 In particular, the following features are planned but not yet
3389 @item signature references,
3390 @item signature inheritance,
3391 @item the @code{sigof} construct for extracting the signature information
3393 @item views for renaming member functions when matching a class type
3394 with a signature type,
3395 @item specifying exceptions with signature member functions, and
3396 @item signature templates.
3398 This list is roughly in the order in which we intend to implement
3399 them. Watch this space for updates.