5

I would like to hard code the path to a library in my executable, in Linux. On OS X this is achieved by providing the full path after the -o argument when building the library. For example, I build a library like this on OS X:

cc foo.c --shared -o /home/sander/libfoo.so

When I build an executable called 'bar' that links with this library, and I use otool -L on the executable, I get this output:

bar:
    /home/sander/libfoo.so (compatibility version 0.0.0, current version 0.0.0)

I can now run this executable from anywhere, and it is always able to find the library.

I am looking for equivalent functionality on Linux with gcc. I'd rather not use rpath since that doesn't link to a specific library + path.

2
  • 1
    Is there a reason you can't just link statically? If you're concerned about things being moved, that would seem far the safer option. Commented May 9, 2015 at 19:20
  • I can't link statically. This functionality is part of a package management system, and I must be able to update individual packages. I am not as much concerned about the libraries being moved. What's more important is that I can find the libraries from anywhere on my system. Commented May 9, 2015 at 19:35

1 Answer 1

6

Just compile it this way, so don't use -llib but specify it as object to compile:

cd /full/path/to/lib
gcc -shared -fpic -o liblib.so lib.c             # make the lib
gcc -c -o prog.o prog.c                          # compile program
gcc -o prog prog.o "/full/path/to/lib/liblib.so" # link everything together

EDIT: I initially wrote that on OS X it would not matter whether an absolute or relative path is specified after the -o option. That is not true. It does affect the library's "name" in the Mach-O LC_ID_DYLIB load command. Thanks @Sander Mertens for letting me know.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, that worked! I disagree on -o though. otool reveals that whatever you specify after -o is used when linking with that library. I just verified it again on OS X, and depending on the argument of -o, otool shows different output.
@SanderMertens sorry about that and thanks for letting me know. Editing the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.