17

I'm trying to access a shared C library in Python with ctypes on Mac OS X 10.6.8 with Python 2.7.4. To do this, I need to #include <Python.h> in my C code. If I try to compile a C script that only has that one include statement in it, call it "sample.c", I get:

$ gcc -shared -o sample.so sample.c
sample.c:1:20: error: Python.h: No such file or directory

Since I'm running Mac 10.6, I have Xcode 3.2.6, the latest version available on this iteration of OS X without paying to upgrade to 10.7 and getting Xcode 4. Is there a way to get the Python header file without upgrading my OS?

Brett Morris
  • 791
  • 1
  • 4
  • 13
  • *Either* use `ctypes` *or* write your library as a Python extension (using `Python.h`). Doing both is rarely a good idea. – Cairnarvon May 09 '13 at 04:04

5 Answers5

34

Python is a framework on Mac OS X so you need to,

#include <Python/Python.h>

You also need to call gcc with the -framework argument to actually do anything inside C,

gcc -shared -o sample.so sample.c -framework Python
Jared
  • 25,627
  • 7
  • 56
  • 61
  • 3
    The convention is: use `#include ` and set the right `-I`-path to Python-headers (as other answers here have explained, e.g. https://stackoverflow.com/a/59074274/5769463). Prefixing includes with ` – ead Feb 26 '21 at 08:04
4

I'm not sure about 10.6.8, but Python.h should be in

/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7

if you installed the official python.org binary. Try adding

-I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7

to your gcc command and see if that works.

SashaZd
  • 3,315
  • 1
  • 26
  • 48
MattDMo
  • 100,794
  • 21
  • 241
  • 231
4

In case you have installed Python using Brew, it may be worthwhile to check the location of where your headers are. Try I/usr/local/Cellar/python/...

2

Another way is to add `python-config --include` to the gcc call. It will expand to -I/usr/..., so

gcc -shared -o sample.so sample.c `python-config --include`

Also other options can be retrieved, such as `python-config --cflags --ldflags`.

python-config or python3-config is typically available after brew install python. Backticks are bash-specific. To see what it would output (e.g., when one doesn't use bash) use

python-config --include
ttq
  • 383
  • 3
  • 7
  • please provide what `python-config` a non-standard module that doesn't currently work with 3.8, would output. – dlamblin Sep 27 '22 at 17:50
2

My problem was solved by install Xcode command line tools with:

xcode-select --install
jimkomni
  • 27
  • 5