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


I am trying to build a shared library using a C extension file but first I have to generate the output file using the command below:

gcc -Wall utilsmodule.c -o Utilc

After executing the command, I get this error message:

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

I have tried all the suggested solutions over the internet but the problem still exists. I have no problem with Python.h. I managed to locate the file on my machine.

7/1/2020 3:45:41 AM

Accepted Answer

I managed to solve this issue and generate the .so file in one command

gcc -shared -o
-fPIC -I/usr/include/python2.7 -lpython2.7  utilsmodule.c
1/29/2016 1:43:48 AM

On Ubuntu, I was running Python 3 and I had to install

sudo apt-get install python3-dev

If you want to use a version of Python that is not linked to python3, install the associated python3.x-dev package. For example:

sudo apt-get install python3.5-dev

For Python 3.7 and Ubuntu in particular, I needed

sudo apt install libpython3.7-dev

. I think at some point names were changed from pythonm.n-dev to this.

for Python 3.6, similarly:

sudo apt install libpython3.6-dev

Two things you have to do.

Install development package for Python, in case of Debian/Ubuntu/Mint it's done with command:

sudo apt-get install python-dev

Second thing is that include files are not by default in the include path, nor is Python library linked with executable by default. You need to add these flags (replace Python's version accordingly):

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

In other words your compile command ought to be:

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

If you are using a Raspberry Pi:

sudo apt-get install python-dev

on Fedora run this for Python 2:

sudo dnf install python2-devel

and for Python 3:

sudo dnf install python3-devel