ImportError: dynamic module does not define init function (initfizzbuzz)

Worth notify - same error can occur if library is compiled for different python version. For example, if shared object is for python 3, but you try to import module from python 2.


Python doesn't and cannot support arbitrary C files as modules. You'll have to follow certain conventions to let Python know what functions your module supports.

To do so, Python will look for a init<name> function, where <name> is the module name. Python was looking for initfizzbuzz but failed to find it, so loading the module failed.

Apart from an initialiser, you also need to provide a structure detailing what functions are available, and your function will need to handle Python types as arguments. Python provides you with the necessary utility functions and defines to make that easy enough.

I strongly urge you follow the Extending and Embedding the Python Interpreter tutorial. It teaches you everything you need to know to make your fizzbuzz C code work as a Python module.


The error also occurs, when using boost::python, if the module name is different to the compiled .so file name. For example:

hello.cpp

#include <boost/python/module.hpp>
#include <boost/python/def.hpp>
using namespace std;
using namespace boost::python;

int helloWorld(){
    cout << "Hello world!" << endl;
    return 0;
}

BOOST_PYTHON_MODULE(libhello) {
    def("hello_world", helloWorld);
}

compilation command:

g++ -fpic -shared -o libfoo.so -Wl,-soname,"libfoo.so" hello.cpp -I<path/to/python> -L/usr/local/lib  -lboost_python-py34

When including in python with import libfoo the following error occurs:

ImportError: dynamic module does not define init function (PyInit_libfoo)

This is because of "libhello" and "libfoo" do not match.