CMake Encountering Difficulty Locating Library Using "link_directories"
When attempting to link a shared library, libprotobuf.so, using CMake's "link_directories" command, a user encounters linker errors indicating undefined references to functions in the library. Despite the library residing in the specified directory, CMake fails to locate it.
The Solution
The issue stems from the order in which the CMake commands are placed within the CMakeLists.txt file. The "link_directories" command must be invoked prior to the "add_executable" command, rather than before the "target_link_libraries" command.
Explanation
"add_executable" creates an executable target, while "link_directories" specifies which directories should be searched for shared libraries. By placing the "link_directories" command after the "add_executable" command, CMake cannot find the library when attempting to link the executable.
Modified CMakeLists.txt
link_directories(/usr/lib/x86_64-linux-gnu) add_executable(test main.cpp) target_link_libraries(test protobuf)
Once the order of the commands is corrected, CMake successfully locates the libprotobuf.so library, and the linker no longer produces undefined reference errors.
The above is the detailed content of Why Does CMake Fail to Find My Shared Library When Using `link_directories`?. For more information, please follow other related articles on the PHP Chinese website!