Reputation: 2210
I have the following file structure and would like to use a cmake config file MYLIBConfig.cmake
which is used by all CMakeLists.txt
files in the projects to include headers located in a folder include
on the top level.
MYLIBConfig.cmake
include/
header_a.h
header_b.h
src/
project_a/
CMakeLists.txt
main.cpp
project_b/
CMakeLists.txt
main.cpp
A CMakeLists.txt
containts the following:
cmake_minimum_required(VERSION 3.14)
find_package(MYLIB REQUIRED PATHS ${CMAKE_CURRENT_SOURCE_DIR}/../../)
project(projecta)
set(CMAKE_CXX_STANDARD 17)
add_executable(projecta main.cpp)
message(${MYLIB_INCLUDE_DIRS}) # Outpus /include/ which is the problem. Should be a relative path to the include folder
target_include_directories(${PROJECT_NAME}
PRIVATE
${MYLIB_INCLUDE_DIRS}
)
The MYLIBConfig.cmake has currently the following content:
cmake_minimum_required(VERSION 3.14)
#message(${PREFIX})
set(MYLIB_INCLUDE_DIRS ${CMAKE_PREFIX_PATH}/include/)
With this setup, I am not able to include the headers in my main.cpp files using #include "header_a.h"
because they are not found.
The problem is that I don't know if my usage of find_package
is correct because the set variable MYLIB_INCLUDE_DIRS
is just /include/
when I use message(message(${MYLIB_INCLUDE_DIRS})
inside the CMakeLists.txt
. Is there a cmake variable that I can use in the MYLIBConfig.cmake
file that sets a path which is relative to the "currently active" CMakeLists.txt
? Or is there another way to achieve a working include using a config file? I know that I could just use a relative path inside the target_include_directories
of every CMakeLists.txt
but I would like to use a config file to have the flexibility of changing the include folders and possibly set more variables. In the config file I also tried to use ${CMAKE_PREFIX_PATH} and ${CMAKE_CURRENT_SOURCE_DIR} but these variables did not work either.
EDIT
Another way I think it could work is when the MYLIB_INCLUDE_DIRS
would result in a global path. Would this be the appropriate way? And how could this be done?
Upvotes: 1
Views: 1790
Reputation: 480
You can get the global path in MYLIBConfig.cmake
with CMAKE_CURRENT_LIST_DIR:
set(MYLIB_INCLUDE_DIRS ${CMAKE_CURRENT_LIST_DIR}/include/)
Or if you want a relative path to the currently processed source you can get it accordingly with file:
file(RELATIVE_PATH MYLIB_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_LIST_DIR}/include/)
Upvotes: 2