使用zlog的项目编译正常但运行时找不到libzlog.so.1.2求助
Let's walk through the practical fixes for this issue—since you've already covered the basics (library exists in /usr/local/lib, set LD_LIBRARY_PATH, added link_directories in CMake), let's dig into the likely culprits that are still tripping you up:
1. Double-check your LD_LIBRARY_PATH is actually active
Sometimes setting LD_LIBRARY_PATH in the terminal only applies to that single session, or if you added it to a shell config file (like ~/.bashrc or ~/.zshrc) you haven't reloaded it yet.
- Verify the path is loaded with this command:
Ifecho $LD_LIBRARY_PATH/usr/local/libisn't listed, reload your shell config:
Or set it temporarily for the current session:source ~/.bashrc # swap with ~/.zshrc if you use zshexport LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH
2. Update the system's dynamic library cache
The system uses ld.so.cache to quickly locate shared libraries, and /usr/local/lib isn't always in the default search paths. Here's how to fix that permanently:
- First, add
/usr/local/libto the library config directory:echo "/usr/local/lib" | sudo tee /etc/ld.so.conf.d/zlog.conf - Then refresh the system's library cache:
sudo ldconfig
This makes the system recognize libraries in /usr/local/lib without relying on environment variables.
3. Ensure CMake is explicitly linking the zlog library
Adding link_directories(/usr/local/lib) tells CMake where to look for libraries, but you still need to explicitly link zlog to your target executable. Make sure your CMakeLists.txt includes this line (replace placeholders with your project details):
add_executable(your_project_name main.cpp) # Your target name and source files target_link_libraries(your_project_name zlog) # Explicitly link against libzlog.so
Without target_link_libraries, CMake won't know to tie zlog to your binary even if it finds the library directory.
4. Embed the library path directly in your executable (RPATH)
If you want your binary to find the library without relying on system config or environment variables, set RPATH in CMake. Add these lines to your CMakeLists.txt:
# For installed binaries (permanent path) set(CMAKE_INSTALL_RPATH "/usr/local/lib") set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE) # Or for development builds (temporary path during testing) # set(CMAKE_BUILD_RPATH "/usr/local/lib")
This embeds the library path directly into your executable, so it knows exactly where to look for libzlog.so.1.2 when running.
Try these steps one by one—usually updating the ld.so cache or fixing the CMake linking is the quick fix here!
内容的提问来源于stack exchange,提问作者L.Ward

