本文介绍了Python和C ++:如何在Cmakelists(包括GSL库)中使用pybind11的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够将我的C ++代码作为python包进行调用。为此,我将 pybind11 与CMakelists一起使用(以下示例)。我的问题是我必须在代码的编译中包括GSL库,并且这些库需要显式链接器 -lgsl

I want to be able to call my C++ code as a python package. To do this I am using pybind11 with CMakelists (following this example https://github.com/pybind/cmake_example). My problem is that I have to include GSL libraries in the compilation of the code, and these need an explicit linker -lgsl .

如果我只是编译并运行C ++而没有用python封装,则下面的Cmakelists.txt文件即可完成工作

If I were just to compile and run the C++ without wrapping it with python, the following Cmakelists.txt file does the job

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 不起作用。

but when using pybind11 the template I found doesn't allow the add_executable therefore target_link_libraries doesn't work.

我已经试过了

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)

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

but this produces errors in the building.

有什么想法吗?

推荐答案

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

Function pybind11_add_module creates a library target, which can be used for link added module with other libraries:

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

中明确说明了:

This is explicitely stated in documentation:

这篇关于Python和C ++:如何在Cmakelists(包括GSL库)中使用pybind11的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 00:46