User Tools

Site Tools


notes:dynamic_linking

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
notes:dynamic_linking [2013/05/08 16:50]
andy created
notes:dynamic_linking [2013/05/08 17:05] (current)
andy
Line 30: Line 30:
 </​graphviz>​ </​graphviz>​
  
 +
 +===== Overview: Creating a Simple Shared Object =====
 +
 +To create a shared object from a single object file, it must first be compiled as **position-independent code**((This prevents the compiler locating data at fixed addresses, because clearly different executables will load the shared object into different parts of their address space.)) with the ''​-fpic''​ option:
 +
 +<​code>​
 +gcc -c -Wall -Werror -fpic code.c
 +</​code>​
 +
 +<​note>​When linking multiple object files into a single shared object, //all// of them must have been compiled with ''​-fpic''​ or the operation will fail.</​note>​
 +
 +Then the ''​-shared''​ option can be used to link that into a shared object:
 +
 +<​code>​
 +gcc -shared -o libcode.so code.o
 +</​code>​
 +
 +When compiling an application to use the shared library, its location must be specified with ''​-L''​ //prior// to using the ''​-l''​ option to link it (unless it's in a system default shared object directory):
 +
 +<​code>​
 +gcc -L/​home/​user/​src/​code -Wall -o codeapp main.c -lcode
 +</​code>​
 +
 +Similarly, when executing the application the library won't be found unless its location is specified (again, unless it's in a system default location). This can be done with ''​LD_LIBRARY_PATH'':​
 +
 +<​code>​
 +LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/​home/​user/​src/​code ./codeapp
 +</​code>​
 +
 +While sometimes useful for development,​ this isn't a robust solution for production environments and it has serious security implications. It's also possible to specify the path at link time, however:
 +
 +<​code>​
 +gcc -L/​home/​user/​src/​code -Wl,​rpath=/​home/​user/​src/​code -Wall -o codeapp main.c -lcode
 +</​code>​
 +
 +This approach requires libraries to be installed in a fixed location, which isn't always convenient, but doesn'​t require any special configuration at runtime. Note that the ''​-Wl''​ option is used to pass the subsequent option directly through to the linker.
 +
 +The standard approach is to copy the library to a system default location (e.g. ''/​usr/​lib''​) and run the ''​ldconfig''​ utility to create appropriate symlinks to it and update the shared object cache.
  
notes/dynamic_linking.1368031811.txt.gz ยท Last modified: 2013/05/08 16:50 by andy