Ivan Shcherbakov
Ivan Shcherbakov

Reputation: 2113

Any way to make LD record shared library name only, no subdirs?

I am linking a Linux executable referencing a shared library:

g++ Debug/file.o Debug/MyLib.so -o Debug/MyApp -Wl,--rpath='$ORIGIN'

The problem is that the generated MyApp file references "Debug/MyLib.so" so if I run it from the Debug directory, it does not find it. Thus, specifying -Wl,--rpath='$ORIGIN' does not help.

Is there a way to tell the GNU LD to use the 'Debug/MyLib.so' file, but record it as just 'MyLib.so' inside the executable?

Upvotes: 0

Views: 198

Answers (2)

guini
guini

Reputation: 770

If don't want to change the name of your library, you can use the soname option when you create it.

For example:

build the library

$> g++ -fpic -c mylib.cpp 
$> g++ -shared -o subdir/mylib.so mylib.o -Wl,-soname=mylib.so

build the program

g++ -o subdir/main main.cpp -Lsubdir -l:mylib.so -Wl,-rpath='$ORIGIN'

(Don't forget the colon after the -l option)

Upvotes: 1

Anya Shenanigans
Anya Shenanigans

Reputation: 94829

You're linking inappropriately for a shared library. You should rename the library to libMyLib.so, and link your executable using:

g++ Debug/file.o -o Debug/MyApp -Wl,--rpath='$ORIGIN' -LDebug -lMyLib

What the -LDebug says is search in the Debug directory for libraries at link time, and then the -lMyLib says look for a library called libMyLib.so (or libMyLib.a) in the paths that -L specifies, plus the standard library search path.

The standard naming convention for libraries under linux/unix is libLibraryName, and the linker knows when you ask to link to a library using -l, that it should look for a file prefixed lib thatname When you used it in the prior form, it actually recorded the absolute library that was used when linking, rather than the normal mechanism of just recording the name of the library, and relying on the runpath to resolve the path to the library.

Upvotes: 0

Related Questions