Linking Python with Xcode 12

February 14, 2021

Reading time ~1 minute

When Python is too limited or too slow you might want to write some code in C++. You can use the Python API to use it as an extension module.

Xcode comes with the Python2.7, which is deprecated. Below is a guide how to link python3. Note that in order to install a python module you need to run a small python script on your C++ code, so you can only use xcode for some part of the development.

I have python installed via brew but other sources should also work, when you adjust the paths.

Call python3-config --ldflags to obtain the path of -L/usr/local/opt/python@3.9/Frameworks/Python.framework/Versions/3.9/lib/python3.9/config-3.9-darwin -ldl -framework CoreFoundation

Open that file and drag libpython3.9.dylib to the framworks section. Confirm the dialog.

Screenshot showing xcode project with folder Frameworks

Open the Build Settings and search for "Header Search Paths". Fill in /usr/local/Cellar/python@3.9/3.9.1_3/Frameworks/Python.framework/Versions/3.9/include/python3.9

The path can be obtained by calling

python3-config --cflags

In your code include

#include <Python.h>

The compiler flags were different in the setup than in Xcode. Code compiled in Xcode but by calling the setup compilation failed. Set the compile flags in Xcode to "default" to have the same behavior.