Friday, June 26, 2009

Creating and using shared library in Linux

Creating a shared library is relatively easy.  We only need to set a compilation flat to -fPIC (Position Independent Code) to create a library that is usable by other programs.

To use the shared library, however, is quite tricky in Linux.  A shared library or dynamically linked library in Windows are easy to use.  We can just place a dll file to the same folder of an executable. 

In Linux, nonetheless, things are more complicated, because Linux will never try to search for a library in a current directory.  Thus, we have to add a library direction to a search path or install it to a standard place like /usr/lib.  The latter choice needs adminstrator priviledge and not suitable if only one or two programs are to use the library.  So, we should modify a search path.

Now, the question is 'Can we modify a search path, but cause no side effect to other programs at all?'.  We are curious about this since we may have multiple libraries of the same name during testing.  A debug program may call a debug library and a release program may call release library of the same name.  Fortunately, we can do that, as shown in (Section 3.5. Installing and Using a Shared Library).

For example, if a shared library is in the same current directory of an executable my_program we can call

If the library is in another folder, such as /home/my_name, the command will be
LD_LIBRARY_PATH=/home/my_name:$LD_LIBRARY_PATH  ./my_program

Next question is 'How can we do such thing in Eclipse?'. We can do this in 'Run Configurations...'. Once we finish common configuration, we need to set an environment variable in the 'Environment' tab.
Click on the 'New' button. Set Name = LD_LIBRARY_PATH and set the Value = my_lib_dir:$LD_LIBRARY_PATH (change 'my_lib_dir' to the library directory). This is enough for Eclipse settings.


No comments: