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