Article View: pl.comp.objects
Article #5449Rozszerzenia GNU C++
From: Sektor van Skijlen
Date: Wed, 05 May 1999 12:53
Date: Wed, 05 May 1999 12:53
1334 lines
56870 bytes
56870 bytes
Jak to juz niektorzy zauwazyli, przez popularnosc gcc jest on sam sobie jakims
standardem. Warto sie zapoznac z jego rozszerzeniami. Z 'infor gcc'
wynotowalem najwazniejsze rozszerzenia, ktore sa dostepne dla C++, pominalem
jedynie informacje nt. slowa __atribute__. Jak mi sie kiedys zechce, to moze
to przetlumacze :*)). Jest to tez odrobine skrocone, mam jednak nadzieje, ze
nie bedzie stwarzac watpliwosci. Zatem, milej lektury.
Statements and Declarations in Expressions
==========================================
A compound statement enclosed in parentheses may appear as an
expression in GNU C. This allows you to use loops, switches, and local
variables within an expression.
Recall that a compound statement is a sequence of statements
surrounded by braces; in this construct, parentheses go around the
braces. For example:
({ int y = foo (); int z;
if (y > 0) z = y;
else z = - y;
z; })
is a valid (though slightly more complex than necessary) expression for
the absolute value of `foo ()'.
The last thing in the compound statement should be an expression
followed by a semicolon; the value of this subexpression serves as the
value of the entire construct. (If you use some other kind of statement
last within the braces, the construct has type `void', and thus
effectively no value.)
Locally Declared Labels
=======================
Each statement expression is a scope in which "local labels" can be
declared. A local label is simply an identifier; you can jump to it
with an ordinary `goto' statement, but only from within the statement
expression it belongs to.
A local label declaration looks like this:
__label__ LABEL;
or
__label__ LABEL1, LABEL2, ...;
Local label declarations must come at the beginning of the statement
expression, right after the `({', before any ordinary declarations.
The label declaration defines the label *name*, but does not define
the label itself. You must do this in the usual way, with `LABEL:',
within the statements of the statement expression.
Labels as Values
================
You can get the address of a label defined in the current function
(or a containing function) with the unary operator `&&'. The value has
type `void *'. This value is a constant and can be used wherever a
constant of that type is valid. For example:
void *ptr;
...
ptr = &&foo;
To use these values, you need to be able to jump to one. This is
done with the computed goto statement(1), `goto *EXP;'. For example,
goto *ptr;
Any expression of type `void *' is allowed.
Naming an Expression's Type
===========================
You can give a name to the type of an expression using a `typedef'
declaration with an initializer. Here is how to define NAME as a type
name for the type of EXP:
typedef NAME = EXP;
This is useful in conjunction with the statements-within-expressions
feature. Here is how the two together can be used to define a safe
"maximum" macro that operates on any arithmetic type:
#define max(a,b) \
({typedef _ta = (a), _tb = (b); \
_ta _a = (a); _tb _b = (b); \
_a > _b ? _a : _b; })
The reason for using names that start with underscores for the local
variables is to avoid conflicts with variable names that occur within
the expressions that are substituted for `a' and `b'. Eventually we
hope to design a new form of declaration syntax that allows you to
declare variables whose scopes start only after their initializers;
this will be a more reliable way to prevent such conflicts.
Referring to a Type with `typeof'
=================================
Another way to refer to the type of an expression is with `typeof'.
The syntax of using of this keyword looks like `sizeof', but the
construct acts semantically like a type name defined with `typedef'.
There are two ways of writing the argument to `typeof': with an
expression or with a type. Here is an example with an expression:
typeof (x[0](1))
This assumes that `x' is an array of functions; the type described is
that of the values of the functions.
Here is an example with a typename as the argument:
typeof (int *)
Here the type described is that of pointers to `int'.
A `typeof'-construct can be used anywhere a typedef name could be
used. For example, you can use it in a declaration, in a cast, or
inside of `sizeof' or `typeof'.
* This declares `y' with the type of what `x' points to.
typeof (*x) y;
* This declares `y' as an array of such values.
typeof (*x) y[4];
* This declares `y' as an array of pointers to characters:
typeof (typeof (char *)[4]) y;
It is equivalent to the following traditional C declaration:
char *y[4];
To see the meaning of the declaration using `typeof', and why it
might be a useful way to write, let's rewrite it with these macros:
#define pointer(T) typeof(T *)
#define array(T, N) typeof(T [N])
Now the declaration can be rewritten this way:
array (pointer (char), 4) y;
Thus, `array (pointer (char), 4)' is the type of arrays of 4
pointers to `char'.
Ode mnie drobna uwaga: typedef= i typeof wspomagaja glownie niedoskonalosc
makr #define i szczerze mowiac niewielkie widze tego ztosowanie w C++. Moze
jednak sie zdarzy jakas niedoskonalosc nawet szablonow, gdzie bedzie dobrze
tego uzyc (ciekawe, czy sie bedzie komponowac z typename :*)).
Conditionals with Omitted Operands
==================================
The middle operand in a conditional expression may be omitted. Then
if the first operand is nonzero, its value is the value of the
conditional expression.
Therefore, the expression
x ? : y
has the value of `x' if that is nonzero; otherwise, the value of `y'.
This example is perfectly equivalent to
x ? x : y
In this simple case, the ability to omit the middle operand is not
especially useful. When it becomes useful is when the first operand
does, or may (if it is a macro argument), contain a side effect. Then
repeating the operand in the middle would perform the side effect
twice. Omitting the middle operand uses the value already computed
without the undesirable effects of recomputing it.
Double-Word Integers
====================
GNU C supports data types for integers that are twice as long as
`int'. Simply write `long long int' for a signed integer, or `unsigned
long long int' for an unsigned integer. To make an integer constant of
type `long long int', add the suffix `LL' to the integer. To make an
integer constant of type `unsigned long long int', add the suffix `ULL'
to the integer.
Complex Numbers
===============
GNU C supports complex data types. You can declare both complex
integer types and complex floating types, using the keyword
`__complex__'.
For example, `__complex__ double x;' declares `x' as a variable
whose real part and imaginary part are both of type `double'.
`__complex__ short int y;' declares `y' to have real and imaginary
parts of type `short int'; this is not likely to be useful, but it
shows that the set of complex types is complete.
To write a constant with a complex data type, use the suffix `i' or
`j' (either one; they are equivalent). For example, `2.5fi' has type
`__complex__ float' and `3i' has type `__complex__ int'. Such a
constant always has a pure imaginary value, but you can form any
complex value you like by adding one to a real constant.
To extract the real part of a complex-valued expression EXP, write
`__real__ EXP'. Likewise, use `__imag__' to extract the imaginary part.
The operator `~' performs complex conjugation when used on a value
with a complex type.
GNU CC can allocate complex automatic variables in a noncontiguous
fashion; it's even possible for the real part to be in a register while
the imaginary part is on the stack (or vice-versa). None of the
supported debugging info formats has a way to represent noncontiguous
allocation like this, so GNU CC describes a noncontiguous complex
variable as if it were two separate variables of noncomplex type. If
the variable's actual name is `foo', the two fictitious variables are
named `foo$real' and `foo$imag'. You can examine and set these two
fictitious variables with your debugger.
A future version of GDB will know how to recognize such pairs and
treat them as a single variable with a complex type.
Arrays of Length Zero
=====================
Zero-length arrays are allowed in GNU C. They are very useful as
the last element of a structure which is really a header for a
variable-length object:
struct line {
int length;
char contents[0];
};
{
struct line *thisline = (struct line *)
malloc (sizeof (struct line) + this_length);
thisline->length = this_length;
}
In standard C, you would have to give `contents' a length of 1, which
means either you waste space or complicate the argument to `malloc'.
Arrays of Variable Length
=========================
Variable-length automatic arrays are allowed in GNU C. These arrays
are declared like any other automatic arrays, but with a length that is
not a constant expression. The storage is allocated at the point of
declaration and deallocated when the brace-level is exited. For
example:
FILE *
concat_fopen (char *s1, char *s2, char *mode)
{
char str[strlen (s1) + strlen (s2) + 1];
strcpy (str, s1);
strcat (str, s2);
return fopen (str, mode);
}
Jumping or breaking out of the scope of the array name deallocates
the storage. Jumping into the scope is not allowed; you get an error
message for it.
You can use the function `alloca' to get an effect much like
variable-length arrays. The function `alloca' is available in many
other C implementations (but not in all). On the other hand,
variable-length arrays are more elegant.
There are other differences between these two methods. Space
allocated with `alloca' exists until the containing *function* returns.
The space for a variable-length array is deallocated as soon as the
array name's scope ends. (If you use both variable-length arrays and
`alloca' in the same function, deallocation of a variable-length array
will also deallocate anything more recently allocated with `alloca'.)
You can also use variable-length arrays as arguments to functions:
struct entry
tester (int len, char data[len][len])
{
...
}
The length of an array is computed once when the storage is allocated
and is remembered for the scope of the array in case you access it with
`sizeof'.
If you want to pass the array first and the length afterward, you can
use a forward declaration in the parameter list--another GNU extension.
struct entry
tester (int len; char data[len][len], int len)
{
...
}
The `int len' before the semicolon is a "parameter forward
declaration", and it serves the purpose of making the name `len' known
when the declaration of `data' is parsed.
You can write any number of such parameter forward declarations in
the parameter list. They can be separated by commas or semicolons, but
the last one must end with a semicolon, which is followed by the "real"
parameter declarations. Each forward declaration must match a "real"
declaration in parameter name and data type.
Non-Lvalue Arrays May Have Subscripts
=====================================
Subscripting is allowed on arrays that are not lvalues, even though
the unary `&' operator is not. For example, this is valid in GNU C
though not valid in other C dialects:
struct foo {int a[4];};
struct foo f();
bar (int index)
{
return f().a[index];
}
Arithmetic on `void'- and Function-Pointers
===========================================
In GNU C, addition and subtraction operations are supported on
pointers to `void' and on pointers to functions. This is done by
treating the size of a `void' or of a function as 1.
A consequence of this is that `sizeof' is also allowed on `void' and
on function types, and returns 1.
The option `-Wpointer-arith' requests a warning if these extensions
are used.
Labeled Elements in Initializers
================================
Standard C requires the elements of an initializer to appear in a
fixed order, the same as the order of the elements in the array or
structure being initialized.
In GNU C you can give the elements in any order, specifying the array
indices or structure field names they apply to. This extension is not
implemented in GNU C++.
To specify an array index, write `[INDEX]' or `[INDEX] =' before the
element value. For example,
int a[6] = { [4] 29, [2] = 15 };
is equivalent to
int a[6] = { 0, 0, 15, 0, 29, 0 };
The index values must be constant expressions, even if the array being
initialized is automatic.
To initialize a range of elements to the same value, write `[FIRST
... LAST] = VALUE'. For example,
int widths[] = { [0 ... 9] = 1, [10 ... 99] = 2, [100] = 3 };
Note that the length of the array is the highest value specified plus
one.
In a structure initializer, specify the name of a field to initialize
with `FIELDNAME:' before the element value. For example, given the
following structure,
struct point { int x, y; };
the following initialization
struct point p = { y: yvalue, x: xvalue };
is equivalent to
struct point p = { xvalue, yvalue };
Another syntax which has the same meaning is `.FIELDNAME ='., as
shown here:
struct point p = { .y = yvalue, .x = xvalue };
You can also use an element label (with either the colon syntax or
the period-equal syntax) when initializing a union, to specify which
element of the union should be used. For example,
union foo { int i; double d; };
union foo f = { d: 4 };
will convert 4 to a `double' to store it in the union using the second
element. By contrast, casting 4 to type `union foo' would store it
into the union as the integer `i', since it is an integer. (*Note Cast
to Union::.)
You can combine this technique of naming elements with ordinary C
initialization of successive elements. Each initializer element that
does not have a label applies to the next consecutive element of the
array or structure. For example,
int a[6] = { [1] = v1, v2, [4] = v4 };
is equivalent to
int a[6] = { 0, v1, v2, 0, v4, 0 };
Labeling the elements of an array initializer is especially useful
when the indices are characters or belong to an `enum' type. For
example:
int whitespace[256]
= { [' '] = 1, ['\t'] = 1, ['\h'] = 1,
['\f'] = 1, ['\n'] = 1, ['\r'] = 1 };
Case Ranges
===========
You can specify a range of consecutive values in a single `case'
label, like this:
case LOW ... HIGH:
This has the same effect as the proper number of individual `case'
labels, one for each integer value from LOW to HIGH, inclusive.
This feature is especially useful for ranges of ASCII character
codes:
case 'A' ... 'Z':
*Be careful:* Write spaces around the `...', for otherwise it may be
parsed wrong when you use it with integer values. For example, write
this:
case 1 ... 5:
rather than this:
case 1...5:
Dollar Signs in Identifier Names
================================
The Character <ESC> in Constants
================================
You can use the sequence `\e' in a string or character constant to
stand for the ASCII character <ESC>.
Assembler Instructions with C Expression Operands
=================================================
In an assembler instruction using `asm', you can specify the
operands of the instruction using C expressions. This means you need
not guess which registers or memory locations will contain the data you
want to use.
You must specify an assembler instruction template much like what
appears in a machine description, plus an operand constraint string for
each operand.
For example, here is how to use the 68881's `fsinx' instruction:
asm ("fsinx %1,%0" : "=f" (result) : "f" (angle));
Here `angle' is the C expression for the input operand while `result'
is that of the output operand. Each has `"f"' as its operand
constraint, saying that a floating point register is required. The `='
in `=f' indicates that the operand is an output; all output operands'
constraints must use `='. The constraints use the same language used
in the machine description (*note Constraints::.).
Each operand is described by an operand-constraint string followed by
the C expression in parentheses. A colon separates the assembler
template from the first output operand and another separates the last
output operand from the first input, if any. Commas separate the
operands within each group. The total number of operands is limited to
ten or to the maximum number of operands in any instruction pattern in
the machine description, whichever is greater.
If there are no output operands but there are input operands, you
must place two consecutive colons surrounding the place where the output
operands would go.
Output operand expressions must be lvalues; the compiler can check
this. The input operands need not be lvalues. The compiler cannot
check whether the operands have data types that are reasonable for the
instruction being executed. It does not parse the assembler instruction
template and does not know what it means or even whether it is valid
assembler input. The extended `asm' feature is most often used for
machine instructions the compiler itself does not know exist. If the
output expression cannot be directly addressed (for example, it is a
bit field), your constraint must allow a register. In that case, GNU CC
will use the register as the output of the `asm', and then store that
register into the output.
The ordinary output operands must be write-only; GNU CC will assume
that the values in these operands before the instruction are dead and
need not be generated. Extended asm supports input-output or read-write
operands. Use the constraint character `+' to indicate such an operand
and list it with the output operands.
When the constraints for the read-write operand (or the operand in
which only some of the bits are to be changed) allows a register, you
may, as an alternative, logically split its function into two separate
operands, one input operand and one write-only output operand. The
connection between them is expressed by constraints which say they need
to be in the same location when the instruction executes. You can use
the same C expression for both operands, or different expressions. For
example, here we write the (fictitious) `combine' instruction with
`bar' as its read-only source operand and `foo' as its read-write
destination:
asm ("combine %2,%0" : "=r" (foo) : "0" (foo), "g" (bar));
The constraint `"0"' for operand 1 says that it must occupy the same
location as operand 0. A digit in constraint is allowed only in an
input operand and it must refer to an output operand.
Only a digit in the constraint can guarantee that one operand will
be in the same place as another. The mere fact that `foo' is the value
of both operands is not enough to guarantee that they will be in the
same place in the generated assembler code. The following would not
work reliably:
asm ("combine %2,%0" : "=r" (foo) : "r" (foo), "g" (bar));
Various optimizations or reloading could cause operands 0 and 1 to
be in different registers; GNU CC knows no reason not to do so. For
example, the compiler might find a copy of the value of `foo' in one
register and use it for operand 1, but generate the output operand 0 in
a different register (copying it afterward to `foo''s own address). Of
course, since the register for operand 1 is not even mentioned in the
assembler code, the result will not work, but GNU CC can't tell that.
Some instructions clobber specific hard registers. To describe this,
write a third colon after the input operands, followed by the names of
the clobbered hard registers (given as strings). Here is a realistic
example for the VAX:
asm volatile ("movc3 %0,%1,%2"
: /* no outputs */
: "g" (from), "g" (to), "g" (count)
: "r0", "r1", "r2", "r3", "r4", "r5");
If you refer to a particular hardware register from the assembler
code, you will probably have to list the register after the third colon
to tell the compiler the register's value is modified. In some
assemblers, the register names begin with `%'; to produce one `%' in the
assembler code, you must write `%%' in the input.
If your assembler instruction can alter the condition code register,
add `cc' to the list of clobbered registers. GNU CC on some machines
represents the condition codes as a specific hardware register; `cc'
serves to name this register. On other machines, the condition code is
handled differently, and specifying `cc' has no effect. But it is
valid no matter what the machine.
If your assembler instruction modifies memory in an unpredictable
fashion, add `memory' to the list of clobbered registers. This will
cause GNU CC to not keep memory values cached in registers across the
assembler instruction.
You can put multiple assembler instructions together in a single
`asm' template, separated either with newlines (written as `\n') or
with semicolons if the assembler allows such semicolons. The GNU
assembler allows semicolons and most Unix assemblers seem to do so.
The input operands are guaranteed not to use any of the clobbered
registers, and neither will the output operands' addresses, so you can
read and write the clobbered registers as many times as you like. Here
is an example of multiple instructions in a template; it assumes the
subroutine `_foo' accepts arguments in registers 9 and 10:
asm ("movl %0,r9;movl %1,r10;call _foo"
: /* no outputs */
: "g" (from), "g" (to)
: "r9", "r10");
Unless an output operand has the `&' constraint modifier, GNU CC may
allocate it in the same register as an unrelated input operand, on the
assumption the inputs are consumed before the outputs are produced.
This assumption may be false if the assembler code actually consists of
more than one instruction. In such a case, use `&' for each output
operand that may not overlap an input. *Note Modifiers::.
If you want to test the condition code produced by an assembler
instruction, you must include a branch and a label in the `asm'
construct, as follows:
asm ("clr %0;frob %1;beq 0f;mov #1,%0;0:"
: "g" (result)
: "g" (input));
This assumes your assembler supports local labels, as the GNU assembler
and most Unix assemblers do.
Speaking of labels, jumps from one `asm' to another are not
supported. The compiler's optimizers do not know about these jumps, and
therefore they cannot take account of them when deciding how to
optimize.
Usually the most convenient way to use these `asm' instructions is to
encapsulate them in macros that look like functions. For example,
#define sin(x) \
({ double __value, __arg = (x); \
asm ("fsinx %1,%0": "=f" (__value): "f" (__arg)); \
__value; })
Here the variable `__arg' is used to make sure that the instruction
operates on a proper `double' value, and to accept only those arguments
`x' which can convert automatically to a `double'.
Another way to make sure the instruction operates on the correct data
type is to use a cast in the `asm'. This is different from using a
variable `__arg' in that it converts more different types. For
example, if the desired type were `int', casting the argument to `int'
would accept a pointer with no complaint, while assigning the argument
to an `int' variable named `__arg' would warn about using a pointer
unless the caller explicitly casts it.
If an `asm' has output operands, GNU CC assumes for optimization
purposes the instruction has no side effects except to change the output
operands. This does not mean instructions with a side effect cannot be
used, but you must be careful, because the compiler may eliminate them
if the output operands aren't used, or move them out of loops, or
replace two with one if they constitute a common subexpression. Also,
if your instruction does have a side effect on a variable that otherwise
appears not to change, the old value of the variable may be reused later
if it happens to be found in a register.
You can prevent an `asm' instruction from being deleted, moved
significantly, or combined, by writing the keyword `volatile' after the
`asm'. For example:
#define get_and_set_priority(new) \
({ int __old; \
asm volatile ("get_and_set_priority %0, %1": "=g" (__old) : "g" (new)); \
__old; })
b
If you write an `asm' instruction with no outputs, GNU CC will know the
instruction has side-effects and will not delete the instruction or
move it outside of loops. If the side-effects of your instruction are
not purely external, but will affect variables in your program in ways
other than reading the inputs and clobbering the specified registers or
memory, you should write the `volatile' keyword to prevent future
versions of GNU CC from moving the instruction around within a core
region.
An `asm' instruction without any operands or clobbers (and "old
style" `asm') will not be deleted or moved significantly, regardless,
unless it is unreachable, the same wasy as if you had written a
`volatile' keyword.
Note that even a volatile `asm' instruction can be moved in ways
that appear insignificant to the compiler, such as across jump
instructions. You can't expect a sequence of volatile `asm'
instructions to remain perfectly consecutive. If you want consecutive
output, use a single `asm'.
It is a natural idea to look for a way to give access to the
condition code left by the assembler instruction. However, when we
attempted to implement this, we found no way to make it work reliably.
The problem is that output operands might need reloading, which would
result in additional following "store" instructions. On most machines,
these instructions would alter the condition code before there was time
to test it. This problem doesn't arise for ordinary "test" and
"compare" instructions because they don't have any output operands.
Definig Variables in Specified Registers
================================
GNU C allows you to put a few global variables into specified
hardware registers. You can also specify the register in which an
ordinary register variable should be allocated.
* Global register variables reserve registers throughout the program.
This may be useful in programs such as programming language
interpreters which have a couple of global variables that are
accessed very often.
* Local register variables in specific registers do not reserve the
registers. The compiler's data flow analysis is capable of
determining where the specified registers contain live values, and
where they are available for other uses.
Defining Global Register Variables
----------------------------------
You can define a global register variable in GNU C like this:
register int *foo asm ("a5");
Here `a5' is the name of the register which should be used. Choose a
register which is normally saved and restored by function calls on your
machine, so that library routines will not clobber it.
Naturally the register name is cpu-dependent, so you would need to
conditionalize your program according to cpu type. The register `a5'
would be a good choice on a 68000 for a variable of pointer type. On
machines with register windows, be sure to choose a "global" register
that is not affected magically by the function call mechanism.
In addition, operating systems on one type of cpu may differ in how
they name the registers; then you would need additional conditionals.
For example, some 68000 operating systems call this register `%a5'.
Eventually there may be a way of asking the compiler to choose a
register automatically, but first we need to figure out how it should
choose and how to enable you to guide the choice. No solution is
evident.
Global register variables may not have initial values, because an
executable file has no means to supply initial contents for a register.
On the Sparc, there are reports that g3 ... g7 are suitable
registers, but certain library functions, such as `getwd', as well as
the subroutines for division and remainder, modify g3 and g4. g1 and
g2 are local temporaries.
On the 68000, a2 ... a5 should be suitable, as should d2 ... d7. Of
course, it will not do to use more than a few of those.
Specifying Registers for Local Variables
----------------------------------------
You can define a local register variable with a specified register
like above.
Defining such a register variable does not reserve the register; it
remains available for other uses in places where flow control determines
the variable's value is not live. However, these registers are made
unavailable for use in the reload pass; excessive use of this feature
leaves the compiler too few available registers to compile certain
functions.
This option does not guarantee that GNU CC will generate code that
has this variable in the register you specify at all times. You may not
code an explicit reference to this register in an `asm' statement and
assume it will always refer to this variable.
Function Names as Strings
=========================
GNU CC predefines two string variables to be the name of the current
function. The variable `__FUNCTION__' is the name of the function as
it appears in the source. The variable `__PRETTY_FUNCTION__' is the
name of the function pretty printed in a language specific fashion.
These names are always the same in a C function, but in a C++
function they may be different. For example, this program:
extern "C" {
extern int printf (char *, ...);
}
class a {
public:
sub (int i)
{
printf ("__FUNCTION__ = %s\n", __FUNCTION__);
printf ("__PRETTY_FUNCTION__ = %s\n", __PRETTY_FUNCTION__);
}
};
int
main (void)
{
a ax;
ax.sub (0);
return 0;
}
gives this output:
__FUNCTION__ = sub
__PRETTY_FUNCTION__ = int a::sub (int)
These names are not macros: they are predefined string variables.
For example, `#ifdef __FUNCTION__' does not have any special meaning
inside a function, since the preprocessor does not do anything special
with the identifier `__FUNCTION__'.
Getting the Return or Frame Address of a Function
=================================================
These functions may be used to get information about the callers of a
function.
`__builtin_return_address (LEVEL)'
This function returns the return address of the current function,
or of one of its callers. The LEVEL argument is number of frames
to scan up the call stack. A value of `0' yields the return
address of the current function, a value of `1' yields the return
address of the caller of the current function, and so forth.
The LEVEL argument must be a constant integer.
On some machines it may be impossible to determine the return
address of any function other than the current one; in such cases,
or when the top of the stack has been reached, this function will
return `0'.
This function should only be used with a non-zero argument for
debugging purposes.
`__builtin_frame_address (LEVEL)'
This function is similar to `__builtin_return_address', but it
returns the address of the function frame rather than the return
address of the function. Calling `__builtin_frame_address' with a
value of `0' yields the frame address of the current function, a
value of `1' yields the frame address of the caller of the current
function, and so forth.
The frame is the area on the stack which holds local variables and
saved registers. The frame address is normally the address of the
first word pushed on to the stack by the function. However, the
exact definition depends upon the processor and the calling
convention. If the processor has a dedicated frame pointer
register, and the function has a frame, then
`__builtin_frame_address' will return the value of the frame
pointer register.
The caveats that apply to `__builtin_return_address' apply to this
function as well.
Named Return Values in C++
==========================
GNU C++ extends the function-definition syntax to allow you to
specify a name for the result of a function outside the body of the
definition, in C++ programs:
TYPE
FUNCTIONNAME (ARGS) return RESULTNAME;
{
...
BODY
...
}
You can use this feature to avoid an extra constructor call when a
function result has a class type. For example, consider a function
`m', declared as `X v = m ();', whose result is of class `X':
X
m ()
{
X b;
b.a = 23;
return b;
}
Although `m' appears to have no arguments, in fact it has one
implicit argument: the address of the return value. At invocation, the
address of enough space to hold `v' is sent in as the implicit argument.
Then `b' is constructed and its `a' field is set to the value 23.
Finally, a copy constructor (a constructor of the form `X(X&)') is
applied to `b', with the (implicit) return value location as the
target, so that `v' is now bound to the return value.
But this is wasteful. The local `b' is declared just to hold
something that will be copied right out. While a compiler that
combined an "elision" algorithm with interprocedural data flow analysis
could conceivably eliminate all of this, it is much more practical to
allow you to assist the compiler in generating efficient code by
manipulating the return value explicitly, thus avoiding the local
variable and copy constructor altogether.
Using the extended GNU C++ function-definition syntax, you can avoid
the temporary allocation and copying by naming `r' as your return value
at the outset, and assigning to its `a' field directly:
X
m () return r;
{
r.a = 23;
}
The declaration of `r' is a standard, proper declaration, whose effects
are executed *before* any of the body of `m'.
Functions of this type impose no additional restrictions; in
particular, you can execute `return' statements, or return implicitly by
reaching the end of the function body ("falling off the edge"). Cases
like
X
m () return r (23);
{
return;
}
(or even `X m () return r (23); { }') are unambiguous, since the return
value `r' has been initialized in either case. The following code may
be hard to read, but also works predictably:
X
m () return r;
{
X b;
return b;
}
The return value slot denoted by `r' is initialized at the outset,
but the statement `return b;' overrides this value. The compiler deals
with this by destroying `r' (calling the destructor if there is one, or
doing nothing if there is not), and then reinitializing `r' with `b'.
This extension is provided primarily to help people who use
overloaded operators, where there is a great need to control not just
the arguments, but the return values of functions. For classes where
the copy constructor incurs a heavy performance penalty (especially in
the common case where there is a quick default constructor), this is a
major savings. The disadvantage of this extension is that you do not
control when the default constructor for the return value is called: it
is always called at the beginning.
Minimum and Maximum Operators in C++
====================================
It is very convenient to have operators which return the "minimum"
or the "maximum" of two arguments. In GNU C++ (but not in GNU C),
`A <? B'
is the "minimum", returning the smaller of the numeric values A
and B;
`A >? B'
is the "maximum", returning the larger of the numeric values A and
B.
These operations are not primitive in ordinary C++, since you can
use a macro to return the minimum of two things in C++, as in the
following example.
#define MIN(X,Y) ((X) < (Y) ? : (X) : (Y))
You might then use `int min = MIN (i, j);' to set MIN to the minimum
value of variables I and J.
However, side effects in `X' or `Y' may cause unintended behavior.
For example, `MIN (i++, j++)' will fail, incrementing the smaller
counter twice. A GNU C extension allows you to write safe macros that
avoid this kind of problem (*note Naming an Expression's Type: Naming
Types.). However, writing `MIN' and `MAX' as macros also forces you to
use function-call notation for a fundamental arithmetic operation.
Using GNU C++ extensions, you can write `int min = i <? j;' instead.
Since `<?' and `>?' are built into the compiler, they properly
handle expressions with side-effects; `int min = i++ <? j++;' works
correctly.
`goto' and Destructors in GNU C++
=================================
In C++ programs, you can safely use the `goto' statement. When you
use it to exit a block which contains aggregates requiring destructors,
the destructors will run before the `goto' transfers control.
The compiler still forbids using `goto' to *enter* a scope that
requires constructors.
Declarations and Definitions in One Header
==========================================
C++ object definitions can be quite complex. In principle, your
source code will need two kinds of things for each object that you use
across more than one source file. First, you need an "interface"
specification, describing its structure with type declarations and
function prototypes. Second, you need the "implementation" itself. It
can be tedious to maintain a separate interface description in a header
file, in parallel to the actual implementation. It is also dangerous,
since separate interface and implementation definitions may not remain
parallel.
With GNU C++, you can use a single header file for both purposes.
*Warning:* The mechanism to specify this is in transition. For the
nonce, you must use one of two `#pragma' commands; in a future
release of GNU C++, an alternative mechanism will make these
`#pragma' commands unnecessary.
The header file contains the full definitions, but is marked with
`#pragma interface' in the source code. This allows the compiler to
use the header file only as an interface specification when ordinary
source files incorporate it with `#include'. In the single source file
where the full implementation belongs, you can use either a naming
convention or `#pragma implementation' to indicate this alternate use
of the header file.
`#pragma interface'
`#pragma interface "SUBDIR/OBJECTS.h"'
Use this directive in *header files* that define object classes,
to save space in most of the object files that use those classes.
Normally, local copies of certain information (backup copies of
inline member functions, debugging information, and the internal
tables that implement virtual functions) must be kept in each
object file that includes class definitions. You can use this
pragma to avoid such duplication. When a header file containing
`#pragma interface' is included in a compilation, this auxiliary
information will not be generated (unless the main input source
file itself uses `#pragma implementation'). Instead, the object
files will contain references to be resolved at link time.
The second form of this directive is useful for the case where you
have multiple headers with the same name in different directories.
If you use this form, you must specify the same string to `#pragma
implementation'.
`#pragma implementation'
`#pragma implementation "OBJECTS.h"'
Use this pragma in a *main input file*, when you want full output
from included header files to be generated (and made globally
visible). The included header file, in turn, should use `#pragma
interface'. Backup copies of inline member functions, debugging
information, and the internal tables used to implement virtual
functions are all generated in implementation files.
If you use `#pragma implementation' with no argument, it applies to
an include file with the same basename(1) as your source file.
For example, in `allclass.cc', giving just `#pragma implementation'
by itself is equivalent to `#pragma implementation "allclass.h"'.
In versions of GNU C++ prior to 2.6.0 `allclass.h' was treated as
an implementation file whenever you would include it from
`allclass.cc' even if you never specified `#pragma
implementation'. This was deemed to be more trouble than it was
worth, however, and disabled.
If you use an explicit `#pragma implementation', it must appear in
your source file *before* you include the affected header files.
Use the string argument if you want a single implementation file to
include code from multiple header files. (You must also use
`#include' to include the header file; `#pragma implementation'
only specifies how to use the file--it doesn't actually include
it.)
There is no way to split up the contents of a single header file
into multiple implementation files.
`#pragma implementation' and `#pragma interface' also have an effect
on function inlining.
If you define a class in a header file marked with `#pragma
interface', the effect on a function defined in that class is similar to
an explicit `extern' declaration--the compiler emits no code at all to
define an independent version of the function. Its definition is used
only for inlining with its callers.
Conversely, when you include the same header file in a main source
file that declares it as `#pragma implementation', the compiler emits
code for the function itself; this defines a version of the function
that can be found via pointers (or by callers compiled without
inlining). If all calls to the function can be inlined, you can avoid
emitting the function by compiling with `-fno-implement-inlines'. If
any calls were not inlined, you will get linker errors.
---------- Footnotes ----------
(1) A file's "basename" was the name stripped of all leading path
information and of trailing suffixes, such as `.h' or `.C' or `.cc'.
Where's the Template?
=====================
C++ templates are the first language feature to require more
intelligence from the environment than one usually finds on a UNIX
system. Somehow the compiler and linker have to make sure that each
template instance occurs exactly once in the executable if it is needed,
and not at all otherwise. There are two basic approaches to this
problem, which I will refer to as the Borland model and the Cfront
model.
Borland model
Borland C++ solved the template instantiation problem by adding
the code equivalent of common blocks to their linker; the compiler
emits template instances in each translation unit that uses them,
and the linker collapses them together. The advantage of this
model is that the linker only has to consider the object files
themselves; there is no external complexity to worry about. This
disadvantage is that compilation time is increased because the
template code is being compiled repeatedly. Code written for this
model tends to include definitions of all templates in the header
file, since they must be seen to be instantiated.
Cfront model
The AT&T C++ translator, Cfront, solved the template instantiation
problem by creating the notion of a template repository, an
automatically maintained place where template instances are
stored. A more modern version of the repository works as follows:
As individual object files are built, the compiler places any
template definitions and instantiations encountered in the
repository. At link time, the link wrapper adds in the objects in
the repository and compiles any needed instances that were not
previously emitted. The advantages of this model are more optimal
compilation speed and the ability to use the system linker; to
implement the Borland model a compiler vendor also needs to
replace the linker. The disadvantages are vastly increased
complexity, and thus potential for error; for some code this can be
just as transparent, but in practice it can been very difficult to
build multiple programs in one directory and one program in
multiple directories. Code written for this model tends to
separate definitions of non-inline member templates into a
separate file, which should be compiled separately.
When used with GNU ld version 2.8 or later on an ELF system such as
Linux/GNU or Solaris 2, or on Microsoft Windows, g++ supports the
Borland model. On other systems, g++ implements neither automatic
model.
A future version of g++ will support a hybrid model whereby the
compiler will emit any instantiations for which the template definition
is included in the compile, and store template definitions and
instantiation context information into the object file for the rest.
The link wrapper will extract that information as necessary and invoke
the compiler to produce the remaining instantiations. The linker will
then combine duplicate instantiations.
In the mean time, you have the following options for dealing with
template instantiations:
1. Compile your code with `-fno-implicit-templates' to disable the
implicit generation of template instances, and explicitly
instantiate all the ones you use. This approach requires more
knowledge of exactly which instances you need than do the others,
but it's less mysterious and allows greater control. You can
scatter the explicit instantiations throughout your program,
perhaps putting them in the translation units where the instances
are used or the translation units that define the templates
themselves; you can put all of the explicit instantiations you
need into one big file; or you can create small files like
#include "Foo.h"
#include "Foo.cc"
template class Foo<int>;
template ostream& operator <<
(ostream&, const Foo<int>&);
for each of the instances you need, and create a template
instantiation library from those.
If you are using Cfront-model code, you can probably get away with
not using `-fno-implicit-templates' when compiling files that don't
`#include' the member template definitions.
If you use one big file to do the instantiations, you may want to
compile it without `-fno-implicit-templates' so you get all of the
instances required by your explicit instantiations (but not by any
other files) without having to specify them as well.
g++ has extended the template instantiation syntax outlined in the
Working Paper to allow forward declaration of explicit
instantiations, explicit instantiation of members of template
classes and instantiation of the compiler support data for a
template class (i.e. the vtable) without instantiating any of its
members:
extern template int max (int, int);
template void Foo<int>::f ();
inline template class Foo<int>;
2. Do nothing. Pretend g++ does implement automatic instantiation
management. Code written for the Borland model will work fine, but
each translation unit will contain instances of each of the
templates it uses. In a large program, this can lead to an
unacceptable amount of code duplication.
3. Add `#pragma interface' to all files containing template
definitions. For each of these files, add `#pragma implementation
"FILENAME"' to the top of some `.C' file which `#include's it.
Then compile everything with `-fexternal-templates'. The
templates will then only be expanded in the translation unit which
implements them (i.e. has a `#pragma implementation' line for the
file where they live); all other files will use external
references. If you're lucky, everything should work properly. If
you get undefined symbol errors, you need to make sure that each
template instance which is used in the program is used in the file
which implements that template. If you don't have any use for a
particular instance in that file, you can just instantiate it
explicitly, using the syntax from the latest C++ working paper:
template class A<int>;
template ostream& operator << (ostream&, const A<int>&);
This strategy will work with code written for either model. If
you are using code written for the Cfront model, the file
containing a class template and the file containing its member
templates should be implemented in the same translation unit.
A slight variation on this approach is to instead use the flag
`-falt-external-templates'; this flag causes template instances to
be emitted in the translation unit that implements the header
where they are first instantiated, rather than the one which
implements the file where the templates are defined. This header
must be the same in all translation units, or things are likely to
break.
*Note Declarations and Definitions in One Header: C++ Interface,
for more discussion of these pragmas.
Type Abstraction using Signatures
=================================
In GNU C++, you can use the keyword `signature' to define a
completely abstract class interface as a datatype. You can connect this
abstraction with actual classes using signature pointers. If you want
to use signatures, run the GNU compiler with the `-fhandle-signatures'
command-line option. (With this option, the compiler reserves a second
keyword `sigof' as well, for a future extension.)
Roughly, signatures are type abstractions or interfaces of classes.
Some other languages have similar facilities. C++ signatures are
related to ML's signatures, Haskell's type classes, definition modules
in Modula-2, interface modules in Modula-3, abstract types in Emerald,
type modules in Trellis/Owl, categories in Scratchpad II, and types in
POOL-I. For a more detailed discussion of signatures, see `Signatures:
A Language Extension for Improving Type Abstraction and Subtype
Polymorphism in C++' by Gerald Baumgartner and Vincent F. Russo (Tech
report CSD-TR-95-051, Dept. of Computer Sciences, Purdue University,
August 1995, a slightly improved version appeared in
*Software--Practice & Experience*, 25(8), pp. 863-889, August 1995).
You can get the tech report by anonymous FTP from `ftp.cs.purdue.edu'
in `pub/gb/Signature-design.ps.gz'.
Syntactically, a signature declaration is a collection of member
function declarations and nested type declarations. For example, this
signature declaration defines a new abstract type `S' with member
functions `int foo ()' and `int bar (int)':
signature S
{
int foo ();
int bar (int);
};
Since signature types do not include implementation definitions, you
cannot write an instance of a signature directly. Instead, you can
define a pointer to any class that contains the required interfaces as a
"signature pointer". Such a class "implements" the signature type.
To use a class as an implementation of `S', you must ensure that the
class has public member functions `int foo ()' and `int bar (int)'.
The class can have other member functions as well, public or not; as
long as it offers what's declared in the signature, it is suitable as
an implementation of that signature type.
For example, suppose that `C' is a class that meets the requirements
of signature `S' (`C' "conforms to" `S'). Then
C obj;
S * p = &obj;
defines a signature pointer `p' and initializes it to point to an
object of type `C'. The member function call `int i = p->foo ();'
executes `obj.foo ()'.
Abstract virtual classes provide somewhat similar facilities in
standard C++. There are two main advantages to using signatures
instead:
1. Subtyping becomes independent from inheritance. A class or
signature type `T' is a subtype of a signature type `S'
independent of any inheritance hierarchy as long as all the member
functions declared in `S' are also found in `T'. So you can
define a subtype hierarchy that is completely independent from any
inheritance (implementation) hierarchy, instead of being forced to
use types that mirror the class inheritance hierarchy.
2. Signatures allow you to work with existing class hierarchies as
implementations of a signature type. If those class hierarchies
are only available in compiled form, you're out of luck with
abstract virtual classes, since an abstract virtual class cannot
be retrofitted on top of existing class hierarchies. So you would
be required to write interface classes as subtypes of the abstract
virtual class.
There is one more detail about signatures. A signature declaration
can contain member function *definitions* as well as member function
declarations. A signature member function with a full definition is
called a *default implementation*; classes need not contain that
particular interface in order to conform. For example, a class `C' can
conform to the signature
signature T
{
int f (int);
int f0 () { return f (0); };
};
whether or not `C' implements the member function `int f0 ()'. If you
define `C::f0', that definition takes precedence; otherwise, the
default implementation `S::f0' applies.
--
*Kazdy Ci moze powiedziec, co nalezy czuc.* % Michal Malecki
*Ale tylko Ty wiesz, co nalezy myslec.* %Politechnika Lodzka, Et/Inf
*Ainpern kaen dijkten ta Dij, waet als solt fuelen.* % Sektor van Skijlen
*Aver ijnna Tue kaanst, waet als solt daanken.* % <sektor@fnet.pl>
Technical Details
Message-ID:
<7gpf10$67b$1@ra.man.lodz.pl>Path:
mbox-mo1.pugleaf.net!news-archive.icm.edu.pl!pingwin.icm.edu.pl!mat.uni.torun.pl!uw.edu.pl!news.swierk.pl!news.icm.edu.pl!news.task.gda.pl!news.man.lodz.pl!not-for-mailShow Full Headers
Complete Article Headers
Path: mbox-mo1.pugleaf.net!news-archive.icm.edu.pl!pingwin.icm.edu.pl!mat.uni.torun.pl!uw.edu.pl!news.swierk.pl!news.icm.edu.pl!news.task.gda.pl!news.man.lodz.pl!not-for-mail
From: Sektor van Skijlen <sektor@spam.org>
Newsgroups: pl.comp.lang.c,pl.comp.objects
Subject: Rozszerzenia GNU C++
Date: 5 May 1999 12:53:52 GMT
Organization: LODMAN - Metropolitan Area Network in LODZ
Lines: 1334
Distribution: pl
Message-ID: <7gpf10$67b$1@ra.man.lodz.pl>
NNTP-Posting-Host: zly.kis.p.lodz.pl
X-Trace: ra.man.lodz.pl 925908832 6379 212.51.216.2 (5 May 1999 12:53:52 GMT)
X-Complaints-To: abuse@man.lodz.pl
NNTP-Posting-Date: 5 May 1999 12:53:52 GMT
Keywords: GNU C++
User-Agent: tin/pre-1.4-19990413 ("Endemoniada") (UNIX) (SunOS/5.6 (i86pc))
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 7bit