Python 和 C++:如何将 pybind11 与包括 GSL 库的 Cmakelist 一起使用

Python and C++: How to use pybind11 with Cmakelists including GSL libraries

我希望能够将我的 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)

但这会在构建中产生错误。

有什么想法吗?

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

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

这在documentation中有明确说明:

This function behaves very much like CMake’s builtin add_library (in fact, it’s a wrapper function around that command). It will add a library target called <name> to be built from the listed source files. In addition, it will take care of all the Python-specific compiler and linker flags as well as the OS- and Python-version-specific file extension. The produced target <name> can be further manipulated with regular CMake commands.