All the contents in this note are summarized from two Cython tutorials:

  • Smith, Kurt W. Cython: A Guide for Python Programmers. “ O’Reilly Media, Inc.”, 2015.
  • Herron, Philip. Learning Cython Programming. Packt Publishing Ltd, 2016.


  • Compile by hand
  1. From file.pyx to file.c (c file)
cython file.pyx

Type $cython to check all the options available for cython such as –cplus(instead of generating file.c, file.cpp is generated) –embed(embed the python interpreter) -2 -3 (compile based on python 2 or python 3 syntax and code semantic), etc.

  1. From file.c to file.o (object file)
gcc -g -O2 -fpic `python-config --cflags` -c file.c -o file.o
  1. From file.o to (dynamic library)
gcc -shared -o file.o `python-config --libs`
LDFLAGS=$(python-config --ldflags)
gcc file.o -o -shared ${LDFLAGS}
  • pyximport module (very convenient! import .pyx just like importing .py module) Get the file.pyx ready and in python or ipython:
import pyximport
import file

Calling C functions from Python

  • AddFunction.c
#include <stdio.h>
int AddFunction(int a, int b){
  printf("Look we are within your c code!!\n")
  return a + b;
  • AddFunction.h
#ifndef __ADDFUNCTION_H__
#define __ADDFUNCTION_H__

extern int AddFunction (int, int);

#endif //__ADDFUNCTION_H__
  • PyAddFunction.pyx
cdef extern from "AddFunction.h"
  cdef int AddFunction(int, int)

#Python entry point - calling C function
def Add(a, b)
  return AddFunction(a, b)
  • Compile
cython PyAddFunction.pyx

gcc -g -O2 -fpic -c PyAddFunction.c -o PyAddFunciton.o `python-config --includes`
gcc -g -O2 -fpic -c AddFunction.c -o AddFunction.o
gcc -g -O2 -shared -o AddFunction.o PyAddFunction.o `python-config --libs`
  • Load function
from PyAddFunction import Add