Python.h:没有这样的文件或目录

Python.h: No such file or directory

本文关键字:文件 Python      更新时间:2023-10-16

我最近在运行Ubuntu 12.04 LTS的Macbook Pro上安装了KDevelop 4用于C++开发。

我想在我的C++代码中嵌入 Python 应用程序。为此,需要包含Python.h头文件。所以,我做到了。

#include <iostream>
#include <Python.h>
int main(int argc, char **argv) {
    Py_Initialize();
    return 0;
}

但是,在运行时,我收到了来自 IDE 的以下响应:

fatal error: Python.h: No such file or directory

我已经安装了python-dev软件包。

所以,我认为一定是 KDevelop 未包含头文件的问题。因此,我将相关文件夹添加到包含路径中,KDevelop 通过删除上面代码中第二个包含语句下方的红色下划线立即识别出了这一点。

但是,问题仍然存在。我得到同样的错误。感谢您可以提供的任何帮助或意见:-)

(KDevelop 正在为我的项目使用 CMake。

在 CMakeLists.txt 中,尝试添加以下内容:

find_package(PythonLibs REQUIRED)
include_directories(${PYTHON_INCLUDE_DIRS})
target_link_libraries(<your exe or lib> ${PYTHON_LIBRARIES})

有关命令的详细信息,请运行:

cmake --help-module FindPythonLibs
cmake --help-command find_package
cmake --help-command include_directories
cmake --help-command target_link_libraries
sudo apt-get install pythonX.X-dev

例如,对于 3.8

sudo apt-get install python3.8-dev

谢谢克里斯蒂安js19的评论。

原答案:

sudo apt-get install python2.7-dev

为我解决了"Python.h:没有这样的文件或目录"问题

您希望在编译行中包含以下内容:

`python-config --cflags`

这在链接行上:

`python-config --ldflags`
很可能

Python.h不在构建系统的包含路径中。你可以通过运行来找出你的Python.h在哪里

dpkg -L python-dev | grep Python.h

这也将验证python-dev包是否实际安装了Python.h。

我这里没有kdevelop,但是大多数IDE都有一个设置,您可以在其中指定构建系统使用的包含路径,并且您应该能够添加Python.h所在的路径。

编辑:

正如 Nikolai 所暗示的那样,您还需要为链接阶段添加正确的库路径。(python-config --ldflags的输出)。

对于 Linux Ubuntu 腻子用户,请尝试以下操作:

sudo apt-get update
sudo apt-get install python-dev

然后编译它

gcc -o check xyz.c -I/usr/include/python2.7/ -lpython2.7

然后运行它

./check 

我假设它已经安装好了。查找路径:

find / -iname python.h

当你这样做时,在编译添加

-I python_h_path