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

问题描述 投票:0回答:6

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

我想将 Python 应用程序嵌入到我的 C++ 代码中。为此,需要包含

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。)

c++ python include cmake kdevelop
6个回答
77
投票

在 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

58
投票
sudo apt-get install pythonX.X-dev

例如3.8

sudo apt-get install python3.8-dev

谢谢 Cristianjs19 的评论。

原答案:

sudo apt-get install python2.7-dev

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


15
投票

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

`python-config --cflags`

链接线上有这个:

`python-config --ldflags`

6
投票

很可能

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

dpkg -L python-dev | grep Python.h

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

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

编辑:

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


5
投票

对于 Linux Ubuntu Putty 用户试试这个:

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

然后编译

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

然后运行它

./check 

4
投票

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

find / -iname python.h

完成后,在编译时添加

-I python_h_path
© www.soinside.com 2019 - 2024. All rights reserved.