【问题标题】:Python and C++: How to use pybind11 with Cmakelists including GSL librariesPython 和 C++:如何将 pybind11 与 Cmakelists (包括 GSL 库)一起使用
【发布时间】:2018-04-23 09:57:58
【问题描述】:

我希望能够将我的 C++ 代码调用为 python 包。为此,我将 pybind11 与 CMakelists 一起使用(遵循此示例 https://github.com/pybind/cmake_example)。我的问题是我必须在代码编译中包含 GSL 库,并且这些库需要一个显式链接器 -lgsl

如果我只是编译和运行 C++ 而不用 python 包装,下面的 Cmakelists.txt 文件可以完成这项工作

cmake_minimum_required(VERSION 3.0)

set(CMAKE_BUILD_TYPE Debug)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14")

project(myProject)


add_executable(
    myexecutable
    main.cpp
    function1.cpp
)

find_package(GSL REQUIRED)
target_link_libraries(myexecutable GSL::gsl GSL::gslcblas)

但是当使用pybind11 时,我发现的模板不允许add_executable,因此target_link_libraries 不起作用。

我试过了

project(myProject)

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED YES)   # See below (1)



# Set source directory
set(SOURCE_DIR "project")

# Tell CMake that headers are also in SOURCE_DIR
include_directories(${SOURCE_DIR})
set(SOURCES "${SOURCE_DIR}/functions.cpp")


# Generate Python module
add_subdirectory(lib/pybind11)
pybind11_add_module(namr ${SOURCES} "${SOURCE_DIR}/bindings.cpp")


FIND_PACKAGE(GSL REQUIRED)
target_link_libraries(GSL::gsl GSL::gslcblas)

但这会在建筑物中产生错误。

有什么想法吗?

【问题讨论】:

  • 我希望任何投反对票的人发表评论。在没有解释的情况下投反对票是毫无用处的

标签: python c++ cmake pybind11


【解决方案1】:

函数pybind11_add_module创建一个库target,可用于将添加的模块与其他库链接:

pybind11_add_module(namr ${SOURCES} "${SOURCE_DIR}/bindings.cpp")
target_link_libraries(namr PUBLIC GSL::gsl GSL::gslcblas)

这在documentation中有明确说明:

这个函数的行为与 CMake 的内置函数 add_library 非常相似(实际上,它是该命令的包装函数)。它将添加一个名为<name> 的库目标,以从列出的源文件构建。此外,它将处理所有 Python 特定的编译器和链接器标志以及 OS 和 Python 版本特定的文件扩展名。生成的目标 <name> 可以使用常规 CMake 命令进一步操作。

【讨论】:

  • 非常感谢,我是 Cmake 新手,无法按我应该的方式浏览文档。然而,这现在产生了一个我无法理解的新错误:CMake Error at CMakeLists.txt:22 (target_link_libraries): The keyword signature for target_link_libraries has already been used with the target "namr". All uses of target_link_libraries with a target must be either all-keyword or all-plain
  • @Tsyvarev 如果gsl 安装在非标准目录中,如何使用它。例如。如果 gsl 安装在一个目录中,该目录位于 CMakeList.txt 文件所在的目录中。
  • @ankit7540:您可以通过设置CMAKE_PREFIX_PATH 变量来提示find_package GSL 的位置。看到我的回答:stackoverflow.com/a/34797156/3440745
猜你喜欢
  • 1970-01-01
  • 2019-11-14
  • 1970-01-01
  • 2020-10-07
  • 2016-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-16
相关资源
最近更新 更多