c++ - 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.
解决方案
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.
推荐阅读
- kotlin - 如何从 Kotlin 引用 java.awt.Dimension 的公共字段
- sql - 按分组行选择空值 SQL Server
- javascript - Heroku 上未知的代币传播运营商,在本地工作
- angularjs - 将单选更改为多选 Google Map API
- performance - 有没有办法提高在 Elixir 中生成具有非重复随机数的列表的速度?
- java - 在二维数组中切换数组大小需要不同的内存量
- c# - 从数据库中搜索记录并在文本框和下拉列表中显示值
- c++ - 如何允许访问向量是类成员的向量元素?
- google-bigquery - BigQuery 问题:shwoing:不兼容的表分区规范
- css - 如何溢出模态中的列?