Home > Backend Development > C++ > Why Does CMake Fail to Find My Shared Library When Using `link_directories`?

Why Does CMake Fail to Find My Shared Library When Using `link_directories`?

Susan Sarandon
Release: 2024-12-16 09:32:14
Original
277 people have browsed it

Why Does CMake Fail to Find My Shared Library When Using `link_directories`?

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)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template