Search code examples
c++cmakeincludeprefix

CMake: add a directory prefix to `target_include_directories(...)` file #includes


I am using the Crypto++ library in my C++ project, and have installed it with the following (minimised) CMake code:

cmake_minimum_required(VERSION 3.24)
project(CMakeAddLibraryPrefixIncludes)

set(CMAKE_CXX_STANDARD 23)

include(FetchContent)
FetchContent_Declare(CryptoPP
        GIT_REPOSITORY https://github.com/weidai11/cryptopp.git
        GIT_TAG master)
FetchContent_MakeAvailable(CryptoPP)


add_executable(${PROJECT_NAME} main.cpp)

add_library(CryptoPP INTERFACE)
target_include_directories(CryptoPP INTERFACE ${CMAKE_BINARY_DIR}/_deps/cryptopp-src)
target_link_libraries(${PROJECT_NAME} CryptoPP)

Because the library has every header file in the top-level directory, all these files are accessible as #include <aes.h> for example. Is there a way that I can make it so that every file from CryptoPP is only accessible through a directory prefix like #include <cryptopp/aes.h>?


Solution

  • You can specify the folder for downloading sources by providing SOURCE_DIR to FetchContent_Declare. You can then use the parent folder of cryptopp_SOURCE_DIR as your include path.

    FetchContent_Declare(CryptoPP
            SOURCE_DIR ${FETCHCONTENT_BASE_DIR}/cryptopp-src/cryptopp
            GIT_REPOSITORY https://github.com/weidai11/cryptopp.git
            GIT_TAG master)
    FetchContent_MakeAvailable(CryptoPP)
    
    # ...
    
    target_include_directories(CryptoPP INTERFACE "${cryptopp_SOURCE_DIR}/..")