Reputation: 60147
Suppose I have a main.lo
which I'd like to link against library foo.so
. The linker should always look for foo.so
at /foo/bar/lib.so
(fixed path, no search), but I only have lib.so
in my home directory and not in /foo/bar/
, which is a protected directory I can't write to myself.
Is it possible to link the lib like this?
Edit:
Below is a simple example using /tmp
instead of /foo/bar
. Can you make it work by modifying the build script?
main.c
void foo();
int main(){
foo();
return 0;
}
foo.c (multiple-file libraries are overrated)
#include <stdio.h>
void foo(){
puts("foo");
}
build.sh
#!/bin/sh
set -x
gcc -c -fPIC main.c -o main.lo
gcc -c -fPIC foo.c -o foo.lo
gcc -shared -o foo.so foo.lo
gcc -o pwd main.lo "$PWD/foo.so"
rm -f /tmp/foo.so
#? Link into dest, against /tmp/foo.so but use "$PWD/foo.so"
cp -a foo.so /tmp/foo.so
echo pwd:
./pwd #this works
echo dest:
./dest
Upvotes: 2
Views: 276
Reputation: 409432
You need two options to make it work:
First you need to use the -L
option to tell the linker where the library is actually located at the moment.
Then you need to use the -rpath
linker option to tell where the final location will be. Unfortunately this is a linker-specific option which means you need to use the -Wl
option to the GCC frontend program.
So the command should look something like
$ gcc object.o files.o -o target \
-L/current/path/to/library -Wl,-rpath,/final/path/to/library -llibrary
Note that the two paths can of course be the same.
Upvotes: 3