ng Pragmas, Next: Weak Pragmas, Prev: Symbol-Renaming Pragmas, Up: Pragmas 5.52.7 Structure-Packing Pragmas -------------------------------- For compatibility with Win32, GCC supports a set of `#pragma' directives which change the maximum alignment of members of structures (other than zero-width bitfields), unions, and classes subsequently defined. The N value below always is required to be a small power of two and specifies the new alignment in bytes. 1. `#pragma pack(N)' simply sets the new alignment. 2. `#pragma pack()' sets the alignment to the one that was in effect when compilation started (see also command line option `-fpack-struct[=]' *note Code Gen Options::). 3. `#pragma pack(push[,N])' pushes the current alignment setting on an internal stack and then optionally sets the new alignment. 4. `#pragma pack(pop)' restores the alignment setting to the one saved at the top of the internal stack (and removes that stack entry). Note that `#pragma pack([N])' does not influence this internal stack; thus it is possible to have `#pragma pack(push)' followed by multiple `#pragma pack(N)' instances and finalized by a single `#pragma pack(pop)'. Some targets, e.g. i386 and powerpc, support the `ms_struct' `#pragma' which lays out a structure as the documented `__attribute__ ((ms_struct))'. 1. `#pragma ms_struct on' turns on the layout for structures declared. 2. `#pragma ms_struct off' turns off the layout for structures declared. 3. `#pragma ms_struct reset' goes back to the default layout.  File: gcc.info, Node: Weak Pragmas, Next: Diagnostic Pragmas, Prev: Structure-Packing Pragmas, Up: Pragmas 5.52.8 Weak Pragmas ------------------- For compatibility with SVR4, GCC supports a set of `#pragma' directives for declaring symbols to be weak, and defining weak aliases. `#pragma weak SYMBOL' This pragma declares SYMBOL to be weak, as if the declaration had the attribute of the same name. The pragma may appear before or after the declaration of SYMBOL, but must appear before either its first use or its definition. It is not an error for SYMBOL to never be defined at all. `#pragma weak SYMBOL1 = SYMBOL2' This pragma declares SYMBOL1 to be a weak alias of SYMBOL2. It is an error if SYMBOL2 is not defined in the current translation unit.  File: gcc.info, Node: Diagnostic Pragmas, Next: Visibility Pragmas, Prev: Weak Pragmas, Up: Pragmas 5.52.9 Diagnostic Pragmas ------------------------- GCC allows the user to selectively enable or disable certain types of diagnostics, and change the kind of the diagnostic. For example, a project's policy might require that all sources compile with `-Werror' but certain files might have exceptions allowing specific types of warnings. Or, a project might selectively enable diagnostics and treat them as errors depending on which preprocessor macros are defined. `#pragma GCC diagnostic KIND OPTION' Modifies the disposition of a diagnostic. Note that not all diagnostics are modifiable; at the moment only warnings (normally controlled by `-W...') can be controlled, and not all of them. Use `-fdiagnostics-show-option' to determine which diagnostics are controllable and which option controls them. KIND is `error' to treat this diagnostic as an error, `warning' to treat it like a warning (even if `-Werror' is in effect), or `ignored' if the diagnostic is to be ignored. OPTION is a double quoted string which matches the command line option. #pragma GCC diagnostic warning "-Wformat" #pragma GCC diagnostic error "-Wformat" #pragma GCC diagnostic ignored "-Wformat" Note that these pragmas override any command line options. Also, while it is syntactically valid to put these pragmas anywhere in your sources, the only supported location for them is before any data or functions are defined. Doing otherwise may result in unpredictable results depending on how the optimizer manages your sources. If the same option is listed multiple times, the last one specified is the one that is in effect. This pragma is not intended to be a general purpose replacement for command line options, but for implementing strict control over project policies.  File: gcc.info, Node: Visibility Pragmas, Prev: Diagnostic Pragmas, Up: Pragmas 5.52.10 Visibility Pragmas -------------------------- `#pragma GCC visibility push(VISIBILITY)' `#pragma GCC visibility pop' This pragma allows the user to set the visibility for multiple declarations without having to give each a visibility attribute *Note Function Attributes::, for more information about visibility and the attribute syntax. In C++, `#pragma GCC visibility' affects only namespace-scope declarations. Class members and template specializations are not affected; if you want to override the visibility for a particular member or instantiation, you must use an attribute.  File: gcc.info, Node: Unnamed Fields, Next: Thread-Local, Prev: Pragmas, Up: C Extensions 5.53 Unnamed struct/union fields within structs/unions ====================================================== For compatibility with other compilers, GCC allows you to define a structure or union that contains, as fields, structures and unions without names. For example: struct { int a; union { int b; float c; }; int d; } foo; In this example, the user would be able to access members of the unnamed union with code like `foo.b'. Note that only unnamed structs and unions are allowed, you may not have, for example, an unnamed `int'. You must never create such structures that cause ambiguous field definitions. For example, this structure: struct { int a; struct { int a; }; } foo; It is ambiguous which `a' is being referred to with `foo.a'. Such constructs are not supported and must be avoided. In the future, such constructs may be detected and treated as compilation errors. Unless `-fms-extensions' is used, the unnamed field must be a structure or union definition without a tag (for example, `struct { int a; };'). If `-fms-extensions' is used, the field may also be a definition with a tag such as `struct foo { int a; };', a reference to a previously defined structure or union such as `struct foo;', or a reference to a `typedef' name for a previously defined structure or union type.  File: gcc.info, Node: Thread-Local, Next: Binary constants, Prev: Unnamed Fields, Up: C Extensions 5.54 Thread-Local Storage ========================= Thread-local storage (TLS) is a mechanism by which variables are allocated such that there is one instance of the variable per extant thread. The run-time model GCC uses to implement this originates in the IA-64 processor-specific ABI, but has since been migrated to other processors as well. It requires significant support from the linker (`ld'), dynamic linker (`ld.so'), and system libraries (`libc.so' and `libpthread.so'), so it is not available everywhere. At the user level, the extension is visible with a new storage class keyword: `__thread'. For example: __thread int i; extern __thread struct state s; static __thread char *p; The `__thread' specifier may be used alone, with the `extern' or `static' specifiers, but with no other storage class specifier. When used with `extern' or `static', `__thread' must appear immediately after the other storage class specifier. The `__thread' specifier may be applied to any global, file-scoped static, function-scoped static, or static data member of a class. It may not be applied to block-scoped automatic or non-static data member. When the address-of operator is applied to a thread-local variable, it is evaluated at run-time and returns the address of the current thread's instance of that variable. An address so obtained may be used by any thread. When a thread terminates, any pointers to thread-local variables in that thread become invalid. No static initialization may refer to the address of a thread-local variable. In C++, if an initializer is present for a thread-local variable, it must be a CONSTANT-EXPRESSION, as defined in 5.19.2 of the ANSI/ISO C++ standard. See ELF Handling For Thread-Local Storage (http://people.redhat.com/drepper/tls.pdf) for a detailed explanation of the four thread-local storage addressing models, and how the run-time is expected to function. * Menu: * C99 Thread-Local Edits:: * C++98 Thread-Local Edits::  File: gcc.info, Node: C99 Thread-Local Edits, Next: C++98 Thread-Local Edits, Up: Thread-Local 5.54.1 ISO/IEC 9899:1999 Edits for Thread-Local Storage ------------------------------------------------------- The following are a set of changes to ISO/IEC 9899:1999 (aka C99) that document the exact semantics of the language extension. * `5.1.2 Execution environments' Add new text after paragraph 1 Within either execution environment, a "thread" is a flow of control within a program. It is implementation defined whether or not there may be more than one thread associated with a program. It is implementation defined how threads beyond the first are created, the name and type of the function called at thread startup, and how threads may be terminated. However, objects with thread storage duration shall be initialized before thread startup. * `6.2.4 Storage durations of objects' Add new text before paragraph 3 An object whose identifier is declared with the storage-class specifier `__thread' has "thread storage duration". Its lifetime is the entire execution of the thread, and its stored value is initialized only once, prior to thread startup. * `6.4.1 Keywords' Add `__thread'. * `6.7.1 Storage-class specifiers' Add `__thread' to the list of storage class specifiers in paragraph 1. Change paragraph 2 to With the exception of `__thread', at most one storage-class specifier may be given [...]. The `__thread' specifier may be used alone, or immediately following `extern' or `static'. Add new text after paragraph 6 The declaration of an identifier for a variable that has block scope that specifies `__thread' shall also specify either `extern' or `static'. The `__thread' specifier shall be used only with variables.  File: gcc.info, Node: C++98 Thread-Local Edits, Prev: C99 Thread-Local Edits, Up: Thread-Local 5.54.2 ISO/IEC 14882:1998 Edits for Thread-Local Storage -------------------------------------------------------- The following are a set of changes to ISO/IEC 14882:1998 (aka C++98) that document the exact semantics of the language extension. * [intro.execution] New text after paragraph 4 A "thread" is a flow of control within the abstract machine. It is implementation defined whether or not there may be more than one thread. New text after paragraph 7 It is unspecified whether additional action must be taken to ensure when and whether side effects are visible to other threads. * [lex.key] Add `__thread'. * [basic.start.main] Add after paragraph 5 The thread that begins execution at the `main' function is called the "main thread". It is implementation defined how functions beginning threads other than the main thread are designated or typed. A function so designated, as well as the `main' function, is called a "thread startup function". It is implementation defined what happens if a thread startup function returns. It is implementation defined what happens to other threads when any thread calls `exit'. * [basic.start.init] Add after paragraph 4 The storage for an object of thread storage duration shall be statically initialized before the first statement of the thread startup function. An object of thread storage duration shall not require dynamic initialization. * [basic.start.term] Add after paragraph 3 The type of an object with thread storage duration shall not have a non-trivial destructor, nor shall it be an array type whose elements (directly or indirectly) have non-trivial destructors. * [basic.stc] Add "thread storage duration" to the list in paragraph 1. Change paragraph 2 Thread, static, and automatic storage durations are associated with objects introduced by declarations [...]. Add `__thread' to the list of specifiers in paragraph 3. * [basic.stc.thread] New section before [basic.stc.static] The keyword `__thread' applied to a non-local object gives the object thread storage duration. A local variable or class data member declared both `static' and `__thread' gives the variable or member thread storage duration. * [basic.stc.static] Change paragraph 1 All objects which have neither thread storage duration, dynamic storage duration nor are local [...]. * [dcl.stc] Add `__thread' to the list in paragraph 1. Change paragraph 1 With the exception of `__thread', at most one STORAGE-CLASS-SPECIFIER shall appear in a given DECL-SPECIFIER-SEQ. The `__thread' specifier may be used alone, or immediately following the `extern' or `static' specifiers. [...] Add after paragraph 5 The `__thread' specifier can be applied only to the names of objects and to anonymous unions. * [class.mem] Add after paragraph 6 Non-`static' members shall not be `__thread'.  File: gcc.info, Node: Binary constants, Prev: Thread-Local, Up: C Extensions 5.55 Binary constants using the `0b' prefix =========================================== Integer constants can be written as binary constants, consisting of a sequence of `0' and `1' digits, prefixed by `0b' or `0B'. This is particularly useful in environments that operate a lot on the bit-level (like microcontrollers). The following statements are identical: i = 42; i = 0x2a; i = 052; i = 0b101010; The type of these constants follows the same rules as for octal or hexadecimal integer constants, so suffixes like `L' or `UL' can be applied.  File: gcc.info, Node: C++ Extensions, Next: Objective-C, Prev: C Extensions, Up: Top 6 Extensions to the C++ Language ******************************** The GNU compiler provides these extensions to the C++ language (and you can also use most of the C language extensions in your C++ programs). If you want to write code that checks whether these features are available, you can test for the GNU compiler the same way as for C programs: check for a predefined macro `__GNUC__'. You can also use `__GNUG__' to test specifically for GNU C++ (*note Predefined Macros: (cpp)Common Predefined Macros.). * Menu: * Volatiles:: What constitutes an access to a volatile object. * Restricted Pointers:: C99 restricted pointers and references. * Vague Linkage:: Where G++ puts inlines, vtables and such. * C++ Interface:: You can use a single C++ header file for both declarations and definitions. * Template Instantiation:: Methods for ensuring that exactly one copy of each needed template instantiation is emitted. * Bound member functions:: You can extract a function pointer to the method denoted by a `->*' or `.*' expression. * C++ Attributes:: Variable, function, and type attributes for C++ only. * Namespace Association:: Strong using-directives for namespace association. * Type Traits:: Compiler support for type traits * Java Exceptions:: Tweaking exception handling to work with Java. * Deprecated Features:: Things will disappear from g++. * Backwards Compatibility:: Compatibilities with earlier definitions of C++.  File: gcc.info, Node: Volatiles, Next: Restricted Pointers, Up: C++ Extensions 6.1 When is a Volatile Object Accessed? ======================================= Both the C and C++ standard have the concept of volatile objects. These are normally accessed by pointers and used for accessing hardware. The standards encourage compilers to refrain from optimizations concerning accesses to volatile objects. The C standard leaves it implementation defined as to what constitutes a volatile access. The C++ standard omits to specify this, except to say that C++ should behave in a similar manner to C with respect to volatiles, where possible. The minimum either standard specifies is that at a sequence point all previous accesses to volatile objects have stabilized and no subsequent accesses have occurred. Thus an implementation is free to reorder and combine volatile accesses which occur between sequence points, but cannot do so for accesses across a sequence point. The use of volatiles does not allow you to violate the restriction on updating objects multiple times within a sequence point. *Note Volatile qualifier and the C compiler: Qualifiers implementation. The behavior differs slightly between C and C++ in the non-obvious cases: volatile int *src = SOMEVALUE; *src; With C, such expressions are rvalues, and GCC interprets this either as a read of the volatile object being pointed to or only as request to evaluate the side-effects. The C++ standard specifies that such expressions do not undergo lvalue to rvalue conversion, and that the type of the dereferenced object may be incomplete. The C++ standard does not specify explicitly that it is this lvalue to rvalue conversion which may be responsible for causing an access. However, there is reason to believe that it is, because otherwise certain simple expressions become undefined. However, because it would surprise most programmers, G++ treats dereferencing a pointer to volatile object of complete type when the value is unused as GCC would do for an equivalent type in C. When the object has incomplete type, G++ issues a warning; if you wish to force an error, you must force a conversion to rvalue with, for instance, a static cast. When using a reference to volatile, G++ does not treat equivalent expressions as accesses to volatiles, but instead issues a warning that no volatile is accessed. The rationale for this is that otherwise it becomes difficult to determine where volatile access occur, and not possible to ignore the return value from functions returning volatile references. Again, if you wish to force a read, cast the reference to an rvalue.  File: gcc.info, Node: Restricted Pointers, Next: Vague Linkage, Prev: Volatiles, Up: C++ Extensions 6.2 Restricting Pointer Aliasing ================================ As with the C front end, G++ understands the C99 feature of restricted pointers, specified with the `__restrict__', or `__restrict' type qualifier. Because you cannot compile C++ by specifying the `-std=c99' language flag, `restrict' is not a keyword in C++. In addition to allowing restricted pointers, you can specify restricted references, which indicate that the reference is not aliased in the local context. void fn (int *__restrict__ rptr, int &__restrict__ rref) { /* ... */ } In the body of `fn', RPTR points to an unaliased integer and RREF refers to a (different) unaliased integer. You may also specify whether a member function's THIS pointer is unaliased by using `__restrict__' as a member function qualifier. void T::fn () __restrict__ { /* ... */ } Within the body of `T::fn', THIS will have the effective definition `T *__restrict__ const this'. Notice that the interpretation of a `__restrict__' member function qualifier is different to that of `const' or `volatile' qualifier, in that it is applied to the pointer rather than the object. This is consistent with other compilers which implement restricted pointers. As with all outermost parameter qualifiers, `__restrict__' is ignored in function definition matching. This means you only need to specify `__restrict__' in a function definition, rather than in a function prototype as well.  File: gcc.info, Node: Vague Linkage, Next: C++ Interface, Prev: Restricted Pointers, Up: C++ Extensions 6.3 Vague Linkage ================= There are several constructs in C++ which require space in the object file but are not clearly tied to a single translation unit. We say that these constructs have "vague linkage". Typically such constructs are emitted wherever they are needed, though sometimes we can be more clever. Inline Functions Inline functions are typically defined in a header file which can be included in many different compilations. Hopefully they can usually be inlined, but sometimes an out-of-line copy is necessary, if the address of the function is taken or if inlining fails. In general, we emit an out-of-line copy in all translation units where one is needed. As an exception, we only emit inline virtual functions with the vtable, since it will always require a copy. Local static variables and string constants used in an inline function are also considered to have vague linkage, since they must be shared between all inlined and out-of-line instances of the function. VTables C++ virtual functions are implemented in most compilers using a lookup table, known as a vtable. The vtable contains pointers to the virtual functions provided by a class, and each object of the class contains a pointer to its vtable (or vtables, in some multiple-inheritance situations). If the class declares any non-inline, non-pure virtual functions, the first one is chosen as the "key method" for the class, and the vtable is only emitted in the translation unit where the key method is defined. _Note:_ If the chosen key method is later defined as inline, the vtable will still be emitted in every translation unit which defines it. Make sure that any inline virtuals are declared inline in the class body, even if they are not defined there. type_info objects C++ requires information about types to be written out in order to implement `dynamic_cast', `typeid' and exception handling. For polymorphic classes (classes with virtual functions), the type_info object is written out along with the vtable so that `dynamic_cast' can determine the dynamic type of a class object at runtime. For all other types, we write out the type_info object when it is used: when applying `typeid' to an expression, throwing an object, or referring to a type in a catch clause or exception specification. Template Instantiations Most everything in this section also applies to template instantiations, but there are other options as well. *Note Where's the Template?: Template Instantiation. When used with GNU ld version 2.8 or later on an ELF system such as GNU/Linux or Solaris 2, or on Microsoft Windows, duplicate copies of these constructs will be discarded at link time. This is known as COMDAT support. On targets that don't support COMDAT, but do support weak symbols, GCC will use them. This way one copy will override all the others, but the unused copies will still take up space in the executable. For targets which do not support either COMDAT or weak symbols, most entities with vague linkage will be emitted as local symbols to avoid duplicate definition errors from the linker. This will not happen for local statics in inlines, however, as having multiple copies will almost certainly break things. *Note Declarations and Definitions in One Header: C++ Interface, for another way to control placement of these constructs.  File: gcc.info, Node: C++ Interface, Next: Template Instantiation, Prev: Vague Linkage, Up: C++ Extensions 6.4 #pragma interface and implementation ======================================== `#pragma interface' and `#pragma implementation' provide the user with a way of explicitly directing the compiler to emit entities with vague linkage (and debugging information) in a particular translation unit. _Note:_ As of GCC 2.7.2, these `#pragma's are not useful in most cases, because of COMDAT support and the "key method" heuristic mentioned in *note Vague Linkage::. Using them can actually cause your program to grow due to unnecessary out-of-line copies of inline functions. Currently (3.4) the only benefit of these `#pragma's is reduced duplication of debugging information, and that should be addressed soon on DWARF 2 targets with the use of COMDAT groups. `#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. 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 an inline 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'.  File: gcc.info, Node: Template Instantiation, Next: Bound member functions, Prev: C++ Interface, Up: C++ Extensions 6.5 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 are referred 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 GNU/Linux 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 template-using code with `-frepo'. The compiler will generate files with the extension `.rpo' listing all of the template instantiations used in the corresponding object files which could be instantiated there; the link wrapper, `collect2', will then update the `.rpo' files to tell the compiler where to place those instantiations and rebuild any affected object files. The link-time overhead is negligible after the first pass, as the compiler will continue to place the instantiations in the same files. This is your best option for application code written for the Borland model, as it will just work. Code written for the Cfront model will need to be modified so that the template definitions are available at one or more points of instantiation; usually this is as simple as adding `#include ' to the end of each template header. For library code, if you want the library to provide all of the template instantiations it needs, just try to link all of its object files together; the link will fail, but cause the instantiations to be generated as a side effect. Be warned, however, that this may cause conflicts if multiple libraries try to provide the same instantiations. For greater control, use explicit instantiation as described in the next option. 2. 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; template ostream& operator << (ostream&, const Foo&); 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 given in the ISO standard to allow forward declaration of explicit instantiations (with `extern'), instantiation of the compiler support data for a template class (i.e. the vtable) without instantiating any of its members (with `inline'), and instantiation of only the static data members of a template class, without the support data or member functions (with (`static'): extern template int max (int, int); inline template class Foo; static template class Foo; 3. 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.  File: gcc.info, Node: Bound member functions, Next: C++ Attributes, Prev: Template Instantiation, Up: C++ Extensions 6.6 Extracting the function pointer from a bound pointer to member function =========================================================================== In C++, pointer to member functions (PMFs) are implemented using a wide pointer of sorts to handle all the possible call mechanisms; the PMF needs to store information about how to adjust the `this' pointer, and if the function pointed to is virtual, where to find the vtable, and where in the vtable to look for the member function. If you are using PMFs in an inner loop, you should really reconsider that decision. If that is not an option, you can extract the pointer to the function that would be called for a given object/PMF pair and call it directly inside the inner loop, to save a bit of time. Note that you will still be paying the penalty for the call through a function pointer; on most modern architectures, such a call defeats the branch prediction features of the CPU. This is also true of normal virtual function calls. The syntax for this extension is extern A a; extern int (A::*fp)(); typedef int (*fptr)(A *); fptr p = (fptr)(a.*fp); For PMF constants (i.e. expressions of the form `&Klasse::Member'), no object is needed to obtain the address of the function. They can be converted to function pointers directly: fptr p1 = (fptr)(&A::foo); You must specify `-Wno-pmf-conversions' to use this extension.  File: gcc.info, Node: C++ Attributes, Next: Namespace Association, Prev: Bound member functions, Up: C++ Extensions 6.7 C++-Specific Variable, Function, and Type Attributes ======================================================== Some attributes only make sense for C++ programs. `init_priority (PRIORITY)' In Standard C++, objects defined at namespace scope are guaranteed to be initialized in an order in strict accordance with that of their definitions _in a given translation unit_. No guarantee is made for initializations across translation units. However, GNU C++ allows users to control the order of initialization of objects defined at namespace scope with the `init_priority' attribute by specifying a relative PRIORITY, a constant integral expression currently bounded between 101 and 65535 inclusive. Lower numbers indicate a higher priority. In the following example, `A' would normally be created before `B', but the `init_priority' attribute has reversed that order: Some_Class A __attribute__ ((init_priority (2000))); Some_Class B __attribute__ ((init_priority (543))); Note that the particular values of PRIORITY do not matter; only their relative ordering. `java_interface' This type attribute informs C++ that the class is a Java interface. It may only be applied to classes declared within an `extern "Java"' block. Calls to methods declared in this interface will be dispatched using GCJ's interface table mechanism, instead of regular virtual table dispatch. See also *Note Namespace Association::.  File: gcc.info, Node: Namespace Association, Next: Type Traits, Prev: C++ Attributes, Up: C++ Extensions 6.8 Namespace Association ========================= *Caution:* The semantics of this extension are not fully defined. Users should refrain from using this extension as its semantics may change subtly over time. It is possible that this extension will be removed in future versions of G++. A using-directive with `__attribute ((strong))' is stronger than a normal using-directive in two ways: * Templates from the used namespace can be specialized and explicitly instantiated as though they were members of the using namespace. * The using namespace is considered an associated namespace of all templates in the used namespace for purposes of argument-dependent name lookup. The used namespace must be nested within the using namespace so that normal unqualified lookup works properly. This is useful for composing a namespace transparently from implementation namespaces. For example: namespace std { namespace debug { template struct A { }; } using namespace debug __attribute ((__strong__)); template <> struct A { }; // ok to specialize template void f (A); } int main() { f (std::A()); // lookup finds std::f f (std::A()); }  File: gcc.info, Node: Type Traits, Next: Java Exceptions, Prev: Namespace Association, Up: C++ Extensions 6.9 Type Traits =============== The C++ front-end implements syntactic extensions that allow to determine at compile time various characteristics of a type (or of a pair of types). `__has_nothrow_assign (type)' If `type' is const qualified or is a reference type then the trait is false. Otherwise if `__has_trivial_assign (type)' is true then the trait is true, else if `type' is a cv class or union type with copy assignment operators that are known not to throw an exception then the trait is true, else it is false. Requires: `type' shall be a complete type, an array type of unknown bound, or is a `void' type. `__has_nothrow_copy (type)' If `__has_trivial_copy (type)' is true then the trait is true, else if `type' is a cv class or union type with copy constructors that are known not to throw an exception then the trait is true, else it is false. Requires: `type' shall be a complete type, an array type of unknown bound, or is a `void' type. `__has_nothrow_constructor (type)' If `__has_trivial_constructor (type)' is true then the trait is true, else if `type' is a cv class or union type (or array thereof) with a default constructor that is known not to throw an exception then the trait is true, else it is false. Requires: `type' shall be a complete type, an array type of unknown bound, or is a `void' type. `__has_trivial_assign (type)' If `type' is const qualified or is a reference type then the trait is false. Otherwise if `__is_pod (type)' is true then the trait is true, else if `type' is a cv class or union type with a trivial copy assignment ([class.copy]) then the trait is true, else it is false. Requires: `type' shall be a complete type, an array type of unknown bound, or is a `void' type. `__has_trivial_copy (type)' If `__is_pod (type)' is true or `type' is a reference type then the trait is true, else if `type' is a cv class or union type with a trivial copy constructor ([class.copy]) then the trait is true, else it is false. Requires: `type' shall be a complete type, an array type of unknown bound, or is a `void' type. `__has_trivial_constructor (type)' If `__is_pod (type)' is true then the trait is true, else if `type' is a cv class or union type (or array thereof) with a trivial default constructor ([class.ctor]) then the trait is true, else it is false. Requires: `type' shall be a complete type, an array type of unknown bound, or is a `void' type. `__has_trivial_destructor (type)' If `__is_pod (type)' is true or `type' is a reference type then the trait is true, else if `type' is a cv class or union type (or array thereof) with a trivial destructor ([class.dtor]) then the trait is true, else it is false. Requires: `type' shall be a complete type, an array type of unknown bound, or is a `void' type. `__has_virtual_destructor (type)' If `type' is a class type with a virtual destructor ([class.dtor]) then the trait is true, else it is false. Requires: `type' shall be a complete type, an array type of unknown bound, or is a `void' type. `__is_abstract (type)' If `type' is an abstract class ([class.abstract]) then the trait is true, else it is false. Requires: `type' shall be a complete type, an array type of unknown bound, or is a `void' type. `__is_base_of (base_type, derived_type)' If `base_type' is a base class of `derived_type' ([class.derived]) then the trait is true, otherwise it is false. Top-level cv qualifications of `base_type' and `derived_type' are ignored. For the purposes of this trait, a class type is considered is own base. Requires: if `__is_class (base_type)' and `__is_class (derived_type)' are true and `base_type' and `derived_type' are not the same type (disregarding cv-qualifiers), `derived_type' shall be a complete type. Diagnostic is produced if this requirement is not met. `__is_class (type)' If `type' is a cv class type, and not a union type ([basic.compound]) the the trait is true, else it is false. `__is_empty (type)' If `__is_class (type)' is false then the trait is false. Otherwise `type' is considered empty if and only if: `type' has no non-static data members, or all non-static data members, if any, are bit-fields of lenght 0, and `type' has no virtual members, and `type' has no virtual base classes, and `type' has no base classes `base_type' for which `__is_empty (base_type)' is false. Requires: `type' shall be a complete type, an array type of unknown bound, or is a `void' type. `__is_enum (type)' If `type' is a cv enumeration type ([basic.compound]) the the trait is true, else it is false. `__is_pod (type)' If `type' is a cv POD type ([basic.types]) then the trait is true, else it is false. Requires: `type' shall be a complete type, an array type of unknown bound, or is a `void' type. `__is_polymorphic (type)' If `type' is a polymorphic class ([class.virtual]) then the trait is true, else it is false. Requires: `type' shall be a complete type, an array type of unknown bound, or is a `void' type. `__is_union (type)' If `type' is a cv union type ([basic.compound]) the the trait is true, else it is false.  File: gcc.info, Node: Java Exceptions, Next: Deprecated Features, Prev: Type Traits, Up: C++ Extensions 6.10 Java Exceptions ==================== The Java language uses a slightly different exception handling model from C++. Normally, GNU C++ will automatically detect when you are writing C++ code that uses Java exceptions, and handle them appropriately. However, if C++ code only needs to execute destructors when Java exceptions are thrown through it, GCC will guess incorrectly. Sample problematic code is: struct S { ~S(); }; extern void bar(); // is written in Java, and may throw exceptions void foo() { S s; bar(); } The usual effect of an incorrect guess is a link failure, complaining of a missing routine called `__gxx_personality_v0'. You can inform the compiler that Java exceptions are to be used in a translation unit, irrespective of what it might think, by writing `#pragma GCC java_exceptions' at the head of the file. This `#pragma' must appear before any functions that throw or catch exceptions, or run destructors when exceptions are thrown through them. You cannot mix Java and C++ exceptions in the same translation unit. It is believed to be safe to throw a C++ exception from one file through another file compiled for the Java exception model, or vice versa, but there may be bugs in this area.  File: gcc.info, Node: Deprecated Features, Next: Backwards Compatibility, Prev: Java Exceptions, Up: C++ Extensions 6.11 Deprecated Features ======================== In the past, the GNU C++ compiler was extended to experiment with new features, at a time when the C++ language was still evolving. Now that the C++ standard is complete, some of those features are superseded by superior alternatives. Using the old features might cause a warning in some cases that the feature will be dropped in the future. In other cases, the feature might be gone already. While the list below is not exhaustive, it documents some of the options that are now deprecated: `-fexternal-templates' `-falt-external-templates' These are two of the many ways for G++ to implement template instantiation. *Note Template Instantiation::. The C++ standard clearly defines how template definitions have to be organized across implementation units. G++ has an implicit instantiation mechanism that should work just fine for standard-conforming code. `-fstrict-prototype' `-fno-strict-prototype' Previously it was possible to use an empty prototype parameter list to indicate an unspecified number of parameters (like C), rather than no parameters, as C++ demands. This feature has been removed, except where it is required for backwards compatibility *Note Backwards Compatibility::. G++ allows a virtual function returning `void *' to be overridden by one returning a different pointer type. This extension to the covariant return type rules is now deprecated and will be removed from a future version. The G++ minimum and maximum operators (`?') and their compound forms (`?=') have been deprecated and are now removed from G++. Code using these operators should be modified to use `std::min' and `std::max' instead. The named return value extension has been deprecated, and is now removed from G++. The use of initializer lists with new expressions has been deprecated, and is now removed from G++. Floating and complex non-type template parameters have been deprecated, and are now removed from G++. The implicit typename extension has been deprecated and is now removed from G++. The use of default arguments in function pointers, function typedefs and other places where they are not permitted by the standard is deprecated and will be removed from a future version of G++. G++ allows floating-point literals to appear in integral constant expressions, e.g. ` enum E { e = int(2.2 * 3.7) } ' This extension is deprecated and will be removed from a future version. G++ allows static data members of const floating-point type to be declared with an initializer in a class definition. The standard only allows initializers for static members of const integral types and const enumeration types so this extension has been deprecated and will be removed from a future version.  File: gcc.info, Node: Backwards Compatibility, Prev: Deprecated Features, Up: C++ Extensions 6.12 Backwards Compatibility ============================ Now that there is a definitive ISO standard C++, G++ has a specification to adhere to. The C++ language evolved over time, and features that used to be acceptable in previous drafts of the standard, such as the ARM [Annotated C++ Reference Manual], are no longer accepted. In order to allow compilation of C++ written to such drafts, G++ contains some backwards compatibilities. _All such backwards compatibility features are liable to disappear in future versions of G++._ They should be considered deprecated *Note Deprecated Features::. `For scope' If a variable is declared at for scope, it used to remain in scope until the end of the scope which contained the for statement (rather than just within the for scope). G++ retains this, but issues a warning, if such a variable is accessed outside the for scope. `Implicit C language' Old C system header files did not contain an `extern "C" {...}' scope to set the language. On such systems, all header files are implicitly scoped inside a C language scope. Also, an empty prototype `()' will be treated as an unspecified number of arguments, rather than no arguments, as C++ demands.  File: gcc.info, Node: Objective-C, Next: Compatibility, Prev: C++ Extensions, Up: Top 7 GNU Objective-C runtime features ********************************** This document is meant to describe some of the GNU Objective-C runtime features. It is not intended to teach you Objective-C, there are several resources on the Internet that present the language. Questions and comments about this document to Ovidiu Predescu . * Menu: * Executing code before main:: * Type encoding:: * Garbage Collection:: * Constant string objects:: * compatibility_alias::  File: gcc.info, Node: Executing code before main, Next: Type encoding, Prev: Objective-C, Up: Objective-C 7.1 `+load': Executing code before main ======================================= The GNU Objective-C runtime provides a way that allows you to execute code before the execution of the program enters the `main' function. The code is executed on a per-class and a per-category basis, through a special class method `+load'. This facility is very useful if you want to initialize global variables which can be accessed by the program directly, without sending a message to the class first. The usual way to initialize global variables, in the `+initialize' method, might not be useful because `+initialize' is only called when the first message is sent to a class object, which in some cases could be too late. Suppose for example you have a `FileStream' class that declares `Stdin', `Stdout' and `Stderr' as global variables, like below: FileStream *Stdin = nil; FileStream *Stdout = nil; FileStream *Stderr = nil; @implementation FileStream + (void)initialize { Stdin = [[FileStream new] initWithFd:0]; Stdout = [[FileStream new] initWithFd:1]; Stderr = [[FileStream new] initWithFd:2]; } /* Other methods here */ @end In this example, the initialization of `Stdin', `Stdout' and `Stderr' in `+initialize' occurs too late. The programmer can send a message to one of these objects before the variables are actually initialized, thus sending messages to the `nil' object. The `+initialize' method which actually initializes the global variables is not invoked until the first message is sent to the class object. The solution would require these variables to be initialized just before entering `main'. The correct solution of the above problem is to use the `+load' method instead of `+initialize': @implementation FileStream + (void)load { Stdin = [[FileStream new] initWithFd:0]; Stdout = [[FileStream new] initWithFd:1]; Stderr = [[FileStream new] initWithFd:2]; } /* Other methods here */ @end The `+load' is a method that is not overridden by categories. If a class and a category of it both implement `+load', both methods are invoked. This allows some additional initializations to be performed in a category. This mechanism is not intended to be a replacement for `+initialize'. You should be aware of its limitations when you decide to use it instead of `+initialize'. * Menu: * What you can and what you cannot do in +load::  File: gcc.info, Node: What you can and what you cannot do in +load, Prev: Executing code before main, Up: Executing code before main 7.1.1 What you can and what you cannot do in `+load' ---------------------------------------------------- The `+load' implementation in the GNU runtime guarantees you the following things: * you can write whatever C code you like; * you can send messages to Objective-C constant strings (`@"this is a constant string"'); * you can allocate and send messages to objects whose class is implemented in the same file; * the `+load' implementation of all super classes of a class are executed before the `+load' of that class is executed; * the `+load' implementation of a class is executed before the `+load' implementation of any category. In particular, the following things, even if they can work in a particular case, are not guaranteed: * allocation of or sending messages to arbitrary objects; * allocation of or sending messages to objects whose classes have a category implemented in the same file; You should make no assumptions about receiving `+load' in sibling classes when you write `+load' of a class. The order in which sibling classes receive `+load' is not guaranteed. The order in which `+load' and `+initialize' are called could be problematic if this matters. If you don't allocate objects inside `+load', it is guaranteed that `+load' is called before `+initialize'. If you create an object inside `+load' the `+initialize' method of object's class is invoked even if `+load' was not invoked. Note if you explicitly call `+load' on a class, `+initialize' will be called first. To avoid possible problems try to implement only one of these methods. The `+load' method is also invoked when a bundle is dynamically loaded into your running program. This happens automatically without any intervening operation from you. When you write bundles and you need to write `+load' you can safely create and send messages to objects whose classes already exist in the running program. The same restrictions as above apply to classes defined in bundle.  File: gcc.info, Node: Type encoding, Next: Garbage Collection, Prev: Executing code before main, Up: Objective-C 7.2 Type encoding ================= The Objective-C compiler generates type encodings for all the types. These type encodings are used at runtime to find out information about selectors and methods and about objects and classes. The types are encoded in the following way: `_Bool' `B' `char' `c' `unsigned char' `C' `short' `s' `unsigned short' `S' `int' `i' `unsigned int' `I' `long' `l' `unsigned long' `L' `long long' `q' `unsigned long `Q' long' `float' `f' `double' `d' `void' `v' `id' `@' `Class' `#' `SEL' `:' `char*' `*' unknown type `?' Complex types `j' followed by the inner type. For example `_Complex double' is encoded as "jd". bit-fields `b' followed by the starting position of the bit-field, the type of the bit-field and the size of the bit-field (the bit-fields encoding was changed from the NeXT's compiler encoding, see below) The encoding of bit-fields has changed to allow bit-fields to be properly handled by the runtime functions that compute sizes and alignments of types that contain bit-fields. The previous encoding contained only the size of the bit-field. Using only this information it is not possible to reliably compute the size occupied by the bit-field. This is very important in the presence of the Boehm's garbage collector because the objects are allocated using the typed memory facility available in this collector. The typed memory allocation requires information about where the pointers are located inside the object. The position in the bit-field is the position, counting in bits, of the bit closest to the beginning of the structure. The non-atomic types are encoded as follows: pointers `^' followed by the pointed type. arrays `[' followed by the number of elements in the array followed by the type of the elements followed by `]' structures `{' followed by the name of the structure (or `?' if the structure is unnamed), the `=' sign, the type of the members and by `}' unions `(' followed by the name of the structure (or `?' if the union is unnamed), the `=' sign, the type of the members followed by `)' Here are some types and their encodings, as they are generated by the compiler on an i386 machine: Objective-C type Compiler encoding int a[10]; `[10i]' struct { `{?=i[3f]b128i3b131i2c}' int i; float f[3]; int a:3; int b:2; char c; } In addition to the types the compiler also encodes the type specifiers. The table below describes the encoding of the current Objective-C type specifiers: Specifier Encoding `const' `r' `in' `n' `inout' `N' `out' `o' `bycopy' `O' `oneway' `V' The type specifiers are encoded just before the type. Unlike types however, the type specifiers are only encoded when they appear in method argument types.  File: gcc.info, Node: Garbage Collection, Next: Constant string objects, Prev: Type encoding, Up: Objective-C 7.3 Garbage Collection ====================== Support for a new memory management policy has been added by using a powerful conservative garbage collector, known as the Boehm-Demers-Weiser conservative garbage collector. It is available from `http://www.hpl.hp.com/personal/Hans_Boehm/gc/'. To enable the support for it you have to configure the compiler using an additional argument, `--enable-objc-gc'. You need to have garbage collector installed before building the compiler. This will build an additional runtime library which has several enhancements to support the garbage collector. The new library has a new name, `libobjc_gc.a' to not conflict with the non-garbage-collected library. When the garbage collector is used, the objects are allocated using the so-called typed memory allocation mechanism available in the Boehm-Demers-Weiser collector. This mode requires precise information on where pointers are located inside objects. This information is computed once per class, immediately after the class has been initialized. There is a new runtime function `class_ivar_set_gcinvisible()' which can be used to declare a so-called "weak pointer" reference. Such a pointer is basically hidden for the garbage collector; this can be useful in certain situations, especially when you want to keep track of the allocated objects, yet allow them to be collected. This kind of pointers can only be members of objects, you cannot declare a global pointer as a weak reference. Every type which is a pointer type can be declared a weak pointer, including `id', `Class' and `SEL'. Here is an example of how to use this feature. Suppose you want to implement a class whose instances hold a weak pointer reference; the following class does this: @interface WeakPointer : Object { const void* weakPointer; } - initWithPointer:(const void*)p; - (const void*)weakPointer; @end @implementation WeakPointer + (void)initialize { class_ivar_set_gcinvisible (self, "weakPointer", YES); } - initWithPointer:(const void*)p { weakPointer = p; return self; } - (const void*)weakPointer { return weakPointer; } @end Weak pointers are supported through a new type character specifier represented by the `!' character. The `class_ivar_set_gcinvisible()' function adds or removes this specifier to the string type description of the instance variable named as argument.  File: gcc.info, Node: Constant string objects, Next: compatibility_alias, Prev: Garbage Collection, Up: Objective-C 7.4 Constant string objects =========================== GNU Objective-C provides constant string objects that are generated directly by the compiler. You declare a constant string object by prefixing a C constant string with the character `@': id myString = @"this is a constant string object"; The constant string objects are by default instances of the `NXConstantString' class which is provided by the GNU Objective-C runtime. To get the definition of this class you must include the `objc/NXConstStr.h' header file. User defined libraries may want to implement their own constant string class. To be able to support them, the GNU Objective-C compiler provides a new command line options `-fconstant-string-class=CLASS-NAME'. The provided class should adhere to a strict structure, the same as `NXConstantString''s structure: @interface MyConstantStringClass { Class isa; char *c_string; unsigned int len; } @end `NXConstantString' inherits from `Object'; user class libraries may choose to inherit the customized constant string class from a different class than `Object'. There is no requirement in the methods the constant string class has to implement, but the final ivar layout of the class must be the compatible with the given structure. When the compiler creates the statically allocated constant string object, the `c_string' field will be filled by the compiler with the string; the `length' field will be filled by the compiler with the string length; the `isa' pointer will be filled with `NULL' by the compiler, and it will later be fixed up automatically at runtime by the GNU Objective-C runtime library to point to the class which was set by the `-fconstant-string-class' option when the object file is loaded (if you wonder how it works behind the scenes, the name of the class to use, and the list of static objects to fixup, are stored by the compiler in the object file in a place where the GNU runtime library will find them at runtime). As a result, when a file is compiled with the `-fconstant-string-class' option, all the constant string objects will be instances of the class specified as argument to this option. It is possible to have multiple compilation units referring to different constant string