Sun Studio 12: C++ User's Guide

16.3 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. All static constructors in a dynamic library that is linked to an application are called before main() is executed and all static destructors are called after main() exits. If a shared library is opened using dlopen(), all static constructors are executed at dlopen() and all static destructors are executed at dlclose().

You should use CC -G to build a dynamic library. When you use ld (the link-editor) or cc (the C compiler) to build a dynamic library, exceptions might not work and the global variables that are defined in the library are not initialized.

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 named that contains objects from source files and, type:

% CC -G -o -h -Kpic

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.

Note –

The CC -G command does not pass any -l options to ld. If you want the shared library to have a dependency on another shared library, you must pass the necessary -l option on the command line. For example, if you want the shared library to be dependent upon, you must pass -lCr un on the command line.