【问题标题】:CMake FindPython Oddity: MSVC is not linking the library CMakes instructs to linkCMake FindPython Oddity:MSVC 未链接 CMakes 指示链接的库
【发布时间】:2020-06-06 17:12:52
【问题描述】:

我正在测试我的 cmake python-extension 设置实用程序,遇到了我自己似乎无法解决的奇怪行为。

本质上,我的CMakeLists.txt 归结为两行:

find_package(Python3 COMPONENTS Interpreter Development REQUIRED)
...
Python3_add_library (${TARGET} SHARED ${SRCS})

当我尝试在调试模式下构建时,MSVC 2019 出现链接器错误:

LINK : fatal error LNK1104: cannot open file 'python37_d.lib'

我正在使用 conda,但我知道我的 PC 上没有调试库。所以,我开始四处挖掘,看看我是否可以绕过它:主要是为了链接到发布库,python37.lib...

this stackoverflow post的帮助下,我打印了所有的目标属性,找到了相关入口:

mymath LINK_LIBRARIES = Python3::Python

这表明使用了 IMPORTED 目标 FindPython3 配置。所以,我也打印了它的属性,发现:

Python3::Python IMPORTED_IMPLIB = C:/Users/tikum/miniconda3/libs/python37.lib

疑惑中,我查看了build目录下对应的.vcxproj,发现

<ImportLibrary>
C:/Users/tikum/Documents/Python/python-cmaketools-cpython-example/build/src/cpython_example/mymath/Debug/mymath.lib
</ImportLibrary>

所以,我完全没有找到任何链接到python37_d.lib 的痕迹......有人可以告诉我这里发生了什么吗?

P.S.,我正在尝试编译的示例 C 代码是我在网上找到的 Martino Pilia 示例的逐行副本。

【问题讨论】:

  • @CristiFati - 我之前看过那篇文章,但这是不行的。我收到配置时错误:The keyword signature for target_link_libraries has already been used with the target "mymath". All uses of target_link_libraries with a target must be either all-keyword or all-plain.
  • @CristiFati - 是的,这与下面的答案相同。

标签: python visual-c++ cmake


【解决方案1】:

您必须取消定义 DEBUG 或 _DEBUG,不记得了,在您的代码中包含的 python.h 周围,因为 Python 与 pragma 指令链接。所以和cmake无关。

类似的东西

#ifdef DEBUG
#undef DEBUG
#include <Python.h>
#define DEBUG
#else
#include <Python.h>
#endif

应该做的伎俩

【讨论】:

  • 其实,我已经尝试过了(虽然当时只有_DEBUG,但`DEBUG 也不起作用)。
  • 奇怪的是我们在代码中使用的。 python dll 使用#pragma comment(lib, "python....lib") 链接。尝试在 python 标头中找到该代码,您将找到要取消定义的正确变量。这就是在 Windows 上执行此操作的方法。
  • 好吧,我之前一定是试错了,undef _DEBUG 确实成功了!谢谢
  • 是的,当我深入研究时,我看到了#pragma 行(直到今天我才知道你可以像这样链接,非常漂亮)
猜你喜欢
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多