This is my project tree:
project
| + src
| + external
| | + foo
| | | + include
| | | | - foo.hpp
| | | + src
| | | | - foo.cpp
| | | | - CMakeLists.txt
| | | - CMakeLists.txt
| | + CMakeLists.txt
| + src
| | - main.cpp
| - CMakeLists.txt
foo.cpp includes foo.hpp:
// foo.cpp
#include "foo.hpp"
Now the problem is that including the directory in the top CMake successfully find foo.hpp, but if I include in the subproject it doesn't. Any reason for it? (directories are included before the executable is compiled).
// project/CMakeLists.txt
include_directories(external/foo/include) //OK
add_subdirectory(external)
add_executable(main main.cpp)
target_link_libraries(main foo)
// project/external/CMakeLists.txt
add_subdirectory(foo)
// project/external/foo/CMakeLists.txt
include_directories(include) // NOT WORKING
add_subdirectory(src)
// project/external/foo/src/CMakeLists.txt
add_library(foo foo.cpp)
Add include directories to the build. Add the given directories to those the compiler uses to search for include files. Relative paths are interpreted as relative to the current source directory.
include_directories(x/y) affects directory scope. All targets in this CMakeList, as well as those in all subdirectories added after the point of its call, will have the path x/y added to their include path. target_include_directories(t x/y) has target scope—it adds x/y to the include path for target t .
To include headers in CMake targets, use the command target_include_directories(...) . Depending on the purpose of the included directories, you will need to define the scope specifier – either PUBLIC , PRIVATE or INTERFACE .
First, you use include_directories() to tell CMake to add the directory as -I to the compilation command line. Second, you list the headers in your add_executable() or add_library() call.
Quoting the documentation for include_directories
:
The include directories are added to the directory property INCLUDE_DIRECTORIES for the current CMakeLists file. They are also added to the target property INCLUDE_DIRECTORIES for each target in the current CMakeLists file. The target property values are the ones used by the generators.
The INCLUDE_DIRECTORIES
directory property is inherited to all subdirectories and all targets in the directory.
${CMAKE_CURRENT_SOURCE_DIR}
for include_directories
is redundant as relative paths are interpreted as relative to this directory by default. You should throw it out to increase readability.get_property
and message
to double-check that all directories and targets end up with the correct entries in their INCLUDE_DIRECTORIES
property.include_directories
completely and use target_include_directories
instead. This has the advantage that include dependencies get resolved on a per-target basis exclusively which is usually the more desirable behavior.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With