Search code examples
c++cmakebuild

How to integrate C++ library when its package is not named


C++ and CMake newbie question regarding how to integrate a third-party library into my own code. I'm trying to add Datadog metrics to C++ application. The officially-endorsed library doesn't state how it can be integrated. I imagine it should tell me how to import it like this:

find_package(<PACKAGE> REQUIRED)
add_executable(foobar src/main.cpp)
target_include_directories(foobar PUBLIC ${<PACKAGE_DIRECTORIES>})
target_link_libraries(foobar ${<PACKAGE_LIBRARIES>})

This is my understanding of how to integrate a third-party library (don't you wish there is "pip" in C++?). But the names in <> are not provided in the README. I certainly don't have to do it like this as long as I can use CMake. Any help is appreciated!


Solution

  • Easy solution is to fetch this library directly and do add_subdirectory. But this requires cmake >= 3.11.

    Create dir cmake and file cmake/cpp-datadogstatsd.cmake

    cpp-datadogstatsd.cmake:

    FetchContent_Declare(
            datadogstatsd
            GIT_REPOSITORY https://github.com/BoardiesITSolutions/cpp-datadogstatsd
            # try v1.1.0.5 if this does not work
            GIT_TAG        1.1.0.5
    )
    
    FetchContent_GetProperties(datadogstatsd)
    if(NOT datadogstatsd_POPULATED)
        message(STATUS "Downloading datadogstatsd...")
    
        FetchContent_Populate(datadogstatsd)
        add_subdirectory(${datadogstatsd_SOURCE_DIR} ${datadogstatsd_BINARY_DIR} EXCLUDE_FROM_ALL)
    endif()
    
    

    Then, include this cmake file, and link DataDogStatsD_static to your lib/exe:

    include(cmake/cpp-datadogstatsd.cmake)
    
    add_executable(test main.cpp)
    target_link_libraries(test DataDogStatsD_static)