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 libfoo.so that contains objects from source files lsrc1.cc and lsrc2.cc, type:
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
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 commands
ldd -u -r mylib.so ldd -U -r mylib.so
You can then rebuild mylib.so without the unneeded dependencies.