source: trunk/third/gcc/gcc.info-8 @ 8834

Revision 8834, 48.7 KB checked in by ghudson, 28 years ago (diff)
This commit was generated by cvs2svn to compensate for changes in r8833, which included commits to RCS files with non-trunk default branches.
Line 
1This is Info file gcc.info, produced by Makeinfo-1.55 from the input
2file gcc.texi.
3
4   This file documents the use and the internals of the GNU compiler.
5
6   Published by the Free Software Foundation 59 Temple Place - Suite 330
7Boston, MA 02111-1307 USA
8
9   Copyright (C) 1988, 1989, 1992, 1993, 1994, 1995 Free Software
10Foundation, Inc.
11
12   Permission is granted to make and distribute verbatim copies of this
13manual provided the copyright notice and this permission notice are
14preserved on all copies.
15
16   Permission is granted to copy and distribute modified versions of
17this manual under the conditions for verbatim copying, provided also
18that the sections entitled "GNU General Public License," "Funding for
19Free Software," and "Protect Your Freedom--Fight `Look And Feel'" are
20included exactly as in the original, and provided that the entire
21resulting derived work is distributed under the terms of a permission
22notice identical to this one.
23
24   Permission is granted to copy and distribute translations of this
25manual into another language, under the above conditions for modified
26versions, except that the sections entitled "GNU General Public
27License," "Funding for Free Software," and "Protect Your Freedom--Fight
28`Look And Feel'", and this permission notice, may be included in
29translations approved by the Free Software Foundation instead of in the
30original English.
31
32
33File: gcc.info,  Node: Build Cross,  Prev: Cross Runtime,  Up: Cross-Compiler
34
35Actually Building the Cross-Compiler
36------------------------------------
37
38   Now you can proceed just as for compiling a single-machine compiler
39through the step of building stage 1.  If you have not provided some
40sort of `libgcc1.a', then compilation will give up at the point where
41it needs that file, printing a suitable error message.  If you do
42provide `libgcc1.a', then building the compiler will automatically
43compile and link a test program called `libgcc1-test'; if you get
44errors in the linking, it means that not all of the necessary routines
45in `libgcc1.a' are available.
46
47   You must provide the header file `float.h'.  One way to do this is
48to compile `enquire' and run it on your target machine.  The job of
49`enquire' is to run on the target machine and figure out by experiment
50the nature of its floating point representation.  `enquire' records its
51findings in the header file `float.h'.  If you can't produce this file
52by running `enquire' on the target machine, then you will need to come
53up with a suitable `float.h' in some other way (or else, avoid using it
54in your programs).
55
56   Do not try to build stage 2 for a cross-compiler.  It doesn't work to
57rebuild GNU CC as a cross-compiler using the cross-compiler, because
58that would produce a program that runs on the target machine, not on the
59host.  For example, if you compile a 386-to-68030 cross-compiler with
60itself, the result will not be right either for the 386 (because it was
61compiled into 68030 code) or for the 68030 (because it was configured
62for a 386 as the host).  If you want to compile GNU CC into 68030 code,
63whether you compile it on a 68030 or with a cross-compiler on a 386, you
64must specify a 68030 as the host when you configure it.
65
66   To install the cross-compiler, use `make install', as usual.
67
68
69File: gcc.info,  Node: Sun Install,  Next: VMS Install,  Prev: Cross-Compiler,  Up: Installation
70
71Installing GNU CC on the Sun
72============================
73
74   On Solaris (version 2.1), do not use the linker or other tools in
75`/usr/ucb' to build GNU CC.  Use `/usr/ccs/bin'.
76
77   Make sure the environment variable `FLOAT_OPTION' is not set when
78you compile `libgcc.a'.  If this option were set to `f68881' when
79`libgcc.a' is compiled, the resulting code would demand to be linked
80with a special startup file and would not link properly without special
81pains.
82
83   There is a bug in `alloca' in certain versions of the Sun library.
84To avoid this bug, install the binaries of GNU CC that were compiled by
85GNU CC.  They use `alloca' as a built-in function and never the one in
86the library.
87
88   Some versions of the Sun compiler crash when compiling GNU CC.  The
89problem is a segmentation fault in cpp.  This problem seems to be due to
90the bulk of data in the environment variables.  You may be able to avoid
91it by using the following command to compile GNU CC with Sun CC:
92
93     make CC="TERMCAP=x OBJS=x LIBFUNCS=x STAGESTUFF=x cc"
94
95
96File: gcc.info,  Node: VMS Install,  Next: Collect2,  Prev: Sun Install,  Up: Installation
97
98Installing GNU CC on VMS
99========================
100
101   The VMS version of GNU CC is distributed in a backup saveset
102containing both source code and precompiled binaries.
103
104   To install the `gcc' command so you can use the compiler easily, in
105the same manner as you use the VMS C compiler, you must install the VMS
106CLD file for GNU CC as follows:
107
108  1. Define the VMS logical names `GNU_CC' and `GNU_CC_INCLUDE' to
109     point to the directories where the GNU CC executables
110     (`gcc-cpp.exe', `gcc-cc1.exe', etc.) and the C include files are
111     kept respectively.  This should be done with the commands:
112
113          $ assign /system /translation=concealed -
114            disk:[gcc.] gnu_cc
115          $ assign /system /translation=concealed -
116            disk:[gcc.include.] gnu_cc_include
117
118     with the appropriate disk and directory names.  These commands can
119     be placed in your system startup file so they will be executed
120     whenever the machine is rebooted.  You may, if you choose, do this
121     via the `GCC_INSTALL.COM' script in the `[GCC]' directory.
122
123  2. Install the `GCC' command with the command line:
124
125          $ set command /table=sys$common:[syslib]dcltables -
126            /output=sys$common:[syslib]dcltables gnu_cc:[000000]gcc
127          $ install replace sys$common:[syslib]dcltables
128
129  3. To install the help file, do the following:
130
131          $ library/help sys$library:helplib.hlb gcc.hlp
132
133     Now you can invoke the compiler with a command like `gcc /verbose
134     file.c', which is equivalent to the command `gcc -v -c file.c' in
135     Unix.
136
137   If you wish to use GNU C++ you must first install GNU CC, and then
138perform the following steps:
139
140  1. Define the VMS logical name `GNU_GXX_INCLUDE' to point to the
141     directory where the preprocessor will search for the C++ header
142     files.  This can be done with the command:
143
144          $ assign /system /translation=concealed -
145            disk:[gcc.gxx_include.] gnu_gxx_include
146
147     with the appropriate disk and directory name.  If you are going to
148     be using libg++, this is where the libg++ install procedure will
149     install the libg++ header files.
150
151  2. Obtain the file `gcc-cc1plus.exe', and place this in the same
152     directory that `gcc-cc1.exe' is kept.
153
154     The GNU C++ compiler can be invoked with a command like `gcc /plus
155     /verbose file.cc', which is equivalent to the command `g++ -v -c
156     file.cc' in Unix.
157
158   We try to put corresponding binaries and sources on the VMS
159distribution tape.  But sometimes the binaries will be from an older
160version than the sources, because we don't always have time to update
161them.  (Use the `/version' option to determine the version number of
162the binaries and compare it with the source file `version.c' to tell
163whether this is so.)  In this case, you should use the binaries you get
164to recompile the sources.  If you must recompile, here is how:
165
166  1. Execute the command procedure `vmsconfig.com' to set up the files
167     `tm.h', `config.h', `aux-output.c', and `md.', and to create files
168     `tconfig.h' and `hconfig.h'.  This procedure also creates several
169     linker option files used by `make-cc1.com' and a data file used by
170     `make-l2.com'.
171
172          $ @vmsconfig.com
173
174  2. Setup the logical names and command tables as defined above.  In
175     addition, define the VMS logical name `GNU_BISON' to point at the
176     to the directories where the Bison executable is kept.  This
177     should be done with the command:
178
179          $ assign /system /translation=concealed -
180            disk:[bison.] gnu_bison
181
182     You may, if you choose, use the `INSTALL_BISON.COM' script in the
183     `[BISON]' directory.
184
185  3. Install the `BISON' command with the command line:
186
187          $ set command /table=sys$common:[syslib]dcltables -
188            /output=sys$common:[syslib]dcltables -
189            gnu_bison:[000000]bison
190          $ install replace sys$common:[syslib]dcltables
191
192  4. Type `@make-gcc' to recompile everything (alternatively, submit
193     the file `make-gcc.com' to a batch queue).  If you wish to build
194     the GNU C++ compiler as well as the GNU CC compiler, you must
195     first edit `make-gcc.com' and follow the instructions that appear
196     in the comments.
197
198  5. In order to use GCC, you need a library of functions which GCC
199     compiled code will call to perform certain tasks, and these
200     functions are defined in the file `libgcc2.c'.  To compile this
201     you should use the command procedure `make-l2.com', which will
202     generate the library `libgcc2.olb'.  `libgcc2.olb' should be built
203     using the compiler built from the same distribution that
204     `libgcc2.c' came from, and `make-gcc.com' will automatically do
205     all of this for you.
206
207     To install the library, use the following commands:
208
209          $ library gnu_cc:[000000]gcclib/delete=(new,eprintf)
210          $ library gnu_cc:[000000]gcclib/delete=L_*
211          $ library libgcc2/extract=*/output=libgcc2.obj
212          $ library gnu_cc:[000000]gcclib libgcc2.obj
213
214     The first command simply removes old modules that will be replaced
215     with modules from `libgcc2' under different module names.  The
216     modules `new' and `eprintf' may not actually be present in your
217     `gcclib.olb'--if the VMS librarian complains about those modules
218     not being present, simply ignore the message and continue on with
219     the next command.  The second command removes the modules that
220     came from the previous version of the library `libgcc2.c'.
221
222     Whenever you update the compiler on your system, you should also
223     update the library with the above procedure.
224
225  6. You may wish to build GCC in such a way that no files are written
226     to the directory where the source files reside.  An example would
227     be the when the source files are on a read-only disk.  In these
228     cases, execute the following DCL commands (substituting your
229     actual path names):
230
231          $ assign dua0:[gcc.build_dir.]/translation=concealed, -
232                   dua1:[gcc.source_dir.]/translation=concealed  gcc_build
233          $ set default gcc_build:[000000]
234
235     where the directory `dua1:[gcc.source_dir]' contains the source
236     code, and the directory `dua0:[gcc.build_dir]' is meant to contain
237     all of the generated object files and executables.  Once you have
238     done this, you can proceed building GCC as described above.  (Keep
239     in mind that `gcc_build' is a rooted logical name, and thus the
240     device names in each element of the search list must be an actual
241     physical device name rather than another rooted logical name).
242
243  7. *If you are building GNU CC with a previous version of GNU CC, you
244     also should check to see that you have the newest version of the
245     assembler*.  In particular, GNU CC version 2 treats global constant
246     variables slightly differently from GNU CC version 1, and GAS
247     version 1.38.1 does not have the patches required to work with GCC
248     version 2.  If you use GAS 1.38.1, then `extern const' variables
249     will not have the read-only bit set, and the linker will generate
250     warning messages about mismatched psect attributes for these
251     variables.  These warning messages are merely a nuisance, and can
252     safely be ignored.
253
254     If you are compiling with a version of GNU CC older than 1.33,
255     specify `/DEFINE=("inline=")' as an option in all the
256     compilations.  This requires editing all the `gcc' commands in
257     `make-cc1.com'.  (The older versions had problems supporting
258     `inline'.)  Once you have a working 1.33 or newer GNU CC, you can
259     change this file back.
260
261  8. If you want to build GNU CC with the VAX C compiler, you will need
262     to make minor changes in `make-cccp.com' and `make-cc1.com' to
263     choose alternate definitions of `CC', `CFLAGS', and `LIBS'.  See
264     comments in those files.  However, you must also have a working
265     version of the GNU assembler (GNU as, aka GAS) as it is used as
266     the back-end for GNU CC to produce binary object modules and is
267     not included in the GNU CC sources.  GAS is also needed to compile
268     `libgcc2' in order to build `gcclib' (see above); `make-l2.com'
269     expects to be able to find it operational in
270     `gnu_cc:[000000]gnu-as.exe'.
271
272     To use GNU CC on VMS, you need the VMS driver programs `gcc.exe',
273     `gcc.com', and `gcc.cld'.  They are distributed with the VMS
274     binaries (`gcc-vms') rather than the GNU CC sources.  GAS is also
275     included in `gcc-vms', as is Bison.
276
277     Once you have successfully built GNU CC with VAX C, you should use
278     the resulting compiler to rebuild itself.  Before doing this, be
279     sure to restore the `CC', `CFLAGS', and `LIBS' definitions in
280     `make-cccp.com' and `make-cc1.com'.  The second generation
281     compiler will be able to take advantage of many optimizations that
282     must be suppressed when building with other compilers.
283
284   Under previous versions of GNU CC, the generated code would
285occasionally give strange results when linked with the sharable
286`VAXCRTL' library.  Now this should work.
287
288   Even with this version, however, GNU CC itself should not be linked
289with the sharable `VAXCRTL'.  The version of `qsort' in `VAXCRTL' has a
290bug (known to be present in VMS versions V4.6 through V5.5) which
291causes the compiler to fail.
292
293   The executables are generated by `make-cc1.com' and `make-cccp.com'
294use the object library version of `VAXCRTL' in order to make use of the
295`qsort' routine in `gcclib.olb'.  If you wish to link the compiler
296executables with the shareable image version of `VAXCRTL', you should
297edit the file `tm.h' (created by `vmsconfig.com') to define the macro
298`QSORT_WORKAROUND'.
299
300   `QSORT_WORKAROUND' is always defined when GNU CC is compiled with
301VAX C, to avoid a problem in case `gcclib.olb' is not yet available.
302
303
304File: gcc.info,  Node: Collect2,  Next: Header Dirs,  Prev: VMS Install,  Up: Installation
305
306`collect2'
307==========
308
309   Many target systems do not have support in the assembler and linker
310for "constructors"--initialization functions to be called before the
311official "start" of `main'.  On such systems, GNU CC uses a utility
312called `collect2' to arrange to call these functions at start time.
313
314   The program `collect2' works by linking the program once and looking
315through the linker output file for symbols with particular names
316indicating they are constructor functions.  If it finds any, it creates
317a new temporary `.c' file containing a table of them, compiles it, and
318links the program a second time including that file.
319
320   The actual calls to the constructors are carried out by a subroutine
321called `__main', which is called (automatically) at the beginning of
322the body of `main' (provided `main' was compiled with GNU CC).  Calling
323`__main' is necessary, even when compiling C code, to allow linking C
324and C++ object code together.  (If you use `-nostdlib', you get an
325unresolved reference to `__main', since it's defined in the standard
326GCC library.  Include `-lgcc' at the end of your compiler command line
327to resolve this reference.)
328
329   The program `collect2' is installed as `ld' in the directory where
330the passes of the compiler are installed.  When `collect2' needs to
331find the *real* `ld', it tries the following file names:
332
333   * `real-ld' in the directories listed in the compiler's search
334     directories.
335
336   * `real-ld' in the directories listed in the environment variable
337     `PATH'.
338
339   * The file specified in the `REAL_LD_FILE_NAME' configuration macro,
340     if specified.
341
342   * `ld' in the compiler's search directories, except that `collect2'
343     will not execute itself recursively.
344
345   * `ld' in `PATH'.
346
347   "The compiler's search directories" means all the directories where
348`gcc' searches for passes of the compiler.  This includes directories
349that you specify with `-B'.
350
351   Cross-compilers search a little differently:
352
353   * `real-ld' in the compiler's search directories.
354
355   * `TARGET-real-ld' in `PATH'.
356
357   * The file specified in the `REAL_LD_FILE_NAME' configuration macro,
358     if specified.
359
360   * `ld' in the compiler's search directories.
361
362   * `TARGET-ld' in `PATH'.
363
364   `collect2' explicitly avoids running `ld' using the file name under
365which `collect2' itself was invoked.  In fact, it remembers up a list
366of such names--in case one copy of `collect2' finds another copy (or
367version) of `collect2' installed as `ld' in a second place in the
368search path.
369
370   `collect2' searches for the utilities `nm' and `strip' using the
371same algorithm as above for `ld'.
372
373
374File: gcc.info,  Node: Header Dirs,  Prev: Collect2,  Up: Installation
375
376Standard Header File Directories
377================================
378
379   `GCC_INCLUDE_DIR' means the same thing for native and cross.  It is
380where GNU CC stores its private include files, and also where GNU CC
381stores the fixed include files.  A cross compiled GNU CC runs
382`fixincludes' on the header files in `$(tooldir)/include'.  (If the
383cross compilation header files need to be fixed, they must be installed
384before GNU CC is built.  If the cross compilation header files are
385already suitable for ANSI C and GNU CC, nothing special need be done).
386
387   `GPLUS_INCLUDE_DIR' means the same thing for native and cross.  It
388is where `g++' looks first for header files.  `libg++' installs only
389target independent header files in that directory.
390
391   `LOCAL_INCLUDE_DIR' is used only for a native compiler.  It is
392normally `/usr/local/include'.  GNU CC searches this directory so that
393users can install header files in `/usr/local/include'.
394
395   `CROSS_INCLUDE_DIR' is used only for a cross compiler.  GNU CC
396doesn't install anything there.
397
398   `TOOL_INCLUDE_DIR' is used for both native and cross compilers.  It
399is the place for other packages to install header files that GNU CC will
400use.  For a cross-compiler, this is the equivalent of `/usr/include'.
401When you build a cross-compiler, `fixincludes' processes any header
402files in this directory.
403
404
405File: gcc.info,  Node: C Extensions,  Next: C++ Extensions,  Prev: Installation,  Up: Top
406
407Extensions to the C Language Family
408***********************************
409
410   GNU C provides several language features not found in ANSI standard
411C.  (The `-pedantic' option directs GNU CC to print a warning message if
412any of these features is used.)  To test for the availability of these
413features in conditional compilation, check for a predefined macro
414`__GNUC__', which is always defined under GNU CC.
415
416   These extensions are available in C and Objective C.  Most of them
417are also available in C++.  *Note Extensions to the C++ Language: C++
418Extensions, for extensions that apply *only* to C++.
419
420* Menu:
421
422* Statement Exprs::     Putting statements and declarations inside expressions.
423* Local Labels::        Labels local to a statement-expression.
424* Labels as Values::    Getting pointers to labels, and computed gotos.
425* Nested Functions::    As in Algol and Pascal, lexical scoping of functions.
426* Constructing Calls::  Dispatching a call to another function.
427* Naming Types::        Giving a name to the type of some expression.
428* Typeof::              `typeof': referring to the type of an expression.
429* Lvalues::             Using `?:', `,' and casts in lvalues.
430* Conditionals::        Omitting the middle operand of a `?:' expression.
431* Long Long::           Double-word integers--`long long int'.
432* Complex::             Data types for complex numbers.
433* Zero Length::         Zero-length arrays.
434* Variable Length::     Arrays whose length is computed at run time.
435* Macro Varargs::       Macros with variable number of arguments.
436* Subscripting::        Any array can be subscripted, even if not an lvalue.
437* Pointer Arith::       Arithmetic on `void'-pointers and function pointers.
438* Initializers::        Non-constant initializers.
439* Constructors::        Constructor expressions give structures, unions
440                         or arrays as values.
441* Labeled Elements::    Labeling elements of initializers.
442* Cast to Union::       Casting to union type from any member of the union.
443* Case Ranges::         `case 1 ... 9' and such.
444* Function Attributes:: Declaring that functions have no side effects,
445                         or that they can never return.
446* Function Prototypes:: Prototype declarations and old-style definitions.
447* C++ Comments::        C++ comments are recognized.
448* Dollar Signs::        Dollar sign is allowed in identifiers.
449* Character Escapes::   `\e' stands for the character ESC.
450* Variable Attributes:: Specifying attributes of variables.
451* Type Attributes::     Specifying attributes of types.
452* Alignment::           Inquiring about the alignment of a type or variable.
453* Inline::              Defining inline functions (as fast as macros).
454* Extended Asm::        Assembler instructions with C expressions as operands.
455                         (With them you can define "built-in" functions.)
456* Asm Labels::          Specifying the assembler name to use for a C symbol.
457* Explicit Reg Vars::   Defining variables residing in specified registers.
458* Alternate Keywords::  `__const__', `__asm__', etc., for header files.
459* Incomplete Enums::    `enum foo;', with details to follow.
460* Function Names::      Printable strings which are the name of the current
461                         function.
462
463
464File: gcc.info,  Node: Statement Exprs,  Next: Local Labels,  Up: C Extensions
465
466Statements and Declarations in Expressions
467==========================================
468
469   A compound statement enclosed in parentheses may appear as an
470expression in GNU C.  This allows you to use loops, switches, and local
471variables within an expression.
472
473   Recall that a compound statement is a sequence of statements
474surrounded by braces; in this construct, parentheses go around the
475braces.  For example:
476
477     ({ int y = foo (); int z;
478        if (y > 0) z = y;
479        else z = - y;
480        z; })
481
482is a valid (though slightly more complex than necessary) expression for
483the absolute value of `foo ()'.
484
485   The last thing in the compound statement should be an expression
486followed by a semicolon; the value of this subexpression serves as the
487value of the entire construct.  (If you use some other kind of statement
488last within the braces, the construct has type `void', and thus
489effectively no value.)
490
491   This feature is especially useful in making macro definitions "safe"
492(so that they evaluate each operand exactly once).  For example, the
493"maximum" function is commonly defined as a macro in standard C as
494follows:
495
496     #define max(a,b) ((a) > (b) ? (a) : (b))
497
498But this definition computes either A or B twice, with bad results if
499the operand has side effects.  In GNU C, if you know the type of the
500operands (here let's assume `int'), you can define the macro safely as
501follows:
502
503     #define maxint(a,b) \
504       ({int _a = (a), _b = (b); _a > _b ? _a : _b; })
505
506   Embedded statements are not allowed in constant expressions, such as
507the value of an enumeration constant, the width of a bit field, or the
508initial value of a static variable.
509
510   If you don't know the type of the operand, you can still do this,
511but you must use `typeof' (*note Typeof::.) or type naming (*note
512Naming Types::.).
513
514
515File: gcc.info,  Node: Local Labels,  Next: Labels as Values,  Prev: Statement Exprs,  Up: C Extensions
516
517Locally Declared Labels
518=======================
519
520   Each statement expression is a scope in which "local labels" can be
521declared.  A local label is simply an identifier; you can jump to it
522with an ordinary `goto' statement, but only from within the statement
523expression it belongs to.
524
525   A local label declaration looks like this:
526
527     __label__ LABEL;
528
529or
530
531     __label__ LABEL1, LABEL2, ...;
532
533   Local label declarations must come at the beginning of the statement
534expression, right after the `({', before any ordinary declarations.
535
536   The label declaration defines the label *name*, but does not define
537the label itself.  You must do this in the usual way, with `LABEL:',
538within the statements of the statement expression.
539
540   The local label feature is useful because statement expressions are
541often used in macros.  If the macro contains nested loops, a `goto' can
542be useful for breaking out of them.  However, an ordinary label whose
543scope is the whole function cannot be used: if the macro can be
544expanded several times in one function, the label will be multiply
545defined in that function.  A local label avoids this problem.  For
546example:
547
548     #define SEARCH(array, target)                     \
549     ({                                               \
550       __label__ found;                                \
551       typeof (target) _SEARCH_target = (target);      \
552       typeof (*(array)) *_SEARCH_array = (array);     \
553       int i, j;                                       \
554       int value;                                      \
555       for (i = 0; i < max; i++)                       \
556         for (j = 0; j < max; j++)                     \
557           if (_SEARCH_array[i][j] == _SEARCH_target)  \
558             { value = i; goto found; }              \
559       value = -1;                                     \
560      found:                                           \
561       value;                                          \
562     })
563
564
565File: gcc.info,  Node: Labels as Values,  Next: Nested Functions,  Prev: Local Labels,  Up: C Extensions
566
567Labels as Values
568================
569
570   You can get the address of a label defined in the current function
571(or a containing function) with the unary operator `&&'.  The value has
572type `void *'.  This value is a constant and can be used wherever a
573constant of that type is valid.  For example:
574
575     void *ptr;
576     ...
577     ptr = &&foo;
578
579   To use these values, you need to be able to jump to one.  This is
580done with the computed goto statement(1), `goto *EXP;'.  For example,
581
582     goto *ptr;
583
584Any expression of type `void *' is allowed.
585
586   One way of using these constants is in initializing a static array
587that will serve as a jump table:
588
589     static void *array[] = { &&foo, &&bar, &&hack };
590
591   Then you can select a label with indexing, like this:
592
593     goto *array[i];
594
595Note that this does not check whether the subscript is in bounds--array
596indexing in C never does that.
597
598   Such an array of label values serves a purpose much like that of the
599`switch' statement.  The `switch' statement is cleaner, so use that
600rather than an array unless the problem does not fit a `switch'
601statement very well.
602
603   Another use of label values is in an interpreter for threaded code.
604The labels within the interpreter function can be stored in the
605threaded code for super-fast dispatching.
606
607   You can use this mechanism to jump to code in a different function.
608If you do that, totally unpredictable things will happen.  The best way
609to avoid this is to store the label address only in automatic variables
610and never pass it as an argument.
611
612   ---------- Footnotes ----------
613
614   (1)  The analogous feature in Fortran is called an assigned goto,
615but that name seems inappropriate in C, where one can do more than
616simply store label addresses in label variables.
617
618
619File: gcc.info,  Node: Nested Functions,  Next: Constructing Calls,  Prev: Labels as Values,  Up: C Extensions
620
621Nested Functions
622================
623
624   A "nested function" is a function defined inside another function.
625(Nested functions are not supported for GNU C++.)  The nested function's
626name is local to the block where it is defined.  For example, here we
627define a nested function named `square', and call it twice:
628
629     foo (double a, double b)
630     {
631       double square (double z) { return z * z; }
632     
633       return square (a) + square (b);
634     }
635
636   The nested function can access all the variables of the containing
637function that are visible at the point of its definition.  This is
638called "lexical scoping".  For example, here we show a nested function
639which uses an inherited variable named `offset':
640
641     bar (int *array, int offset, int size)
642     {
643       int access (int *array, int index)
644         { return array[index + offset]; }
645       int i;
646       ...
647       for (i = 0; i < size; i++)
648         ... access (array, i) ...
649     }
650
651   Nested function definitions are permitted within functions in the
652places where variable definitions are allowed; that is, in any block,
653before the first statement in the block.
654
655   It is possible to call the nested function from outside the scope of
656its name by storing its address or passing the address to another
657function:
658
659     hack (int *array, int size)
660     {
661       void store (int index, int value)
662         { array[index] = value; }
663     
664       intermediate (store, size);
665     }
666
667   Here, the function `intermediate' receives the address of `store' as
668an argument.  If `intermediate' calls `store', the arguments given to
669`store' are used to store into `array'.  But this technique works only
670so long as the containing function (`hack', in this example) does not
671exit.
672
673   If you try to call the nested function through its address after the
674containing function has exited, all hell will break loose.  If you try
675to call it after a containing scope level has exited, and if it refers
676to some of the variables that are no longer in scope, you may be lucky,
677but it's not wise to take the risk.  If, however, the nested function
678does not refer to anything that has gone out of scope, you should be
679safe.
680
681   GNU CC implements taking the address of a nested function using a
682technique called "trampolines".  A paper describing them is available
683from `maya.idiap.ch' in directory `pub/tmb', file `usenix88-lexic.ps.Z'.
684
685   A nested function can jump to a label inherited from a containing
686function, provided the label was explicitly declared in the containing
687function (*note Local Labels::.).  Such a jump returns instantly to the
688containing function, exiting the nested function which did the `goto'
689and any intermediate functions as well.  Here is an example:
690
691     bar (int *array, int offset, int size)
692     {
693       __label__ failure;
694       int access (int *array, int index)
695         {
696           if (index > size)
697             goto failure;
698           return array[index + offset];
699         }
700       int i;
701       ...
702       for (i = 0; i < size; i++)
703         ... access (array, i) ...
704       ...
705       return 0;
706     
707      /* Control comes here from `access'
708         if it detects an error.  */
709      failure:
710       return -1;
711     }
712
713   A nested function always has internal linkage.  Declaring one with
714`extern' is erroneous.  If you need to declare the nested function
715before its definition, use `auto' (which is otherwise meaningless for
716function declarations).
717
718     bar (int *array, int offset, int size)
719     {
720       __label__ failure;
721       auto int access (int *, int);
722       ...
723       int access (int *array, int index)
724         {
725           if (index > size)
726             goto failure;
727           return array[index + offset];
728         }
729       ...
730     }
731
732
733File: gcc.info,  Node: Constructing Calls,  Next: Naming Types,  Prev: Nested Functions,  Up: C Extensions
734
735Constructing Function Calls
736===========================
737
738   Using the built-in functions described below, you can record the
739arguments a function received, and call another function with the same
740arguments, without knowing the number or types of the arguments.
741
742   You can also record the return value of that function call, and
743later return that value, without knowing what data type the function
744tried to return (as long as your caller expects that data type).
745
746`__builtin_apply_args ()'
747     This built-in function returns a pointer of type `void *' to data
748     describing how to perform a call with the same arguments as were
749     passed to the current function.
750
751     The function saves the arg pointer register, structure value
752     address, and all registers that might be used to pass arguments to
753     a function into a block of memory allocated on the stack.  Then it
754     returns the address of that block.
755
756`__builtin_apply (FUNCTION, ARGUMENTS, SIZE)'
757     This built-in function invokes FUNCTION (type `void (*)()') with a
758     copy of the parameters described by ARGUMENTS (type `void *') and
759     SIZE (type `int').
760
761     The value of ARGUMENTS should be the value returned by
762     `__builtin_apply_args'.  The argument SIZE specifies the size of
763     the stack argument data, in bytes.
764
765     This function returns a pointer of type `void *' to data describing
766     how to return whatever value was returned by FUNCTION.  The data
767     is saved in a block of memory allocated on the stack.
768
769     It is not always simple to compute the proper value for SIZE.  The
770     value is used by `__builtin_apply' to compute the amount of data
771     that should be pushed on the stack and copied from the incoming
772     argument area.
773
774`__builtin_return (RESULT)'
775     This built-in function returns the value described by RESULT from
776     the containing function.  You should specify, for RESULT, a value
777     returned by `__builtin_apply'.
778
779
780File: gcc.info,  Node: Naming Types,  Next: Typeof,  Prev: Constructing Calls,  Up: C Extensions
781
782Naming an Expression's Type
783===========================
784
785   You can give a name to the type of an expression using a `typedef'
786declaration with an initializer.  Here is how to define NAME as a type
787name for the type of EXP:
788
789     typedef NAME = EXP;
790
791   This is useful in conjunction with the statements-within-expressions
792feature.  Here is how the two together can be used to define a safe
793"maximum" macro that operates on any arithmetic type:
794
795     #define max(a,b) \
796       ({typedef _ta = (a), _tb = (b);  \
797         _ta _a = (a); _tb _b = (b);     \
798         _a > _b ? _a : _b; })
799
800   The reason for using names that start with underscores for the local
801variables is to avoid conflicts with variable names that occur within
802the expressions that are substituted for `a' and `b'.  Eventually we
803hope to design a new form of declaration syntax that allows you to
804declare variables whose scopes start only after their initializers;
805this will be a more reliable way to prevent such conflicts.
806
807
808File: gcc.info,  Node: Typeof,  Next: Lvalues,  Prev: Naming Types,  Up: C Extensions
809
810Referring to a Type with `typeof'
811=================================
812
813   Another way to refer to the type of an expression is with `typeof'.
814The syntax of using of this keyword looks like `sizeof', but the
815construct acts semantically like a type name defined with `typedef'.
816
817   There are two ways of writing the argument to `typeof': with an
818expression or with a type.  Here is an example with an expression:
819
820     typeof (x[0](1))
821
822This assumes that `x' is an array of functions; the type described is
823that of the values of the functions.
824
825   Here is an example with a typename as the argument:
826
827     typeof (int *)
828
829Here the type described is that of pointers to `int'.
830
831   If you are writing a header file that must work when included in
832ANSI C programs, write `__typeof__' instead of `typeof'.  *Note
833Alternate Keywords::.
834
835   A `typeof'-construct can be used anywhere a typedef name could be
836used.  For example, you can use it in a declaration, in a cast, or
837inside of `sizeof' or `typeof'.
838
839   * This declares `y' with the type of what `x' points to.
840
841          typeof (*x) y;
842
843   * This declares `y' as an array of such values.
844
845          typeof (*x) y[4];
846
847   * This declares `y' as an array of pointers to characters:
848
849          typeof (typeof (char *)[4]) y;
850
851     It is equivalent to the following traditional C declaration:
852
853          char *y[4];
854
855     To see the meaning of the declaration using `typeof', and why it
856     might be a useful way to write, let's rewrite it with these macros:
857
858          #define pointer(T)  typeof(T *)
859          #define array(T, N) typeof(T [N])
860
861     Now the declaration can be rewritten this way:
862
863          array (pointer (char), 4) y;
864
865     Thus, `array (pointer (char), 4)' is the type of arrays of 4
866     pointers to `char'.
867
868
869File: gcc.info,  Node: Lvalues,  Next: Conditionals,  Prev: Typeof,  Up: C Extensions
870
871Generalized Lvalues
872===================
873
874   Compound expressions, conditional expressions and casts are allowed
875as lvalues provided their operands are lvalues.  This means that you
876can take their addresses or store values into them.
877
878   Standard C++ allows compound expressions and conditional expressions
879as lvalues, and permits casts to reference type, so use of this
880extension is deprecated for C++ code.
881
882   For example, a compound expression can be assigned, provided the last
883expression in the sequence is an lvalue.  These two expressions are
884equivalent:
885
886     (a, b) += 5
887     a, (b += 5)
888
889   Similarly, the address of the compound expression can be taken.
890These two expressions are equivalent:
891
892     &(a, b)
893     a, &b
894
895   A conditional expression is a valid lvalue if its type is not void
896and the true and false branches are both valid lvalues.  For example,
897these two expressions are equivalent:
898
899     (a ? b : c) = 5
900     (a ? b = 5 : (c = 5))
901
902   A cast is a valid lvalue if its operand is an lvalue.  A simple
903assignment whose left-hand side is a cast works by converting the
904right-hand side first to the specified type, then to the type of the
905inner left-hand side expression.  After this is stored, the value is
906converted back to the specified type to become the value of the
907assignment.  Thus, if `a' has type `char *', the following two
908expressions are equivalent:
909
910     (int)a = 5
911     (int)(a = (char *)(int)5)
912
913   An assignment-with-arithmetic operation such as `+=' applied to a
914cast performs the arithmetic using the type resulting from the cast,
915and then continues as in the previous case.  Therefore, these two
916expressions are equivalent:
917
918     (int)a += 5
919     (int)(a = (char *)(int) ((int)a + 5))
920
921   You cannot take the address of an lvalue cast, because the use of its
922address would not work out coherently.  Suppose that `&(int)f' were
923permitted, where `f' has type `float'.  Then the following statement
924would try to store an integer bit-pattern where a floating point number
925belongs:
926
927     *&(int)f = 1;
928
929   This is quite different from what `(int)f = 1' would do--that would
930convert 1 to floating point and store it.  Rather than cause this
931inconsistency, we think it is better to prohibit use of `&' on a cast.
932
933   If you really do want an `int *' pointer with the address of `f',
934you can simply write `(int *)&f'.
935
936
937File: gcc.info,  Node: Conditionals,  Next: Long Long,  Prev: Lvalues,  Up: C Extensions
938
939Conditionals with Omitted Operands
940==================================
941
942   The middle operand in a conditional expression may be omitted.  Then
943if the first operand is nonzero, its value is the value of the
944conditional expression.
945
946   Therefore, the expression
947
948     x ? : y
949
950has the value of `x' if that is nonzero; otherwise, the value of `y'.
951
952   This example is perfectly equivalent to
953
954     x ? x : y
955
956In this simple case, the ability to omit the middle operand is not
957especially useful.  When it becomes useful is when the first operand
958does, or may (if it is a macro argument), contain a side effect.  Then
959repeating the operand in the middle would perform the side effect
960twice.  Omitting the middle operand uses the value already computed
961without the undesirable effects of recomputing it.
962
963
964File: gcc.info,  Node: Long Long,  Next: Complex,  Prev: Conditionals,  Up: C Extensions
965
966Double-Word Integers
967====================
968
969   GNU C supports data types for integers that are twice as long as
970`long int'.  Simply write `long long int' for a signed integer, or
971`unsigned long long int' for an unsigned integer.  To make an integer
972constant of type `long long int', add the suffix `LL' to the integer.
973To make an integer constant of type `unsigned long long int', add the
974suffix `ULL' to the integer.
975
976   You can use these types in arithmetic like any other integer types.
977Addition, subtraction, and bitwise boolean operations on these types
978are open-coded on all types of machines.  Multiplication is open-coded
979if the machine supports fullword-to-doubleword a widening multiply
980instruction.  Division and shifts are open-coded only on machines that
981provide special support.  The operations that are not open-coded use
982special library routines that come with GNU CC.
983
984   There may be pitfalls when you use `long long' types for function
985arguments, unless you declare function prototypes.  If a function
986expects type `int' for its argument, and you pass a value of type `long
987long int', confusion will result because the caller and the subroutine
988will disagree about the number of bytes for the argument.  Likewise, if
989the function expects `long long int' and you pass `int'.  The best way
990to avoid such problems is to use prototypes.
991
992
993File: gcc.info,  Node: Complex,  Next: Zero Length,  Prev: Long Long,  Up: C Extensions
994
995Complex Numbers
996===============
997
998   GNU C supports complex data types.  You can declare both complex
999integer types and complex floating types, using the keyword
1000`__complex__'.
1001
1002   For example, `__complex__ double x;' declares `x' as a variable
1003whose real part and imaginary part are both of type `double'.
1004`__complex__ short int y;' declares `y' to have real and imaginary
1005parts of type `short int'; this is not likely to be useful, but it
1006shows that the set of complex types is complete.
1007
1008   To write a constant with a complex data type, use the suffix `i' or
1009`j' (either one; they are equivalent).  For example, `2.5fi' has type
1010`__complex__ float' and `3i' has type `__complex__ int'.  Such a
1011constant always has a pure imaginary value, but you can form any
1012complex value you like by adding one to a real constant.
1013
1014   To extract the real part of a complex-valued expression EXP, write
1015`__real__ EXP'.  Likewise, use `__imag__' to extract the imaginary part.
1016
1017   The operator `~' performs complex conjugation when used on a value
1018with a complex type.
1019
1020   GNU CC can allocate complex automatic variables in a noncontiguous
1021fashion; it's even possible for the real part to be in a register while
1022the imaginary part is on the stack (or vice-versa).  None of the
1023supported debugging info formats has a way to represent noncontiguous
1024allocation like this, so GNU CC describes a noncontiguous complex
1025variable as if it were two separate variables of noncomplex type.  If
1026the variable's actual name is `foo', the two fictitious variables are
1027named `foo$real' and `foo$imag'.  You can examine and set these two
1028fictitious variables with your debugger.
1029
1030   A future version of GDB will know how to recognize such pairs and
1031treat them as a single variable with a complex type.
1032
1033
1034File: gcc.info,  Node: Zero Length,  Next: Variable Length,  Prev: Complex,  Up: C Extensions
1035
1036Arrays of Length Zero
1037=====================
1038
1039   Zero-length arrays are allowed in GNU C.  They are very useful as
1040the last element of a structure which is really a header for a
1041variable-length object:
1042
1043     struct line {
1044       int length;
1045       char contents[0];
1046     };
1047     
1048     {
1049       struct line *thisline = (struct line *)
1050         malloc (sizeof (struct line) + this_length);
1051       thisline->length = this_length;
1052     }
1053
1054   In standard C, you would have to give `contents' a length of 1, which
1055means either you waste space or complicate the argument to `malloc'.
1056
1057
1058File: gcc.info,  Node: Variable Length,  Next: Macro Varargs,  Prev: Zero Length,  Up: C Extensions
1059
1060Arrays of Variable Length
1061=========================
1062
1063   Variable-length automatic arrays are allowed in GNU C.  These arrays
1064are declared like any other automatic arrays, but with a length that is
1065not a constant expression.  The storage is allocated at the point of
1066declaration and deallocated when the brace-level is exited.  For
1067example:
1068
1069     FILE *
1070     concat_fopen (char *s1, char *s2, char *mode)
1071     {
1072       char str[strlen (s1) + strlen (s2) + 1];
1073       strcpy (str, s1);
1074       strcat (str, s2);
1075       return fopen (str, mode);
1076     }
1077
1078   Jumping or breaking out of the scope of the array name deallocates
1079the storage.  Jumping into the scope is not allowed; you get an error
1080message for it.
1081
1082   You can use the function `alloca' to get an effect much like
1083variable-length arrays.  The function `alloca' is available in many
1084other C implementations (but not in all).  On the other hand,
1085variable-length arrays are more elegant.
1086
1087   There are other differences between these two methods.  Space
1088allocated with `alloca' exists until the containing *function* returns.
1089The space for a variable-length array is deallocated as soon as the
1090array name's scope ends.  (If you use both variable-length arrays and
1091`alloca' in the same function, deallocation of a variable-length array
1092will also deallocate anything more recently allocated with `alloca'.)
1093
1094   You can also use variable-length arrays as arguments to functions:
1095
1096     struct entry
1097     tester (int len, char data[len][len])
1098     {
1099       ...
1100     }
1101
1102   The length of an array is computed once when the storage is allocated
1103and is remembered for the scope of the array in case you access it with
1104`sizeof'.
1105
1106   If you want to pass the array first and the length afterward, you can
1107use a forward declaration in the parameter list--another GNU extension.
1108
1109     struct entry
1110     tester (int len; char data[len][len], int len)
1111     {
1112       ...
1113     }
1114
1115   The `int len' before the semicolon is a "parameter forward
1116declaration", and it serves the purpose of making the name `len' known
1117when the declaration of `data' is parsed.
1118
1119   You can write any number of such parameter forward declarations in
1120the parameter list.  They can be separated by commas or semicolons, but
1121the last one must end with a semicolon, which is followed by the "real"
1122parameter declarations.  Each forward declaration must match a "real"
1123declaration in parameter name and data type.
1124
1125
1126File: gcc.info,  Node: Macro Varargs,  Next: Subscripting,  Prev: Variable Length,  Up: C Extensions
1127
1128Macros with Variable Numbers of Arguments
1129=========================================
1130
1131   In GNU C, a macro can accept a variable number of arguments, much as
1132a function can.  The syntax for defining the macro looks much like that
1133used for a function.  Here is an example:
1134
1135     #define eprintf(format, args...)  \
1136      fprintf (stderr, format , ## args)
1137
1138   Here `args' is a "rest argument": it takes in zero or more
1139arguments, as many as the call contains.  All of them plus the commas
1140between them form the value of `args', which is substituted into the
1141macro body where `args' is used.  Thus, we have this expansion:
1142
1143     eprintf ("%s:%d: ", input_file_name, line_number)
1144     ==>
1145     fprintf (stderr, "%s:%d: " , input_file_name, line_number)
1146
1147Note that the comma after the string constant comes from the definition
1148of `eprintf', whereas the last comma comes from the value of `args'.
1149
1150   The reason for using `##' is to handle the case when `args' matches
1151no arguments at all.  In this case, `args' has an empty value.  In this
1152case, the second comma in the definition becomes an embarrassment: if
1153it got through to the expansion of the macro, we would get something
1154like this:
1155
1156     fprintf (stderr, "success!\n" , )
1157
1158which is invalid C syntax.  `##' gets rid of the comma, so we get the
1159following instead:
1160
1161     fprintf (stderr, "success!\n")
1162
1163   This is a special feature of the GNU C preprocessor: `##' before a
1164rest argument that is empty discards the preceding sequence of
1165non-whitespace characters from the macro definition.  (If another macro
1166argument precedes, none of it is discarded.)
1167
1168   It might be better to discard the last preprocessor token instead of
1169the last preceding sequence of non-whitespace characters; in fact, we
1170may someday change this feature to do so.  We advise you to write the
1171macro definition so that the preceding sequence of non-whitespace
1172characters is just a single token, so that the meaning will not change
1173if we change the definition of this feature.
1174
1175
1176File: gcc.info,  Node: Subscripting,  Next: Pointer Arith,  Prev: Macro Varargs,  Up: C Extensions
1177
1178Non-Lvalue Arrays May Have Subscripts
1179=====================================
1180
1181   Subscripting is allowed on arrays that are not lvalues, even though
1182the unary `&' operator is not.  For example, this is valid in GNU C
1183though not valid in other C dialects:
1184
1185     struct foo {int a[4];};
1186     
1187     struct foo f();
1188     
1189     bar (int index)
1190     {
1191       return f().a[index];
1192     }
1193
1194
1195File: gcc.info,  Node: Pointer Arith,  Next: Initializers,  Prev: Subscripting,  Up: C Extensions
1196
1197Arithmetic on `void'- and Function-Pointers
1198===========================================
1199
1200   In GNU C, addition and subtraction operations are supported on
1201pointers to `void' and on pointers to functions.  This is done by
1202treating the size of a `void' or of a function as 1.
1203
1204   A consequence of this is that `sizeof' is also allowed on `void' and
1205on function types, and returns 1.
1206
1207   The option `-Wpointer-arith' requests a warning if these extensions
1208are used.
1209
1210
1211File: gcc.info,  Node: Initializers,  Next: Constructors,  Prev: Pointer Arith,  Up: C Extensions
1212
1213Non-Constant Initializers
1214=========================
1215
1216   As in standard C++, the elements of an aggregate initializer for an
1217automatic variable are not required to be constant expressions in GNU C.
1218Here is an example of an initializer with run-time varying elements:
1219
1220     foo (float f, float g)
1221     {
1222       float beat_freqs[2] = { f-g, f+g };
1223       ...
1224     }
1225
Note: See TracBrowser for help on using the repository browser.