假设我有一个项目看起来像:
Project (dir)
-- CMakeLists.txt
-- MyLib (dir)
|-- CMakeLists.txt
|-- MyLib.h
|-- MyLib.cpp
-- MyOtherLib (dir)
|-- CMakeLists.txt
|-- MyLib.h (note that this is exactly the same name as in MyLib above)
|-- MyLib.cpp如果我在MyLib/CMakeLists.txt中这样做:
target_include_directories(MyLib PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>然后,target_link_libraries到MyLib的任何内容都将包含执行#include "MyLib.h"的“正确”路径。但是,如果另一个可执行MyExecutable依赖于使用target_link_libraries(MyExecutable MyLib MyOtherLib)的两个库,那么您希望能够使用#include "MyLib/MyLib.h"或#include "MyOtherLib/MyLib.h"指定哪个库。我看到这样做的唯一方法是使用:
target_include_directories(MyLib PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/..>哪种类型会使target_include_directories的优点之一落空,因为它能很强地避免意外的头依赖,因为您实际上不能包含那些您没有明确声明要使用的内容。
还有其他方法可以获得这种#include "MyLib/MyLib.h"行为吗?
发布于 2017-03-30 21:39:57
您应该重新考虑目录树,如下所示:
Project (dir)
-- CMakeLists.txt
-- MyLib (dir)
|-- CMakeLists.txt
|-- src (dir)
MyLib.cpp
|-- include/MyLib (two dirs)
MyLib.h
-- MyOtherLib (dir)
|-- CMakeLists.txt
|-- src (dir)
MyLib.cpp
|-- include/MyOtherLib (two dirs)
MyLib.h这样可以避免包含../,即Project、文件夹和其中的所有内容,这不是一种干净的方法,如果将来添加其他文件/文件夹,可能会导致其他问题。然后,您可以使用MyLib/CMakeLists.txt编写
target_include_directories(MyLib PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>/include)在MyOtherLib/CMakeLists.txt中
target_include_directories(MyOtherLib PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>/include)因此,您将能够在任何程序中编写#include "MyLib/MyLib.h"和#include "MyOtherLib/MyLib.h",这些程序链接到构建树中的库中。
如果还想区分构建树和安装树之间的包含目录,请查看目录文档和有用的cmake生成器表达式。
https://stackoverflow.com/questions/43127301
复制相似问题