One functionality of CMake is to find and link external libraries for building a project. In this Answer, we’ll delve into the CMake find_library
command and explore its purpose and usage.
The find_library
command in CMake is designed to locate a library file within the system. It searches predefined locations, including system paths and paths specified by the user, to locate the specified library file. Once found, the command provides the full path to the library file, which can be used for further processing.
The basic syntax for using the find_library
command is as follows:
find_library(<VAR> name1 [paths])
This can be explained as follows:
<VAR>
: This is the variable to store the result of the search.
name1
: This is the name of the library to search for.
[paths]
: These are optional paths to search for the library.
Let’s take a look at this command with an example. In the code below, we’ll try to find the OpenSSH
library.
#include <iostream> #include <openssl/md5.h> int main() { unsigned char digest[MD5_DIGEST_LENGTH]; char data[] = "Hello, World!"; MD5(reinterpret_cast<const unsigned char*>(&data), sizeof(data) - 1, digest); std::cout << "MD5 digest: "; for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) { std::printf("%02x", digest[i]); } std::cout << std::endl; return 0; }
This CMakeLists.txt
file can be explained as follows:
Line 4: We set our C++ compiler. For this example, it is g++
.
Line 6: We use find_package
to find OpenSSL
.
Lines 8–10: We display the OpenSSL
information.
Line 12: We create an executable.
Line 14: We link OpenSSL
libraries to the executable.
To run the code above, run the following steps:
Install OpenSSL
by running the following code:
apt install libssl-dev
Run CMake to generate build files:
cmake ..
Build the project using the generated build system:
cmake --build .
Run the executable:
./main
The output is the MD5 hash value generated by the MD5 algorithm applied to the input string Hello, World!
. This is all defined in the main.cpp
file.
The find_library
command in CMake is used for locating external libraries during the build process. Its integration with CMake’s build system makes it an essential component of modern software development. Understanding and leveraging the capabilities of find_library
can significantly streamline the development process and improve the overall quality of CMake-based projects.
Free Resources