首页 > 解决方案 > CMake 和 pybind11 使用不一致的 Python 版本

问题描述

我正在Ubuntu(20.04)上的VSCode(1.46.1)中使用CMake(3.16.3)和pybind11(2.4.3)创建一个入门项目,默认情况下它同时具有Python 2.7和3.8。我想为 Python3 构建一个模块。当我在 CMakeLists.txt 中使用以下两行时

find_package(pybind11)
find_package(Python COMPONENTS Interpreter Development REQUIRED)

CMake配置是

[cmake] -- Found PythonInterp: /usr/bin/python (found version "2.7.18")  
[cmake] -- Found PythonLibs: /usr/lib/x86_64-linux-gnu/libpython2.7.so  
[cmake] -- Found Python3: /usr/bin/python3.8 (found version "3.8.2") found components: Interpreter Development 

切换 find_package 语句的顺序

find_package(Python COMPONENTS Interpreter Development REQUIRED)
find_package(pybind11)

提供相同的 python 链接,但使用新的顺序

[cmake] -- Found Python: /usr/bin/python3.8 (found version "3.8.2") found components: Interpreter Development 
[cmake] -- Found PythonInterp: /usr/bin/python (found version "2.7.18") 
[cmake] -- Found PythonLibs: /usr/lib/x86_64-linux-gnu/libpython2.7.so

我是新来的。我已经阅读了关于版本不一致的常见问题解答,但我认为我做的所有事情都是正确的(我不调用 find_package(PythonInterp) 或 find_package(PythonLibs),而是坚持使用 find_package(Python))。这似乎工作,似乎 find_package(pybind11) 默认为 python2.7 (如果我理解文档不正确),我不知道如何设置它。我已经尝试过类似的东西,# set(bindings_python_version 3.8)但这并没有改变任何东西。

我在一台基于 Windows 的机器上工作,但它只有一个版本的 Python,所以没有混淆的机会

标签: cmakepybind11

解决方案


所以最后,在调用set(PYBIND11_PYTHON_VERSION 3.8 CACHE STRING "")之前调用find_package(pybind11)解决了我的问题,尽管它不能帮助我理解为什么 pybind11 默认为 2.7。如果有人能指出我的解释,我将不胜感激。


推荐阅读