When working with CMake, it's common to set include directories for a target using target_include_directories
or the older include_directories
. But sometimes you need to retrieve those include directories later - for example, for debugging, logging, or passing them to another command. This tutorial explains how to get target include directories using CMake.
Let's say we have the following CMakeLists.txt
file:
cmake_minimum_required(VERSION 3.27)
project(myapp)
set(CMAKE_CXX_STANDARD 17)
add_executable(${PROJECT_NAME} main.cpp)
include_directories(lib/include)
target_include_directories(${PROJECT_NAME} PRIVATE include)
get_target_property(TARGET_INCLUDES ${PROJECT_NAME} INCLUDE_DIRECTORIES)
message(STATUS "${TARGET_INCLUDES}")
We use get_target_property
to query the INCLUDE_DIRECTORIES
property of the target. This retrieves all include directories associated with the target, combining both global directories set with include_directories
and target-specific directories set with target_include_directories
.
Run the following command to generate the build files:
cmake -S . -B build
The command will print messages to the console. One of these messages will display the target's include directories. Example output:
-- /home/ubuntu/myproject/lib/include;/home/ubuntu/myproject/include
CMake returns a semicolon-separated list of absolute include directories for the given target.
Leave a Comment
Cancel reply