将 CMake 指向 conda env 中的正确 Python header?
Point CMake to proper Python header inside conda env?
我正在尝试在 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)
我 运行 cmake 和我的 Conda 环境(称为 venv
)处于活动状态。当我尝试编译时,我得到:
/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
我尝试将 main.cpp 中的 #include <Python.h>
替换为 #include <PATH>
,其中 PATH 被替换为上面列出的路径之一。在这三种情况下,我都会收到一个新错误:
undefined reference to 'Py_Initialize'
有人可以指出我在这里遗漏了什么吗?另外我在这台机器上没有 sudo 权限
更新:
这个问题和 Guillame Racicot 的解决方案适用于 cmake 版本 1.13.5。正如 Guillame 指出的那样,解决方案可能因不同版本的 cmake 而异。
当使用 find_package
时,您还必须 link 将其设置为您的目标:
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 的文档。有一个 link 的所有目标列表以及可以找到的所有组件。
我正在尝试在 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)
我 运行 cmake 和我的 Conda 环境(称为 venv
)处于活动状态。当我尝试编译时,我得到:
/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
我尝试将 main.cpp 中的 #include <Python.h>
替换为 #include <PATH>
,其中 PATH 被替换为上面列出的路径之一。在这三种情况下,我都会收到一个新错误:
undefined reference to 'Py_Initialize'
有人可以指出我在这里遗漏了什么吗?另外我在这台机器上没有 sudo 权限
更新: 这个问题和 Guillame Racicot 的解决方案适用于 cmake 版本 1.13.5。正如 Guillame 指出的那样,解决方案可能因不同版本的 cmake 而异。
当使用 find_package
时,您还必须 link 将其设置为您的目标:
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 的文档。有一个 link 的所有目标列表以及可以找到的所有组件。