我试图使用C扩展名文件构建共享库,但首先必须使用以下命令生成输出文件:

gcc -Wall utilsmodule.c -o Utilc

执行命令后,我收到以下错误消息:

> utilsmodule.c:1:20: fatal error: Python.h: No such file or directory
compilation terminated.

我已经在互联网上尝试了所有建议的解决方案,但问题仍然存在。我对Python.h没有问题。我设法在我的机器上找到了该文件。


当前回答

如果您在Amazon Linux上使用Python 3.6(基于RHEL,但此处给出的RHEL答案无效):

sudo yum install python36-devel

其他回答

我在ubuntu中安装coolprop时也遇到了这个错误。

对于ubuntu 16.04和python 3.6

sudo apt-get install python3.6-dev

如果这不起作用,请尝试安装/更新gcc-lib。

sudo apt-get install gcc

对于OpenSuse的同志们:

sudo zypper install python3-devel

若您使用cmake构建项目,可以使用这个示例。

cmake_minimum_required(VERSION 2.6)
project(demo)
find_package(PythonLibs REQUIRED)
include_directories(${PYTHON_INCLUDE_DIRS})
add_executable(demo main.cpp)
target_link_libraries(demo ${PYTHON_LIBRARIES})

如果您已经安装了Python,并且希望链接到特定的Python版本,则可以从Python获取相关的include路径。

>>> import sysconfig
>>> sysconfig.get_path('include')
'/usr/include/python3.10' # Example output

您可以使用shell脚本手动指定特定python版本的包含路径/构建:

#!/bin/sh
python_include=$(python3.10 -c "import sysconfig; print(sysconfig.get_path('include'))")
gcc -Wall utilsmodule.c -o Utilc -I"$python_include"

我遇到的情况是我的Python.h位于/usr/include/python3.8和/usr/include/pyton2.7目录中,只需通过类似的方式给出gcc的路径-I/usr/include/pymon3.8即可python的版本替换为您的版本