53

I have a shared library that I wish to link an executable against using GCC. The shared library has a nonstandard name not of the form libNAME.so, so I can not use the usual -l option. (It happens to also be a Python extension, and so has no 'lib' prefix.)

I am able to pass the path to the library file directly to the link command line, but this causes the library path to be hardcoded into the executable.

For example:

g++ -o build/bin/myapp build/bin/_mylib.so

Is there a way to link to this library without causing the path to be hardcoded into the executable?

David Nehme
  • 21,379
  • 8
  • 78
  • 117
kbluck
  • 11,530
  • 4
  • 25
  • 25

3 Answers3

77

The -l option of g++ has a ":" prefix that allows you to use libraries with unconventional file names. The command

g++ -o build/bin/myapp -l:_mylib.so other_source_files

should search your path for the shared library with the file name _mylib.so.

David Nehme
  • 21,379
  • 8
  • 78
  • 117
  • 3
    I am finding that this results in `build/bin/_mylib.so` embedded in the library that was linked using `-l:` - instead of embedding just `_mylib.so` as it normally does for standard sonames. As a result, when you try loading `_mylib.so`, it would be looking for that full path (`ldd` would show it) and won't find `_mylib.so` by itself. – Evgen Jun 15 '16 at 23:25
  • this information is found in `man ld`: "On systems which support shared libraries, ld may also search for files other than libnamespec.a. Specifically, on ELF and SunOS systems, ld will search a directory for a library called libnamespec.so before searching for one called libnamespec.a. (By convention, a ".so" extension indicates a shared library.) Note that this behavior does not apply to :filename, which always specifies a file called filename." – btwiuse Aug 14 '17 at 11:36
  • Like @EvgeniiPuchkaryov I'm using `-L/path/to/lib` & `-l:mylib.so` and still getting the full path hard coded to elf header. any ideas on how to solve this?? – AmitE Jan 08 '18 at 19:52
  • I ended up building a library with standard name, like `libmylib.so` and then renaming it to `_mylib.so` before placing it to the final destination – Evgen Jan 17 '18 at 16:33
  • Thanks. And if I use CMAKE instead of explicit calls of `g++`, does CMAKE support `-l:` somehow? – Fedor Nov 24 '21 at 14:52
2

If you can copy the shared library to the working directory when g++ is invoked then this should work:

g++ -o build/bin/myapp _mylib.so other_source_files
Robert Gamble
  • 106,424
  • 25
  • 145
  • 137
1

If you are on Unix or Linux I think you can create a symbolic link to the library in the directory you want the library.

For example:
ln -s build/bin/_mylib.so build/bin/lib_mylib.so

You could then use -l_mylib

http://en.wikipedia.org/wiki/Symbolic_link

Chris Roland
  • 777
  • 3
  • 9