首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >通过CMake使用pybind11实现项目ExternalProject_Add的智能方法

通过CMake使用pybind11实现项目ExternalProject_Add的智能方法
EN

Stack Overflow用户
提问于 2017-10-31 04:07:38
回答 1查看 5.7K关注 0票数 6

我正在使用pybind11CMake 3.9.4编写一个python模块。由于方便,我希望在我的pybind11中使用ExternalProject_Add下载ExternalProject_Add源文件。

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

代码语言:javascript
运行
复制
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

不过,这不明智..。是否有任何方法可以使用pybind11下载ExternalProject_Add,而无需注释行并恢复它们(也不需要运行cmakemake两次)?

/Users/me/foo/CMakeLists.txt

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
#ifndef FOO_LIBRARY_H
#define FOO_LIBRARY_H

#include<pybind11/pybind11.h>

int add(int i, int j);

#endif

/Users/me/foo/foo.cpp

代码语言:javascript
运行
复制
#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");
}
EN

回答 1

Stack Overflow用户

发布于 2018-09-13 10:26:27

使用CMake的FetchContent模块(version 3.11+),您可以这样做:

代码语言:javascript
运行
复制
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了。

票数 16
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47027741

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档