Home >Backend Development >C++ >How to Control Library Path Preference in C Linking?
Specify Library Path Preference in C Linking
When linking a C program with external libraries, controlling the preference for specific library paths can be challenging. For instance, if you have a local library named libfoo.so.0 in /my/dir but another library with the same name resides in /usr/local/lib, the linker might prioritize the latter.
Solution 1: Use LD_LIBRARY_PATH
The most straightforward solution is to add the path where your new library resides to the LD_LIBRARY_PATH environment variable. At runtime, your program will search this path before the standard locations for libraries. However, it's worth noting the potential security and performance implications associated with using LD_LIBRARY_PATH.
Solution 2: Use the -Wl,-rpath Option
Alternatively, you can use the -Wl,-rpath,$(DEFAULT_LIB_INSTALL_PATH) compiler option via gcc to instruct the linker to use runtime library search path instead of standard directories. This option can be employed for a temporary solution or, if preferred, you can permanently modify your system's default library search path.
Checking Library Information
To verify the libraries that your linker is aware of, you can use the command:
<code class="bash">/sbin/ldconfig -p | grep libpthread</code>
Similarly, to inspect the libraries that your application is utilizing, use:
<code class="bash">ldd foo</code>
By following these steps, you can effectively specify the preference for library paths during the linking process in your C programs.
The above is the detailed content of How to Control Library Path Preference in C Linking?. For more information, please follow other related articles on the PHP Chinese website!