Python.h found by locate but not by GCC

I just wrote a simple C executable to check if Python.h is working or not

#include<Python.h>
#include<stdio.h>
int main()
{
    printf("this is a python header file included programm\n");
    return 0;
}

Obviously, it does not do much. However, when I try to compile it with gcc it gives me an error:

foo.c:1:19: fatal error: Python.h: No such file or directory.

Then I checked to see if the python-dev Install python-dev package has Python.h installed or not using locate.

$locate Python.h
/usr/include/python2.7/Python.h

It is clear to me that I have the Python.h header file on my system. How do I get my executable working?


Solution 1:

You need to qualify your include

#include <python2.7/Python.h>

Or tell gcc where to find Python.h with the

gcc -I /usr/include/python2.7/ program.c 

Solution 2:

You need to provide GCC with the include path for the Python.h header. This can be done with the -I flag:

gcc -c -I/usr/include/python2.7 sourcefile.c

However, there is a better way: use pkg-config Install pkg-config:

pkg-config --cflags python

This will output the flags that need to be passed to GCC in order to compile applications that use the Python headers and libraries.

When linking, use the output of this command to include the appropriate libraries:

pkg-config --libs python

You could even combine both steps with:

gcc `pkg-config --cflags --libs python` sourcefile.c