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

gcc -Wall utilsmodule.c -o Utilc

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

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

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


当前回答

如果您已经安装了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 dev的头文件和静态库。请使用包管理器在系统范围内安装它们。

对于apt(Ubuntu、Debian…):

sudo apt-get install python-dev   # for python2.x installs
sudo apt-get install python3-dev  # for python3.x installs

对于yum(CentOS,RHEL…):

sudo yum install python-devel    # for python2.x installs
sudo yum install python3-devel   # for python3.x installs

对于dnf(Fedora…):

sudo dnf install python2-devel  # for python2.x installs
sudo dnf install python3-devel  # for python3.x installs

对于zypper(openSUSE…):

sudo zypper in python-devel   # for python2.x installs
sudo zypper in python3-devel  # for python3.x installs

对于apk(Alpine…):

# This is a departure from the normal Alpine naming
# scheme, which uses py2- and py3- prefixes
sudo apk add python2-dev  # for python2.x installs
sudo apk add python3-dev  # for python3.x installs

对于apt-cyg(Cygwin…):

apt-cyg install python-devel   # for python2.x installs
apt-cyg install python3-devel  # for python3.x installs

注意:python3dev不会自动覆盖python3的所有次要版本,如果您正在使用例如python3.8,则可能需要安装python3.8-dev。

这意味着Python.h不在编译器的默认包含路径中。您是在系统范围内安装还是在本地安装?你的操作系统是什么?

您可以使用-I<path>标志来指定编译器应该在其中查找标头的附加目录。您可能需要使用-L<path>进行后续操作,以便gcc可以使用-L<name>找到要链接的库。

特别是对于Python 3.7和Ubuntu,我需要

sudo apt安装libpython3.7-dev

.我想在某些时候,名字从pythom.n-dev改成了这个。

对于Python 3.6、3.8到3.10(以及计数…),类似地:

sudo apt安装libpython3.6-dev 

sudo apt安装libpython3.8-dev 

sudo apt安装libpython3.9-dev

sudo apt安装libpython3.10-dev

如果您已经安装了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开发包,如果是Debian/Uubuntu/Mint,可以使用以下命令完成:

sudo apt-get install python-dev

第二点是,默认情况下,include文件不在include路径中,Python库默认情况下也不与可执行文件链接。您需要添加这些标志(相应地替换Python的版本):

-I/usr/include/python2.7 -lpython2.7 

换句话说,编译命令应该是:

gcc -Wall -I/usr/include/python2.7 -lpython2.7  utilsmodule.c -o Utilc