The main obstacle in the shared C++ library is how to treat global constructors and destructors. Under SunOS, building and using a shared C library is almost as easy as under ELF. But one cannot build a shared C++ library under SunOS because of the special requirements of the constructors and destructors. The .init and .fini sections in ELF provide a perfect solution for the problem.
When building a shared C++ library, we use two special versions of crtbegin.o and crtend.o which have been compiled with -fPIC. To the link editor, building the shared C++ library is almost exactly the same as building a normal executable. the global constructors and destructors are handled by the same .init and .fini sections we have discussed in Section 3.1.
When a shared library is mapped into the address space, the
dynamic linker will execute the _init
function before transferring the control to the program and will
arrange for the _fini
function to be executed when the shared
library is no longer needed.
The link option -shared for the gcc driver places the necessary auxiliary files in the right order and tells the link editor to generate a shared library. The -v option will show what files and options are passed to the link editor.
# gcc -v -shared -o libbar.so libbar.o Reading specs from /usr/lib/gcc-lib/i486-linux/2.6.4-950305/specs gcc driver version 2.6.4 snapshot 950305 executing gcc version 2.6.4 ld -m elf_i386 -shared -o libbar.so /usr/lib/crti.o /usr/lib/crtbeginS.o -L/usr/lib/gcc-lib/i486-linux/2.6.4-950305 -L/usr/i486-linux/lib libbar.o /usr/lib/crtendS.o /usr/lib/crtn.o
crtbeginS.o and crtendS.o are the special version compiled with -fPIC. It is very important that a shared library is always built with gcc -shared since those auxiliary files also serve other purposes. We will discuss this in Section 5.3.