Is hard coding of the position of a shared library possible in program C?

Usually programs (on Linux) use LD_LIBRARY_PATH to find their shared libraries, but I want to use a custom path without constantly changing LD_LIBRARY_PATH.

Basically, bash-wrapper can easily achieve this:

#!/bin/sh export LD_LIBRARY_PATH=/my_lib_path/ /my_bin_path/myprogram $* 

(Bash only changes LD_LIBRARY_PATH in this script and not permanently)

I was wondering if it is possible to do the same in pure C in one executable without the ugly bash -hack. All paths and exact library names are known at compile time.

+4
source share
4 answers

Pass the -rpath parameter to ld or through your -Wl,-rpath . This allows you to expand the search path. It is usually used by an executable file that wants to load modules from some plugin directory. You can add as many directories as you want using this method.

+3
source

As others have said, when linking a program, you can use -Wl,-rpath to add specific paths to the library search path for the application. However, if you just want to hardcode the path to a specific library, use this when linking, rather than using the -l option. For example, instead of -lfoo just use /opt/foo/lib/libfoo.so.1 on the link command line.

+4
source

You cannot change LD_LIBRARY_PATH at runtime, the dynamic loader reads it once when the program executes and never checks it, you can use dlopen () to load the shared library instead:

 dlopen("/path/to/shared/lib.so", RTLD_LAZY); 

This will only work when loading the library and using dlsym() at run time to search for characters, otherwise, if you call functions in the library, these links should be allowed at boot time and AFAIK, you should use something like bashscript.

Note. At runtime, you can change LD_LIBRARY_PATH , if you re-execute this process, I just checked it and it seems to work, but it is very hacky, maybe the only way to do this in C :

 void *handle; // first time check if path is not set if (getenv("LD_LIBRARY_PATH")==NULL) { //set it and re-execute the process setenv("LD_LIBRARY_PATH", "/path/to/lib/", 1); execl(argv[0], argv[0], NULL); } // open the shared library the second time handle = dlopen("test.so", RTLD_LAZY); printf("%p\n", handle); dlclose(handle); 
+3
source

I do not think this is possible at runtime: the library is loaded before the program runs ...

But you can do this at compile time by passing the -rpath option -rpath your linker

0
source

All Articles