linking

B North bnorth at mindspring.com
Wed Mar 19 14:12:20 EST 2003


> Let's say I have both a shared and a static version of the same library
> - libalib.a and libalib.so.  If they both reside in the same directory,
> which one will get linked?

The shared library. On Linux, gcc (or more accurately the linker) prefers
shared libraries to static ones by default. 

However, order of "-L" options matters more: a static library will be 
used if it's found first. So:

> Then if several directories are being searched (-L<dir1> -L<dir2>) will
> the library search order be:
> 
> (a) dir1/shared dir2/shared dir1/static dir2/static
> or
> (b) dir1/shared dir1/static dir2/shared dir2/static

it'll be (b).

The "-static" option can be used to override this preference and
look for only static libraries. 

Other platforms (and maybe Linux) also allow multiple specifications of 
"-Bdynamic" and "-Bstatic" to select on a library-by-library basis:
   gcc ... -Bstatic -lboost -Bdynamic -lm -lc

This should only search for libboost.a and libm.so and libc.so

> 
> The article on using shared libaries at
> 
> http://www.linux-mag.com/2002-04/compile_01.html
> 
> seems to indicate that dlfcn.h/-ldl is used to incorportate shared
> library functions into a program. 

This is only if you're writing a program that opens shared libraries
explicitly (e.g., to support some sort of configurable "plug-in" 
architecture). If your program just calls an external function and
leaves it to the linker to find an appropriate library containing that
function, you don't need to use "-ldl".

Hope this helps,

Ben




More information about the Discuss mailing list