Find package without myLib.cmake

Hi,

I am trying to use libgit2 in my C++ project. I installed the libgit2 library through brew (macOS).

The CMake configuration of my project fails with the following message:

  CMake Warning at CMakeLists.txt:6 (find_package):
  By not providing "Findlibgit2.cmake" in CMAKE_MODULE_PATH this project has
  asked CMake to find a package configuration file provided by "libgit2", but
  CMake did not find one.

  Could not find a package configuration file provided by "libgit2" with any
  of the following names:

    libgit2Config.cmake
    libgit2-config.cmake

  Add the installation prefix of "libgit2" to CMAKE_PREFIX_PATH or set
  "libgit2_DIR" to a directory containing one of the above files.  If
  "libgit2" provides a separate development package or SDK, be sure it has
  been installed.

I checked the content of the directory where the library is installed (/opt/homebrew/Cellar/libgit2/1.4.2_1) and indeed there is no *.cmake package configuration:

.
├── AUTHORS
├── COPYING
├── INSTALL_RECEIPT.json
├── README.md
├── include
│   ├── git2
│   └── git2.h
├── lib
│   ├── libgit2.1.4.0.dylib
│   ├── libgit2.1.4.dylib -> libgit2.1.4.0.dylib
│   ├── libgit2.a
│   ├── libgit2.dylib -> libgit2.1.4.dylib
│   └── pkgconfig
└── share
    └── libgit2

As there is no package configuration but the library exists, what is the proper way to include it in my project?

If it helps, here is a minimal example:

cmake_minimum_required(VERSION 3.21)

project(libgit2_example CXX)

set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "/opt/homebrew/Cellar/libgit2/1.4.2_1")
find_package(libgit2)

add_executable(${CMAKE_PROJECT_NAME})

target_sources(${CMAKE_PROJECT_NAME}
        PRIVATE
        main.cpp)

target_include_directories(${CMAKE_PROJECT_NAME}
        PRIVATE
        /opt/homebrew/Cellar/libgit2/1.4.2_1/include)

target_link_libraries(${CMAKE_PROJECT_NAME}
        PRIVATE
        libgit2)
#include "git2.h"

int main() {
    git_libgit2_init();
    return 0;
}

libgit2 provides a .pc file (under lib/pkgconfig I assume). You can use FindPkgConfig and its APIs to make that information available in CMake.

From what I understood from FindPkgConfig, I came to this solution:

cmake_minimum_required(VERSION 3.21)

project(libgit2_example CXX)

set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "/opt/homebrew/Cellar/libgit2")
find_package(PkgConfig)
if (PkgConfig_FOUND)
    pkg_check_modules(LIBGIT2 libgit2)
endif ()

add_executable(${CMAKE_PROJECT_NAME})

target_sources(${CMAKE_PROJECT_NAME}
        PRIVATE
        main.cpp)

target_include_directories(${CMAKE_PROJECT_NAME}
        PRIVATE
        ${LIBGIT2_INCLUDE_DIRS})

target_link_directories(${CMAKE_PROJECT_NAME}
        PRIVATE
        ${LIBGIT2_LIBRARY_DIRS})

target_link_libraries(${CMAKE_PROJECT_NAME}
        PRIVATE
        ${LIBGIT2_LIBRARIES})

It works. Thanks.