0

为了让我的 .cpp 和 .h 文件稍微整理一下,等待他们的职责,我决定将它们放入单独的文件夹中,我使用了以下结构:


|
-CMakeLists.txt [rootCmakeList]
src
|
-main.cpp
.......|
....... 数学
.......|
.......-CMakeLists.txt[mathCmakeList]
.......-Algebra.h
.......-Algebra.cpp
....... XML [xmlCmakeList]
... ....|
.......-CMakeLists.txt
.......-AwesomeXML.h
.......-AwesomeXML.cpp

[rootCmakeList] 看起来:

cmake_minimum_required(VERSION 3.11.3)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED True)
set(CMAKE_CXX_FLAGS_DEBUG  "-g")

project(myProject)
#add exectuable
add_executable(myProject src/main.cpp)

target_include_directories(myProject PUBLIC "${src/XML}") 
target_include_directories(myProject PUBLIC "${src/math}") 

add_subdirectory(src/XML) 
add_subdirectory(src/math) 

target_link_libraries(myProject xml)#needed? 
target_link_libraries(myProject math)#needed? 

[mathCmakeList] 看起来:

include_directories(${myProject}src/math)
add_library(math Algebra.cpp) 

[xmlCmakeList] 看起来:

include_directories(${myProject}src/xml) 
add_library(xml AwesomeXML.cpp) 

到目前为止一切顺利,没有任何问题。但是如果我想#include Algebra.h 到 AweseomeXML.cpp 我找不到文件。

老实说,我什至不确定 cmake 命令add_librarytarget_link_libraries在这里是否真的有意义,因为我不想创建自己的库,只是想整理一下我的文件,等待他们的主题。

4

1 回答 1

1

myProject似乎不是您设置的变量。此外,如果您正确设置了库目标,则无需手动将任何包含目录添加到 myProject。

首先为 设置CMakeLists.txt文件math,因为它不依赖于其他项目。我建议将链接库使用的标头移动到子目录。我自己通常使用include,并且您希望链接库在#includes 中使用的任何路径都从那里开始。INTERFACE_INCLUDE_DIRECTORIES以将它们添加到的目标属性的方式设置包含目录math

add_library(math Algebra.cpp
    include/Algebra.h # for IDEs
)

target_include_directories(math # should be static here, since you don't want to deploy the lib by itself
    PUBLIC include # available to both math and linking libs
    PRIVATE .      # only available to math; only necessary, if there are "private" headers
)

然后对 执行相同的操作xml,但由于您使用的是来自 的功能math,因此您需要链接它,以便您自动访问其包含目录,因为它们可通过以下方式获得INTERFACE_INCLUDE_DIRECTORIES

add_library(xml STATIC
    AwesomeXML.cpp
    include/AwesomeXML.h
)

target_include_directories(xml PUBLIC include)

target_link_libraries(xml PRIVATE math) # change PRIVATE to PUBLIC, if Algebra.h is included in a public header

现在在顶层,我们应该确保在定义目标之前,目标的任何依赖项都是可用的。还链接一个库可以让您访问它们各自的公共包含目录和公共包含公开链接的依赖项的目录:

cmake_minimum_required(VERSION 3.11.3)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED True)
set(CMAKE_CXX_FLAGS_DEBUG  "-g")

project(myProject)

add_subdirectory(src/math)
add_subdirectory(src/XML) 

#add exectuable
add_executable(myProject src/main.cpp)

target_link_libraries(myProject PRIVATE math xml)
于 2021-02-06T21:18:15.877 回答