首页 > 解决方案 > target_include_directories() does not find header files

问题描述

In my project I try to practice good Cmake usage and want to change all include_directories() to target_include_directories(). My project structure is like this:

Project
| CMakeLists.txt
|--external
|--Lib_A
|   CmakeLists.txt
|--Lib_B
|   CmakeLists.txt
|-- ...

My Project/CmakeLists.txt looks like this:

add_subdirectory(Lib_A)
add_subdirectory(Lib_B)

and the Lib_A/CmakeLists.txt like this:

set(SOURCES file1.cpp file1.h file2.cpp file2.h ...)
add_library(Lib_A STATIC ${SOURCES})
target_include_directories(Lib_A PRIVATE
   ${CMAKE_SOURCE_DIR}/Lib_B
   ${CMAKE_SOURCE_DIR}/external/rapidjson/include
)

now we're getting where an Error occurs. Lib_B/CmakeLists.txt is

set(SOURCES fileX.cpp fileX.h fileY.cpp fileY.h ...)
add_library(Lib_B STATIC ${SOURCES})
target_include_directories(Lib_B PUBLIC
   ${CMAKE_SOURCE_DIR}/Lib_A
   ${CMAKE_SOURCE_DIR}/external/rapidjson/include
   ...
)
target_link_libraries(Lib_B PUBLIC Lib_A Lib_C Lib_D ...)

Now I get an error when building the project stating in a .cpp file of Lib_B, it does not find an include Lib_A/file2.h: "No such file or directory". I already tried switching the keywords PUBLIC, PRIVATE and INTERFACE but nothing seems to work, except that I get more errors about not finding headers in Lib_A when I set the keyword from PRIVATE to PUBLIC or INTERFACE. Funny thing is, if I make this change in Lib_B/CmakeLists.txt

set(SOURCES fileX.cpp fileX.h fileY.cpp fileY.h ...)
include_directories(${CMAKE_SOURCE_DIR}/Lib_A) #this was taken..
add_library(Lib_B STATIC ${SOURCES})
target_include_directories(Lib_B PUBLIC
   ${CMAKE_SOURCE_DIR}/external/rapidjson/include
   ...                                         #..from here
)
target_link_libraries(Lib_B PUBLIC Lib_A Lib_C Lib_D ...)

the error does not occur anymore. So it seems to be local error having something to do with the target_dir... command, bit I do not see what's wrong and why it's not working.

标签: c++cmake

解决方案


I found the problem: The error came from another module, which includes a header which includes Lib_A/file2.h. Switching to the modern Cmake command blocked to other module from getting this include path and so the error was thrown.

Adding the include paths to the problematic module solved the issue.


推荐阅读