What is the CMake find_library?

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.

Usage

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.

Code example

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;
}
Usage of the find_library command

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:

  1. Install OpenSSL by running the following code:

apt install libssl-dev
  1. Run CMake to generate build files:

cmake ..
  1. Build the project using the generated build system:

cmake --build .
  1. 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.

Conclusion

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

Copyright ©2025 Educative, Inc. All rights reserved