1

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.

2
  • 1
    When you compile your c file use -fPIC aswell as -c to compile as position independent code. As required by shared libraries. Commented Feb 14, 2015 at 0:52
  • It worked Paul. Thanks a lot for your input. Compilation command: gcc -shared -I/usr/include/python2.7 -fPIC foo.c -o foo.so Commented Feb 16, 2015 at 19:08

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Yes Paul you are correct. When i compiled with -fPIC option it got completed successfully. I am able to import the module in Python shell and it got executed as expected. Thanks a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.