python - 将 CMake 指向 conda env 中的正确 Python 标头?
问题描述
我正在尝试在 C++ 中嵌入 Python 代码并在 Conda 环境中使用这些包。我有:
// main.cpp
#include <Python.h>
int main(int argc, char *argv[]) {
Py_Initialize();
return 0;
}
在 CMakeLists.txt 我添加了:
find_package(Python3 COMPONENTS Interpreter Development)
我在我的 Conda env(称为venv
)活动的情况下运行 cmake。当我尝试编译时,我得到:
/home/myself/.conda/envs/venv/bin/python3.7 (found version "3.7.7") found components: Interpreter Development
但是当我跑步时,make
我得到:fatal error: Python.h: No such file or directory
. 所以我做了一个locate Python.h
,我发现了几个Python.h
文件:
/home/myself/.conda/envs/venv/include/python3.7m/Python.h
/home/myself/.conda/envs/venv/lib/python3.7/site-packages/tensorflow/include/external/local_config_python/python_include/Python.h
/home/myself/.conda/pkgs/python-3.7.7-hcff3b4d_5/include/python3.7m/Python.h
我尝试将#include <Python.h>
main.cpp中的#include <PATH>
PATH 替换为上面列出的路径之一。在所有三种情况下,我都会收到一个新错误:
undefined reference to 'Py_Initialize'
有人可以指出我在这里缺少什么吗?另外我在这台机器上没有 sudo 权限
更新: 这个问题和 Guillame Racicot 的解决方案适用于 cmake 版本 1.13.5。正如 Guillame 所指出的,对于不同版本的 cmake,解决方案可能会有所不同。
解决方案
使用时find_package
,您还必须将其链接到您的目标:
find_package(Python3 REQUIRED COMPONENTS Interpreter Development)
add_executable(main main.cpp)
# Adds the proper include directories and link to libraries
target_link_libraries(main PUBLIC Python3::Python)
关于 CMake 工作原理,以及目标和导入目标如何工作的文档,请参阅cmake-buildsystem(7)。
要了解导入时要做什么,请参阅该模块的文档。例如,这里是FindPython3的文档。有一个要链接到的所有目标的列表以及可以找到的所有组件。
推荐阅读
- python - 难以创建 XLSM 文件
- javascript - 为数组的每个对象创建一个编辑函数
- r - 如何在 ZillowR 中使用 zillow api
- javascript - 为 Vuetify v-checkbox 指定真/假值
- google-chrome - Chrome中的iframe不显示图像
- c++ - Clang - 获取 SubstTemplateTypeParm 完整模板信息
- node.js - 我在“npm install”上得到“拒绝访问”
- python - 使用烧瓶加载和预测 keras 模型时的最佳实践
- css - 我的背景颜色 CSS 不会填满整个部分
- javascript - 重叠梯子时如何设置玩家移动能力