How to `target_include_directories`, but for a single header file?

Imagine that I have this tree:

.
├── CMakeLists.txt
└── subdir
    ├── CMakeLists.txt
    ├── dont_include_this.h
    └── include_this.h

How do I setup my CMake project to be able to #include "include_this.h" but to not be able to #include "dont_include_this.h"?

Try the following in subdir/CMakeLists.txt:

# https://cmake.org/cmake/help/latest/command/configure_file.html
configure_file(include_this.h include_this.h COPYONLY)

target_include_directories(foobar PRIVATE ${CMAKE_CURRENT_BINARY_DIR})

This just copies the file (as needed) into the current binary directory. Then you add the current binary directory as an include directory. Essentially you are just making a new include directory that doesn’t have dont_include_this.h.

1 Like

Note that this solution requires a rerun of CMake if include_this.h changes. You’ll want add_custom_command(cmake -E copy_if_different) to do it at build time. However, it is probably better to just split the headers in the source tree in the first place:

subdir/include/include_this.h
subdir/private/dont_include_this.h

and then use PRIVATE and PUBLIC directories to target_include_directories as appropriate.