gpt4 book ai didi

python - 从 CMake 在 Windows/Visual Studio 中以 Debug模式强制链接 Python 发布库

转载 作者:太空宇宙 更新时间:2023-11-04 04:08:34 24 4
gpt4 key购买 nike

我正在使用 Boost Python 为 C++ 库开发 Python 绑定(bind),适用于 Linux 和 Windows (Visual Studio)。

在 Windows 中,静态 Boost Python 库对 Python 具有依赖性(这是另一个线程的动机,here),因此,在我的 CMake 配置中,我需要执行以下操作:

if((${CMAKE_SYSTEM_NAME} STREQUAL "Linux") OR APPLE)
target_link_libraries(my_python_module ${Boost_LIBRARIES})
elseif(WIN32 AND MSVC)
add_definitions(/DBOOST_PYTHON_STATIC_LIB)
target_link_libraries(my_python_module ${Boost_LIBRARIES}) #This includes the Boost Python library
# Even though Boost Python library is included statically, in Windows it has a dependency to the Python library.
target_link_libraries(my_python_module ${Python_LIBRARIES})
endif()

这在 Linux 中工作正常,但在 Windows 中,它只能在 Release 模式下工作,而不是在 Debug 模式下工作,在这种情况下我总是得到:

LINK: fatal error LNK1104:无法打开文件“python37.lib”

经过一番摸索后,我注意到问题是由 CMake 指示 Visual Studio 链接 'python37_d.lib' 而不是 'python37 引起的.lib' 在 Debug模式下。

但是,正如我在 linked issue 中所描述的那样, officially provided Boost Python debug 库链接到 Python release 库,而不是调试库。因此,解决方案是强制链接到 Python 发布库,而不管构建类型如何。不幸的是,${Python_LIBRARIES} 会根据模式自动设置库,我不想在我的代码中明确指定 python37.lib(因为我可以升级 Python而且我不想因此而更改我的 CMake 脚本)。

我发现了一些类似的问题 herehere ,但这并不能反射(reflect)我所面临的确切情况。基于这些,我尝试设置:

target_link_libraries(my_python_module optimized ${Python_LIBRARIES})

但这也没有用。所以,问题是:

有没有办法在 Debug模式下强制使用 Python 发布库 WITHOUT 必须显式设置它并让 Python CMake 包自动执行它。明确的意思是:

target_link_libraries(my_python_module python37)

非常感谢您的帮助。

最佳答案

kanstar 评论中建议的 set(Python_FIND_ABI "OFF""ANY""ANY") 似乎是执行此操作的正确方法。但是,虽然 Python_FIND_ABI 在 CMake 中 master , 它尚未在 latest version 中发布(撰写本文时为 v3.15.2)。

同时,也有依赖CMake版本的解决方案。

CMake 3.12 及以上版本

可以链接到 FindPythonPython_LIBRARY_RELEASE,这并不意味着是模块的 public interface 的一部分,但变量设置正确。

cmake_minimum_required (VERSION 3.12)
find_package(Python ..<choose your COMPONENTS; refer to FindPython docs>..)
if(WIN32 AND MSVC)
target_link_libraries(my_python_module ${Python_LIBRARY_RELEASE})
endif()

CMake 3.0.4 到 3.11

感谢@Phil 的评论,我们可以扩展答案以包括具有 FindPythonLibs 的早期 CMake 版本设置 PYTHON_LIBRARY_RELEASE 变量的模块。

cmake_minimum_required (VERSION 3.0)
find_package(PythonLibs ..<refer to FindPythonLibs docs>..)
if(WIN32 AND MSVC)
target_link_libraries(my_python_module ${PYTHON_LIBRARY_RELEASE})
endif()

关于python - 从 CMake 在 Windows/Visual Studio 中以 Debug模式强制链接 Python 发布库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56798472/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com