Go to main content
Oracle® Developer Studio 12.6: C++ User's Guide

Exit Print View

Updated: July 2017
 
 

14.1 Understanding Libraries

Libraries provide two benefits. First, they provide a way to share code among several applications. If you have such code, you can create a library with it and link the library with any application that needs it. Second, libraries provide a way to reduce the complexity of very large applications. Such applications can build and maintain relatively independent portions as libraries and so reduce the burden on programmers working on other portions.

Building a library simply means creating .o files (by compiling your code with the -c option) and combining the .o files into a library using the CC command. You can build two kinds of libraries: static (archive) libraries and dynamic (shared) libraries.

With static (archive) libraries, objects within the library are linked into the program’s executable file at link time. Only those .o files from the library that are needed by the application are linked into the executable. The name of a static (archive) library generally ends with a .a suffix.

With dynamic (shared) libraries, objects within the library are not linked into the program’s executable file. Instead, the linker notes in the executable that the program depends on the library. When the program is executed, the system loads the dynamic libraries that the program requires. If two programs that use the same dynamic library execute at the same time, the operating system shares the library among the programs. The name of a dynamic (shared) library ends with an .so suffix.

Linking dynamically with shared libraries has several advantages over linking statically with archive libraries:

  • The size of the executable is smaller.

  • Significant portions of code can be shared among programs at runtime, reducing the amount of memory use.

  • The library can be replaced at runtime without relinking with the application. (This is the primary mechanism that enables programs to take advantage of many improvements in the Oracle Solaris operating system without requiring relinking and redistribution of programs.)

  • The shared library can be loaded at runtime using the dlopen() function call.

However, dynamic libraries have some disadvantages:

  • Runtime linking has an execution-time cost.

  • Distributing a program that uses dynamic libraries might require simultaneous distribution of the libraries it uses.

  • Moving a shared library to a different location can prevent the system from finding the library and executing the program. (The environment variable LD_LIBRARY_PATH helps overcome this problem.)