Relocating Libraries
en

Relocating Libraries

Relocating Shared Libraries

When building games you may want to make the game installable anywhere within the system. For instance a normal user does not have permissions to write to system areas, so they will need to install them for example in their home directory or on their own removable media, such as a CDROM. Another example to install the game in a non standard location is their maybe a conflict between a library the game needs and a library installed as part of the Operating System.

You could make the user set the LD_LIBRARY_PATH environment variable to find the libraries, but it is best to make it very easy for the user to start the game. With careful use of the -R option using the $ORIGIN variable you can achieve your goal.

A look at the diagram below shows the relationship between a game installed in the standard /usr/bin directory and 2 dependent libraries for the game. Just to add a  bit of fun to the equation libmylibrary.so is dependent on libmylibrary2.so. The $ORIGIN variable is used by ld.so.1 as the base directory from where the object it is currently loading is.  

Origin Diagram

When the game is executed it will will first try to load libmylibrary.so. The relative path from the executable to the library is '$ORIGIN/../lib'. When it starts loading this library it will find that it depends upon libmylibrary2.so which just so happens to be in the same directory, therefore the relative path is just '$ORIGIN'. Therefore the link editor "ld" -R argument for a relative path lookup will be '-R $ORIGIN/../lib:$ORIGIN'. 

The command for linking should look something like this.

    cc -c -KPIC -o mylibrary2~_code.o mylibrary2~_code.c
    ld -G -o libmylibrary2.so mylibrary2~_code.o
    cc -c -KPIC -o mylibrary~_code.o mylibrary~_code.c
    ld -G -o libmylibrary.so mylibrary~_code.o -lmylibrary2 -L. -R'$ORIGIN/../lib:$ORIGIN'
    # Compile and link mygame
    cc -o mygame mygame.c -lmylibrary -L. -R'$ORIGIN/../lib:$ORIGIN'

In a build system, you might want to consider the option of using the LD_OPTIONS environment variable to set the link editor options. This is very useful when porting a game across from another system. Below is a typical %build section of a pkgbuild spec file which will allow the game to be relocatable.

    %build
    export LD~_OPTIONS="-L. -R'$ORIGIN/../lib:$ORIGIN'
    export CC=cc
    export CFLAGS="%{optflags}"
    export LDFLAGS="%{~_ldflags}"
    ./configure ~--prefix=%{_prefix} 
    make

For more information on using building relocatable libraries, please consult the  Linker and Libraries Guide at docs.sun.com.

Tags:
Created by admin on 2009/10/26 12:07
Last modified by admin on 2009/10/26 12:25

Collectives


XWiki Enterprise 2.7.1.34853 - Documentation