Using Linking Library Binary Files If you only built a static library (libstdc++.a), or if you specified static linking, you don't have to worry about this. But if you built a shared library (libstdc++.so) and linked against it, then you will need to find that library when you run the executable. Methods vary for different platforms and different styles, but the usual ones are printed to the screen during installation. They include: At runtime set LD_LIBRARY_PATH in your environment correctly, so that the shared library for libstdc++ can be found and loaded. Be certain that you understand all of the other implications and behavior of LD_LIBRARY_PATH first (few people do, and they get into trouble). Compile the path to find the library at runtime into the program. This can be done by passing certain options to g++, which will in turn pass them on to the linker. The exact format of the options is dependent on which linker you use: GNU ld (default on Linux):-Wl,--rpath,destdir/lib IRIX ld: -Wl,-rpath,destdir/lib Solaris ld:-Wl,-Rdestdir/lib More...? Let us know! Use the ldd utility to show which library the system thinks it will get at runtime. A libstdc++.la file is also installed, for use with Libtool. If you use Libtool to create your executables, these details are taken care of for you. Headers Header Files The C++ standard specifies the entire set of header files that must be available to all hosted implementations. Actually, the word "files" is a misnomer, since the contents of the headers don't necessarily have to be in any kind of external file. The only rule is that when one #include's a header, the contents of that header become available, no matter how. That said, in practice files are used. There are two main types of include files: header files related to a specific version of the ISO C++ standard (called Standard Headers), and all others (TR1, C++ ABI, and Extensions). Two dialects of standard headers are supported, corresponding to the 1998 standard as updated for 2003, and the draft of the upcoming 200x standard. C++98/03 include files. These are available in the default compilation mode, i.e. -std=c++98 or -std=gnu++98. C++ 1998 Library Headers algorithm bitset complex deque exception fstream functional iomanip ios iosfwd iostream istream iterator limits list locale map memory new numeric ostream queue set sstream stack stdexcept streambuf string utility typeinfo valarray vector
C++ 1998 Library Headers for C Library Facilities cassert cerrno cctype cfloat ciso646 climits clocale cmath csetjmp csignal cstdarg cstddef cstdio cstdlib cstring ctime cwchar cwctype
C++0x include files. These are only available in C++0x compilation mode, i.e. -std=c++0x or -std=gnu++0x. C++ 200x Library Headers algorithm array bitset chrono complex condition_variable deque exception forward_list fstream functional initalizer_list iomanip ios iosfwd iostream istream iterator limits list locale map memory mutex new numeric ostream queue random ratio regex set sstream stack stdexcept streambuf string system_error thread tuple type_traits typeinfo unordered_map unordered_set utility valarray vector
C++ 200x Library Headers for C Library Facilities cassert ccomplex cctype cerrno cfenv cfloat cinttypes ciso646 climits clocale cmath csetjmp csignal cstdarg cstdatomic cstdbool cstddef cstdint cstdlib cstdio cstring ctgmath ctime cuchar cwchar cwctype stdatomic.h
In addition, TR1 includes as: C++ TR1 Library Headers tr1/array tr1/complex tr1/memory tr1/functional tr1/random tr1/regex tr1/tuple tr1/type_traits tr1/unordered_map tr1/unordered_set tr1/utility
C++ TR1 Library Headers for C Library Facilities tr1/ccomplex tr1/cfenv tr1/cfloat tr1/cmath tr1/cinttypes tr1/climits tr1/cstdarg tr1/cstdbool tr1/cstdint tr1/cstdio tr1/cstdlib tr1/ctgmath tr1/ctime tr1/cwchar tr1/cwctype
Also included are files for the C++ ABI interface: C++ ABI Headers cxxabi.hcxxabi_forced.h
And a large variety of extensions. Extension Headers ext/algorithm ext/atomicity.h ext/array_allocator.h ext/bitmap_allocator.h ext/cast.h ext/codecvt_specializations.h ext/concurrence.h ext/debug_allocator.h ext/enc_filebuf.h ext/extptr_allocator.h ext/functional ext/iterator ext/malloc_allocator.h ext/memory ext/mt_allocator.h ext/new_allocator.h ext/numeric ext/numeric_traits.h ext/pb_ds/assoc_container.h ext/pb_ds/priority_queue.h ext/pod_char_traits.h ext/pool_allocator.h ext/rb_tree ext/rope ext/slist ext/stdio_filebuf.h ext/stdio_sync_filebuf.h ext/throw_allocator.h ext/typelist.h ext/type_traits.h ext/vstring.h
Extension Debug Headers debug/bitset debug/deque debug/list debug/map debug/set debug/string debug/unordered_map debug/unordered_set debug/vector
Extension Parallel Headers parallel/algorithm parallel/numeric
Mixing Headers A few simple rules. First, mixing different dialects of the standard headers is not possible. It's an all-or-nothing affair. Thus, code like #include <array> #include <functional> Implies C++0x mode. To use the entities in <array>, the C++0x compilation mode must be used, which implies the C++0x functionality (and deprecations) in <functional> will be present. Second, the other headers can be included with either dialect of the standard headers, although features and types specific to C++0x are still only enabled when in C++0x compilation mode. So, to use rvalue references with __gnu_cxx::vstring, or to use the debug-mode versions of std::unordered_map, one must use the std=gnu++0x compiler flag. (Or std=c++0x, of course.) A special case of the second rule is the mixing of TR1 and C++0x facilities. It is possible (although not especially prudent) to include both the TR1 version and the C++0x version of header in the same translation unit: #include <tr1/type_traits> #include <type_traits> Several parts of C++0x diverge quite substantially from TR1 predecessors. The C Headers and <code>namespace std</code> The standard specifies that if one includes the C-style header (<math.h> in this case), the symbols will be available in the global namespace and perhaps in namespace std:: (but this is no longer a firm requirement.) One the other hand, including the C++-style header (<cmath>) guarantees that the entities will be found in namespace std and perhaps in the global namespace. Usage of C++-style headers is recommended, as then C-linkage names can be disambiguated by explicit qualification, such as by std::abort. In addition, the C++-style headers can use function overloading to provide a simpler interface to certain families of C-functions. For instance in <cmath>, the function std::sin has overloads for all the builtin floating-point types. This means that std::sin can be used uniformly, instead of a combination of std::sinf, std::sin, and std::sinl. Precompiled Headers There are three base header files that are provided. They can be used to precompile the standard headers and extensions into binary files that may the be used to speed compiles that use these headers. stdc++.h Includes all standard headers. Actual content varies depending on language dialect. stdtr1c++.h Includes all of <stdc++.h>, and adds all the TR1 headers. extc++.h Includes all of <stdtr1c++.h>, and adds all the Extension headers. How to construct a .gch file from one of these base header files. First, find the include directory for the compiler. One way to do this is: g++ -v hello.cc #include <...> search starts here: /mnt/share/bld/H-x86-gcc.20071201/include/c++/4.3.0 ... End of search list. Then, create a precompiled header file with the same flags that will be used to compile other projects. g++ -Winvalid-pch -x c++-header -g -O2 -o ./stdc++.h.gch /mnt/share/bld/H-x86-gcc.20071201/include/c++/4.3.0/x86_64-unknown-linux-gnu/bits/stdc++.h The resulting file will be quite large: the current size is around thirty megabytes. How to use the resulting file. g++ -I. -include stdc++.h -H -g -O2 hello.cc Verification that the PCH file is being used is easy: g++ -Winvalid-pch -I. -include stdc++.h -H -g -O2 hello.cc -o test.exe ! ./stdc++.h.gch . /mnt/share/bld/H-x86-gcc.20071201/include/c++/4.3.0/iostream . /mnt/share/bld/H-x86-gcc.20071201include/c++/4.3.0/string The exclamation point to the left of the stdc++.h.gch listing means that the generated PCH file was used, and thus the Detailed information about creating precompiled header files can be found in the GCC documentation.
Namespaces Available Namespaces There are three main namespaces. std The ISO C++ standards specify that "all library entities are defined within namespace std." This includes namespaces nested within namespace std, such as namespace std::tr1. abi Specified by the C++ ABI. This ABI specifies a number of type and function APIs supplemental to those required by the ISO C++ Standard, but necessary for interoperability. __gnu_ Indicating one of several GNU extensions. Choices include __gnu_cxx, __gnu_debug, __gnu_parallel, and __gnu_pbds. A complete list of implementation namespaces (including namespace contents) is available in the generated source documentation. namespace std One standard requirement is that the library components are defined in namespace std::. Thus, in order to use these types or functions, one must do one of two things: put a kind of using-declaration in your source (either using namespace std; or i.e. using std::string;) This approach works well for individual source files, but should not be used in a global context, like header files. use a fully qualified namefor each library symbol (i.e. std::string, std::cout) Always can be used, and usually enhanced, by strategic use of typedefs. (In the cases where the qualified verbiage becomes unwieldy.) Using Namespace Composition Best practice in programming suggests sequestering new data or functionality in a sanely-named, unique namespace whenever possible. This is considered an advantage over dumping everything in the global namespace, as then name look-up can be explicitly enabled or disabled as above, symbols are consistently mangled without repetitive naming prefixes or macros, etc. For instance, consider a project that defines most of its classes in namespace gtk. It is possible to adapt namespace gtk to namespace std by using a C++-feature called namespace composition. This is what happens if a using-declaration is put into a namespace-definition: the imported symbol(s) gets imported into the currently active namespace(s). For example: namespace gtk { using std::string; using std::tr1::array; class Window { ... }; } In this example, std::string gets imported into namespace gtk. The result is that use of std::string inside namespace gtk can just use string, without the explicit qualification. As an added bonus, std::string does not get imported into the global namespace. Additionally, a more elaborate arrangement can be made for backwards compatibility and portability, whereby the using-declarations can wrapped in macros that are set based on autoconf-tests to either "" or i.e. using std::string; (depending on whether the system has libstdc++ in std:: or not). (ideas from llewelly@dbritsch.dsl.xmission.com, Karl Nelson kenelson@ece.ucdavis.edu) Macros All pre-processor switches and configurations are all gathered in the file c++config.h, which is generated during the libstdc++ configuration and build process, and included by files part of the public libstdc++ API. Most of these macros should not be used by consumers of libstdc++, and are reserved for internal implementation use. These macros cannot be redefined. However, a select handful of these macro control libstdc++ extensions and extra features, or provide versioning information for the API, and are able to be used. All library macros begin with _GLIBCXX_ (except for versions 3.1.x to 3.3.x, which use _GLIBCPP_). Below is the macro which users may check for library version information. __GLIBCXX__ The current version of libstdc++ in compressed ISO date format, form of an unsigned long. For details on the value of this particular macro for a particular release, please consult this document. Below are the macros which users may change with #define/#undef or with -D/-U compiler flags. The default state of the symbol is listed. Configurable (or Not configurable) means that the symbol is initially chosen (or not) based on --enable/--disable options at library build and configure time (documented here), with the various --enable/--disable choices being translated to #define/#undef). ABI means that changing from the default value may mean changing the ABI of compiled code. In other words, these choices control code which has already been compiled (i.e., in a binary such as libstdc++.a/.so). If you explicitly #define or #undef these macros, the headers may see different code paths, but the libraries which you link against will not. Experimenting with different values with the expectation of consistent linkage requires changing the config headers before building/installing the library. _GLIBCXX_DEPRECATED Defined by default. Not configurable. ABI-changing. Turning this off removes older ARM-style iostreams code, and other anachronisms from the API. This macro is dependent on the version of the standard being tracked, and as a result may give different results for -std=c++98 and -std=c++0x. This may be useful in updating old C++ code which no longer meet the requirements of the language, or for checking current code against new language standards. _GLIBCXX_FORCE_NEW Undefined by default. When defined, memory allocation and allocators controlled by libstdc++ call operator new/delete without caching and pooling. Configurable via --enable-libstdcxx-allocator. ABI-changing. _GLIBCXX_CONCEPT_CHECKS Undefined by default. Configurable via --enable-concept-checks. When defined, performs compile-time checking on certain template instantiations to detect violations of the requirements of the standard. This is described in more detail here. _GLIBCXX_DEBUG Undefined by default. When defined, compiles user code using the libstdc++ debug mode. _GLIBCXX_DEBUG_PEDANTIC Undefined by default. When defined while compiling with the libstdc++ debug mode, makes the debug mode extremely picky by making the use of libstdc++ extensions and libstdc++-specific behavior into errors. _GLIBCXX_PARALLEL Undefined by default. When defined, compiles user code using the libstdc++ parallel mode. Concurrency This section discusses issues surrounding the proper compilation of multithreaded applications which use the Standard C++ library. This information is GCC-specific since the C++ standard does not address matters of multithreaded applications. Prerequisites All normal disclaimers aside, multithreaded C++ application are only supported when libstdc++ and all user code was built with compilers which report (via gcc/g++ -v ) the same thread model and that model is not single. As long as your final application is actually single-threaded, then it should be safe to mix user code built with a thread model of single with a libstdc++ and other C++ libraries built with another thread model useful on the platform. Other mixes may or may not work but are not considered supported. (Thus, if you distribute a shared C++ library in binary form only, it may be best to compile it with a GCC configured with --enable-threads for maximal interchangeability and usefulness with a user population that may have built GCC with either --enable-threads or --disable-threads.) When you link a multithreaded application, you will probably need to add a library or flag to g++. This is a very non-standardized area of GCC across ports. Some ports support a special flag (the spelling isn't even standardized yet) to add all required macros to a compilation (if any such flags are required then you must provide the flag for all compilations not just linking) and link-library additions and/or replacements at link time. The documentation is weak. Here is a quick summary to display how ad hoc this is: On Solaris, both -pthreads and -threads (with subtly different meanings) are honored. On OSF, -pthread and -threads (with subtly different meanings) are honored. On Linux/i386, -pthread is honored. On FreeBSD, -pthread is honored. Some other ports use other switches. AFAIK, none of this is properly documented anywhere other than in ``gcc -dumpspecs'' (look at lib and cpp entries). Thread Safety We currently use the SGI STL definition of thread safety. The library strives to be thread-safe when all of the following conditions are met: The system's libc is itself thread-safe, The compiler in use reports a thread model other than 'single'. This can be tested via output from gcc -v. Multi-thread capable versions of gcc output something like this: %gcc -v Using built-in specs. ... Thread model: posix gcc version 4.1.2 20070925 (Red Hat 4.1.2-33) Look for "Thread model" lines that aren't equal to "single." Requisite command-line flags are used for atomic operations and threading. Examples of this include -pthread and -march=native, although specifics vary depending on the host environment. See Machine Dependent Options. An implementation of atomicity.h functions exists for the architecture in question. See the internals documentation for more details. The user-code must guard against concurrent method calls which may access any particular library object's state. Typically, the application programmer may infer what object locks must be held based on the objects referenced in a method call. Without getting into great detail, here is an example which requires user-level locks: library_class_a shared_object_a; thread_main () { library_class_b *object_b = new library_class_b; shared_object_a.add_b (object_b); // must hold lock for shared_object_a shared_object_a.mutate (); // must hold lock for shared_object_a } // Multiple copies of thread_main() are started in independent threads. Under the assumption that object_a and object_b are never exposed to another thread, here is an example that should not require any user-level locks: thread_main () { library_class_a object_a; library_class_b *object_b = new library_class_b; object_a.add_b (object_b); object_a.mutate (); } All library objects are safe to use in a multithreaded program as long as each thread carefully locks out access by any other thread while it uses any object visible to another thread, i.e., treat library objects like any other shared resource. In general, this requirement includes both read and write access to objects; unless otherwise documented as safe, do not assume that two threads may access a shared standard library object at the same time. See chapters 17 (library introduction), 23 (containers), and 27 (I/O) for more information. Atomics IO I'll assume that you have already read the general notes on library threads, and the notes on threaded container access (you might not think of an I/O stream as a container, but the points made there also hold here). If you have not read them, please do so first. This gets a bit tricky. Please read carefully, and bear with me. Structure A wrapper type called __basic_file provides our abstraction layer for the std::filebuf classes. Nearly all decisions dealing with actual input and output must be made in __basic_file. A generic locking mechanism is somewhat in place at the filebuf layer, but is not used in the current code. Providing locking at any higher level is akin to providing locking within containers, and is not done for the same reasons (see the links above). Defaults The __basic_file type is simply a collection of small wrappers around the C stdio layer (again, see the link under Structure). We do no locking ourselves, but simply pass through to calls to fopen, fwrite, and so forth. So, for 3.0, the question of "is multithreading safe for I/O" must be answered with, "is your platform's C library threadsafe for I/O?" Some are by default, some are not; many offer multiple implementations of the C library with varying tradeoffs of threadsafety and efficiency. You, the programmer, are always required to take care with multiple threads. (As an example, the POSIX standard requires that C stdio FILE* operations are atomic. POSIX-conforming C libraries (e.g, on Solaris and GNU/Linux) have an internal mutex to serialize operations on FILE*s. However, you still need to not do stupid things like calling fclose(fs) in one thread followed by an access of fs in another.) So, if your platform's C library is threadsafe, then your fstream I/O operations will be threadsafe at the lowest level. For higher-level operations, such as manipulating the data contained in the stream formatting classes (e.g., setting up callbacks inside an std::ofstream), you need to guard such accesses like any other critical shared resource. Future A second choice may be available for I/O implementations: libio. This is disabled by default, and in fact will not currently work due to other issues. It will be revisited, however. The libio code is a subset of the guts of the GNU libc (glibc) I/O implementation. When libio is in use, the __basic_file type is basically derived from FILE. (The real situation is more complex than that... it's derived from an internal type used to implement FILE. See libio/libioP.h to see scary things done with vtbls.) The result is that there is no "layer" of C stdio to go through; the filebuf makes calls directly into the same functions used to implement fread, fwrite, and so forth, using internal data structures. (And when I say "makes calls directly," I mean the function is literally replaced by a jump into an internal function. Fast but frightening. *grin*) Also, the libio internal locks are used. This requires pulling in large chunks of glibc, such as a pthreads implementation, and is one of the issues preventing widespread use of libio as the libstdc++ cstdio implementation. But we plan to make this work, at least as an option if not a future default. Platforms running a copy of glibc with a recent-enough version will see calls from libstdc++ directly into the glibc already installed. For other platforms, a copy of the libio subsection will be built and included in libstdc++. Alternatives Don't forget that other cstdio implementations are possible. You could easily write one to perform your own forms of locking, to solve your "interesting" problems. Containers This section discusses issues surrounding the design of multithreaded applications which use Standard C++ containers. All information in this section is current as of the gcc 3.0 release and all later point releases. Although earlier gcc releases had a different approach to threading configuration and proper compilation, the basic code design rules presented here were similar. For information on all other aspects of multithreading as it relates to libstdc++, including details on the proper compilation of threaded code (and compatibility between threaded and non-threaded code), see Chapter 17. Two excellent pages to read when working with the Standard C++ containers and threads are SGI's http://www.sgi.com/tech/stl/thread_safety.html and SGI's http://www.sgi.com/tech/stl/Allocators.html. However, please ignore all discussions about the user-level configuration of the lock implementation inside the STL container-memory allocator on those pages. For the sake of this discussion, libstdc++ configures the SGI STL implementation, not you. This is quite different from how gcc pre-3.0 worked. In particular, past advice was for people using g++ to explicitly define _PTHREADS or other macros or port-specific compilation options on the command line to get a thread-safe STL. This is no longer required for any port and should no longer be done unless you really know what you are doing and assume all responsibility. Since the container implementation of libstdc++ uses the SGI code, we use the same definition of thread safety as SGI when discussing design. A key point that beginners may miss is the fourth major paragraph of the first page mentioned above ("For most clients,"...), which points out that locking must nearly always be done outside the container, by client code (that'd be you, not us). There is a notable exceptions to this rule. Allocators called while a container or element is constructed uses an internal lock obtained and released solely within libstdc++ code (in fact, this is the reason STL requires any knowledge of the thread configuration). For implementing a container which does its own locking, it is trivial to provide a wrapper class which obtains the lock (as SGI suggests), performs the container operation, and then releases the lock. This could be templatized to a certain extent, on the underlying container and/or a locking mechanism. Trying to provide a catch-all general template solution would probably be more trouble than it's worth. The STL implementation is currently configured to use the high-speed caching memory allocator. Some people like to test and/or normally run threaded programs with a different default. For all details about how to globally override this at application run-time see here. There is a better way (not standardized yet): It is possible to force the malloc-based allocator on a per-case-basis for some application code. The library team generally believes that this is a better way to tune an application for high-speed using this implementation of the STL. There is more information on allocators here. Exceptions Propagating Exceptions aka Exception Neutrality Exception Safety Support for <literal>-fno-exceptions</literal>