cmake - 通过ExternalProject_Add 使用 pybind11 进行 CMake 项目的智能方法

标签 cmake pybind11

我正在使用 pybind11CMake 3.9.4 编写一个 python 模块。 为了方便起见,我希望使用 CMakeLists.txt 中的 ExternalProject_Add 下载 pybind11 源文件。

当我运行 cmake . 时,它不会下载 pybind11 源文件,并引发错误。

CMake Error at CMakeLists.txt:21 (add_subdirectory):
  The source directory
    /Users/me/foo/pybind11_external-prefix/src/pybind11_external
  does not contain a CMakeLists.txt file.

CMake Error at CMakeLists.txt:22 (pybind11_add_module):
  Unknown CMake command "pybind11_add_module".

有一个解决方法:

  1. 注释掉 CMakeLists.txt 中的最后 3 行
  2. 运行cmake。
  3. 运行make(然后,它下载pybind11源文件)
  4. 恢复 CMakeLists.txt 中的最后 3 行
  5. 运行cmake。
  6. 运行make

但是,这并不聪明...有没有办法使用 ExternalProject_Add 下载 pybind11 而无需注释掉这些行并恢复它们(并且无需运行 cmakemake 两次)?

/Users/me/foo/CMakeLists.txt

cmake_minimum_required(VERSION 3.8)
project(foo)
set(CMAKE_CXX_STANDARD 14)

include(ExternalProject)
ExternalProject_Add(
        pybind11_external
        GIT_REPOSITORY https://github.com/pybind/pybind11.git
        GIT_TAG v2.2.1
        CONFIGURE_COMMAND ""
        BUILD_COMMAND ""
        INSTALL_COMMAND ""
)
set(PYBIND11_CPP_STANDARD -std=c++14)
ExternalProject_Get_Property(pybind11_external source_dir)
include_directories(${source_dir}/include)

add_subdirectory(${source_dir})             # comment out, then restore this line
pybind11_add_module(foo SHARED foo.cpp)     # comment out, then restore this line
add_dependencies(foo pybind11_external)     # comment out, then restore this line

/Users/me/foo/foo.hpp

#ifndef FOO_LIBRARY_H
#define FOO_LIBRARY_H

#include<pybind11/pybind11.h>

int add(int i, int j);

#endif

/Users/me/foo/foo.cpp

#include "foo.hpp"

int add(int i, int j) {
    return i + j;
}

PYBIND11_MODULE(example, m) {
    m.doc() = "pybind11 example plugin";
    m.def("add", &add, "A function which adds two numbers");
}

最佳答案

使用 CMake 的 FetchContent模块(版本 3.11+),你可以这样做:

include(FetchContent)
FetchContent_Declare(
    pybind11
    GIT_REPOSITORY https://github.com/pybind/pybind11
    GIT_TAG        v2.2.3
)

FetchContent_GetProperties(pybind11)
if(NOT pybind11_POPULATED)
    FetchContent_Populate(pybind11)
    add_subdirectory(${pybind11_SOURCE_DIR} ${pybind11_BINARY_DIR})
endif()

这将在配置时下载 pybind11,并add_subdirectory 它。然后您就可以调用 pybind11_add_module

关于cmake - 通过ExternalProject_Add 使用 pybind11 进行 CMake 项目的智能方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47027741/

相关文章:

xcode - CMake:如何在 *nix 系统上使用所有内核构建外部项目?

CMake:构建静态二进制文件

c++ - 在CMake文件中添加头文件文件夹路径

c++ - CMake 中的预期构建失败测试

python - 具有自定义持有者类型的 pybind11 多重继承无法转换为基本类型

CMake 找不到自定义模块

python - 如何使用pybind11返回一个DataFrame?

python - 从 C++ 嵌入式解释器捕获 python 窗口输出

python - fatal error : Python. h:编译pybind11示例时没有这样的文件或目录