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.
- Compile to object code with the -fPIC option:
- Create the shared object using the -shared option:
- 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:
- Ensure that the shared object can be found at run time - e.g., by doing this:
g++ -c -fPIC data.cpp g++ -c -fPIC stats.cpp
g++ -shared data.o stats.o -o libdata.so
g++ -I/usr/local/include -L/usr/local/lib prog.cpp -o prog -ldata
export LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH