What
exactly do you mean with "use" a shared library?
When you
compile the source that uses the shared library – doesn't really matter whether the library is "shared" though – the library itself (
.so file) is
not really involved. Instead, you have to
#include the
header file (
.h or
.hpp) that defines the public interface of the library. And, of course, you have to make sure that the required
header file is found in the compiler's search path (e.g. by using the
-I option of the compiler).
When you
link your program, then you
link the required library (
.so file), by using the
-l option of the compiler. For example, in order to link the library "libfoo.so", you would use
-lfoo. Also, you have to make sure that the required library file is found in the linker's search path (e.g. by using the
-L option of the linker).
Finally, at
runtime, the "shared" library (
.so file) needs to be available in one of the paths that the operating system's
loader is scanning, such as
/usr/lib[64] or
/usr/local/lib[64]. The directory, from which to load the "shared" library can also be adjusted,
at runtime, by using the
LD_LIBRARY_PATH environment variable.
Also note:
If both static and shared libraries are found, the linker gives preference to linking with the shared library unless the -static option is used. |
Example:
1 2 3 4 5 6 7 8 9 10
|
# Compile
g++ -I/path/to/library/include -c source1.cpp
g++ -I/path/to/library/include -c source2.cpp
# Link
g++ -L/path/to/library/lib -o program.out source1.o source2.o -lfoo
# Run
export LD_LIBRARY_PATH=/path/to/library/lib
./program.out
|
...assuming that the "shared" library
libfoo.so, which we want to use, resides in directory
/path/to/library/lib, and that its associated header files reside in directory
/path/to/library/include.
Source code file
source1.cpp may look something like this:
1 2 3 4 5 6 7
|
#include <foo.hpp> // <-- declares public interface of "libfoo" library
main()
{
foo::SomeClassFromLibFoo instance;
instance.doSomething();
}
|
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
BTW: Optionally, by using the
linker option
-Wl,-rpath,$ORIGIN, you can create an executable that loads its "shared" libraries from the same directory where the executable file is located.