user3395194
user3395194

Reputation: 89

Python C binding error

I have written a Python API in C code and saved the file as foo.c.

Code:

#include <Python.h>
#include <stdio.h>

static PyObject *foo_add(PyObject *self, PyObject *args)
{
    int a;
    int b;

    if (!PyArg_ParseTuple(args, "ii", &a, &b))
    {
        return NULL;
    }

    return Py_BuildValue("i", a + b);
}

static PyMethodDef foo_methods[] = {
    { "add", (PyCFunction)foo_add, METH_VARARGS, NULL },
    { NULL, NULL, 0, NULL }
};

PyMODINIT_FUNC initfoo()
{
    Py_InitModule3("foo", foo_methods, "My first extension module.");
}

When i try to compile using the below mentioned command i am getting compilation error.

Command: gcc -shared -I/usr/include/python2.7 foo.c -o foo.so

Error: gcc -shared -I/usr/include/python2.7 foo.c -o foo.so /usr/bin/ld: /tmp/ccd6XiZp.o: relocation R_X86_64_32 against `.rodata' can not be used when making a shared object; recompile with -fPIC /tmp/ccd6XiZp.o: error adding symbols: Bad value collect2: error: ld returned 1 exit status

If i give compilation command with "-c" option, its getting compiled successfully and created the object file foo.so (This is the executable file).

I have to create a object file (without using -c option in compilation command) and import them in Python shell to verify it.

Please let me know what am i doing wrong here.

Upvotes: 1

Views: 346

Answers (1)

Paul Rooney
Paul Rooney

Reputation: 21609

In your compilation flags you should include -fPIC to compile as position independent code. This is required for dynamically linked libraries.

e.g.

gcc -c -fPIC foo.c -o foo.o
gcc -shared foo.o -o foo

or in a single step

gcc -shared -fPIC foo.c -o foo.so

Upvotes: 1

Related Questions