Skip to main content

16.7) Creating And Using Shared Objects


The following example illustrates how we create and used a shared object with the GNU C++ compiler on a UNIX-like system. The details will be different for other compilers and other types of system, although the principle is broadly the same.

  1. Compile to object code with the -fPIC option:
  2. g++ -c -fPIC data.cpp
    g++ -c -fPIC stats.cpp
  3. Create the shared object using the -shared option:
  4. g++ -shared data.o stats.o -o libdata.so
  5. Install the header file and shared object in appropriate locations (e.g., under /usr/local), then compile your program and link it against the shared object:
  6. g++ -I/usr/local/include -L/usr/local/lib prog.cpp -o prog -ldata
  7. Ensure that the shared object can be found at run time - e.g., by doing this:
  8. export LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH