C++ User's Guide

Building Dynamic (Shared) Libraries

Dynamic (shared) libraries are built the same way as static (archive) libraries, except that you use -G instead of -xar on the command line.

You should not use ld directly. As with static libraries, the CC command ensures that all the necessary template instances from the template repository are included in the library if you are using templates. Furthermore, the C++ compiler does not initialize global variables if they are defined in a dynamic library, unless the library is built correctly. All static constructors and destructors are called from the .init and .fini sections, respectively. All static constructors in a dynamic library linked to an application are called before main() is executed. Finally, exceptions might not work, unless you use the CC -G command to build the dynamic library.

To build a dynamic (shared) library, you must create relocatable object files by compiling each object with the -Kpic or -KPIC option of CC. You can then build a dynamic library with these relocatable object files. If you get any bizarre link failures, you might have forgotten to compile some objects with -Kpic or -KPIC.

To build a C++ dynamic library, libfoo.so.1, containing objects from source files lsrc1.cc and lsrc2.cc, type:


% CC -G -o libfoo.so.1 -h libfoo.so.1 -Kpic lsrc1.cc lsrc2.cc

The -G option specifies the construction of a dynamic library. The -o option specifies the file name for the library. The -h option specifies a name for the shared library. The -Kpic option specifies that the object files are to be position-independent.