本文介绍了用CMake创建和使用库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想学习CMake,但我无法掌握可用的教程。

I'm trying to learn CMake, but I can't get to grips with the tutorials that are available.

假设我的项目具有以下结构,并且我想通过其CMakeLists文件使my_lib可用,并在main.cpp中使用它,我的CMakeLists文件将是什么喜欢?

Let's say my project has the structure below, and I want to make my_lib available through its CMakeLists file and use it in my main.cpp, what would my CMakeLists files look like?

├── CMakeLists.txt
├── externals
│   └── my_lib
│       └── src
│           ├── CMakeLists.txt
│           ├── MyClass.h
│           └── MyClass.cpp
└── main.cpp

我应该使用include_directories还是add_subdirectory?

Should I use include_directories or add_subdirectory?

推荐答案

为了匹配您指定的目录结构,您的CMakeLists.txt文件可能如下所示:

To match the directory structure you indicated, your CMakeLists.txt files could look like this:

/CMakeLists.txt:

/CMakeLists.txt:

cmake_minimum_required(VERSION 3.0)
project(Main)
add_subdirectory(externals/my_lib/src)
add_executable(my_main main.cpp)
target_link_libraries(my_main my_lib)

/ externals / my_lib /src/CMakeLists.txt:

/externals/my_lib/src/CMakeLists.txt:

cmake_minimum_required(VERSION 3.0)
project(MyLib)
add_library(my_lib MyClass.cpp MyClass.h)
target_include_directories(my_lib PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})

target_include_directories 调用中使用 PUBLIC 意味着您的库不仅将此作为包含路径

Using PUBLIC in the target_include_directories call means that not only does your library have this as an "include path", but so does any target linking to it.

这个设置的缺点是,你还要公开任何内部头文件 my_lib

The downside with this setup however is that you're also going to expose any internal headers of my_lib to consuming targets too. Say you also have an "Internal.h" as part of my_lib which you don't want to expose. You can do this by moving the intentionally-public headers into a separate folder, e.g. "include":

├── CMakeLists.txt
├── externals
│   └── my_lib
│       ├── CMakeLists.txt
│       ├── include
│       │   └── MyClass.h
│       └── src
│           ├── Internal.h
│           └── MyClass.cpp
└── main.cpp

您的顶级CMakeLists.txt不会更改,但/externals/my_lib/CMakeLists.txt(已升级了一级)现在显示为:

Your top-level CMakeLists.txt wouldn't change, but /externals/my_lib/CMakeLists.txt (which has moved up a level) now reads:

cmake_minimum_required(VERSION 3.0)
project(MyLib)
add_library(my_lib src/MyClass.cpp src/Internal.h include/MyClass.h)
target_include_directories(my_lib
    PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include
    PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src
    )

现在,由于你的库的src文件夹是 PRIVATE my_lib ,main。 cpp将不能 #includeInternal.h

Now, since your library's "src" folder is PRIVATE to my_lib, main.cpp won't be able to #include "Internal.h".

这篇关于用CMake创建和使用库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 05:04