【问题标题】:Unable to build pybind11 example when using cmake due to undefined references由于未定义的引用,使用 cmake 时无法构建 pybind11 示例
【发布时间】:2022-01-04 21:21:14
【问题描述】:

由于对 python 标头的未定义引用,例如“对 `PyUnicode_AsUTF8AndSize' 的未定义引用”,我无法构建 pybind11 的示例

#include 不会导致问题,但是这样做会:

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

PYBIND11_MODULE(example, m){
    m.doc() = "pybind11 example plugin"; // optional module docstring

    m.def("add", &add, "A function which adds two numbers");
}

我想我正确添加了python库,所以idk:

cmake_minimum_required(VERSION 3.18)

project(sps LANGUAGES CXX)

find_package(Boost COMPONENTS unit_test_framework serialization REQUIRED)
find_package (Python COMPONENTS Interpreter Development REQUIRED)
find_package(PythonLibs REQUIRED)
add_subdirectory(extern/pybind11)

add_library(
    sps
    INTERFACE
    src/probtree.h
    src/node.h
    )
target_link_libraries(sps INTERFACE Boost::serialization)
target_include_directories(sps INTERFACE ${PYTHON_INCLUDE_DIRS})
target_include_directories(sps INTERFACE extern/pybind11/include)

set_target_properties(sps
    PROPERTIES
        CXX_STANDARD 20
        CXX_STANDARD_REQUIRED ON
    )

add_executable(main src/main.cpp)
target_link_libraries(main sps)

pybind11_add_module(
    sps_c

    src/probtree.h
    src/node.h
    src/main.cpp
    )
set_target_properties(sps_c PROPERTIES LINKER_LANGUAGE CXX)
target_link_libraries(sps_c INTERFACE sps)

add_executable(test_sps test/test_sps.cpp)
target_link_libraries(test_sps Boost::unit_test_framework sps)

我之前得到了这些未定义的引用,但 find_package (Python COMPONENTS Interpreter Development REQUIRED)target_include_directories(sps INTERFACE ${PYTHON_INCLUDE_DIRS}) 修复了它。

我认为链接 pybind11 模块可以工作 target_link_libraries(sps_c INTERFACE sps) 但不行。 如何修复未定义的引用?

【问题讨论】:

    标签: c++ cmake pybind11


    【解决方案1】:

    需要添加target_link_libraries(sps INTERFACE Boost::serialization ${PYTHON_LIBRARIES}) 才能找到python 定义。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-10
      • 2020-01-08
      • 1970-01-01
      • 1970-01-01
      • 2020-05-25
      • 1970-01-01
      • 2019-11-21
      • 2021-04-21
      相关资源
      最近更新 更多