How to specify the library version to use at link time?

Didier Trosset picture Didier Trosset · Oct 1, 2010 · Viewed 20.9k times · Source

Following question How do applications resolve to different versions of shared libraries at run time?, I wondered how to specify on the link command line which version of the library to use?

Let's say I have

libmy.so.1.0
libmy.so.1    -> libmy.so.1.0
libmy.so.2.0
libmy.so.2    -> libmy.so.2.0
libmy.so      -> libmy.so.2

The usual way to specify the library to link with the executable does not show the version to use. Furthermore, it is very likely that one wants to link with the most recent version. Thus the usual line works fine in most cases.

gcc app.o -lmy -o app

What is the command line to link app that should use version 1 of the library?

Answer

Dmitry Yudakov picture Dmitry Yudakov · Oct 1, 2010

The linker is able to accept filenames too

gcc  app.o -l:libmy.so.1 -o app

From man ld:

-l namespec
--library=namespec
Add the archive or object file specified by namespec to the list of files to link. This option may be used any number of times. If namespec is of the form :filename, ld will search the library path for a file called filename, otherwise it will search the library path for a file called libnamespec.a.

I noticed that older versions do not support it, so check man ld -l or --library option on your system.

You could also link to the file mentioning its full name

gcc  app.o /mylibpath/libmy.so.1 -o app