Oracle® Solaris Studio 12.4: C++ User's Guide

Exit Print View

Updated: March 2015
 
 

14.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 unexpected link failures, you might have forgotten to compile some objects with –Kpic or –KPIC.

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

% CC -G -o libfoo.so -h libfoo.so -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 an internal name for the shared library. The -Kpic option specifies that the object files are to be position-independent.

The CC -G command does not pass any -l options to the linker, ld. To ensure proper initialization order, a shared library must have an explicit dependency on each other shared library it needs. To create the dependencies, use a -l option for each such library. Typical C++ shared libraries will use one of the following sets of options:

-lCstd -lCrun -lc     
-library=stlport4 -lCrun -lc
-library=stdcxx4 -lCrun -lc 
-lstdc++ -lgcc_s -lCrunG3 -lc 

The first three sets can be used only in the default -compat=5 mode. The fourth set can be used only in the -std=c++03 or -std=c++11 modes. For each option set, list the options in the order given after all other libraries.

To be sure you have listed all needed dependencies, build the library with the -zdefs option. The linker will issue an error message for each missing symbol definition. To provide the missing definitions, add a -l option for those libraries.

To find out if you have included unneeded dependencies, use the following commands

ldd -u -r mylib.so     
ldd -U -r mylib.so

You can then rebuild mylib.so without the unneeded dependencies.