1

I'm trying to embedding some Python code into C; It's the first time I do a thing like that.

Here is the simple code of my first attempt copied by a guide on internet:

#include <Python.h>
void exec_pycode(const char* code)
{
  Py_Initialize();
  PyRun_SimpleString(code);
  Py_Finalize();
}

int main(int argc, char **argv) {
    exec_pycode(argv[1]);
    return 0;
}

So I've installed python3.4-dev package.

Then for having info for the linker I typed:

pkg-config --cflags --libs python3

Then I tried to compile my code:

gcc -std=c99 -o main -I /usr/local/include/python3.4m  -L /usr/local/lib -lpython3.4m main.c

(according the command before)

but this is the result:

/tmp/ccJFmdcr.o: in function "exec_pycode":
main.c:(.text+0xd): reference undefined to "Py_Initialize"
main.c:(.text+0x1e): reference undefined to "PyRun_SimpleStringFlags"
main.c:(.text+0x23): reference undefined to "Py_Finalize"
collect2: error: ld returned 1 exit status

It would seem that there is a problem with linking phase, but I can't understend where is the problem seeing that i've passed to the linker the exact paths of the header and of the library. How can I solve that problem?

1 Answer 1

2

Try reordering your compilation command, such that all linking options are specified after your C source files:

gcc -std=c99 -o main -I /usr/local/include/python3.4m main.c \
  -L /usr/local/lib -lpython3.4m
Sign up to request clarification or add additional context in comments.

3 Comments

yes I've resolved the previous problem but now I've that problem: /usr/local/lib/libpython3.4m.a(pytime.o): in function "_PyTime_ObjectToTime_t": /home/matteo/Scrivania/Python-3.4.3/Python/pytime.c:212: undefined reference to "ceil" /home/matteo/Scrivania/Python-3.4.3/Python/pytime.c:214: undefined reference to "floor" /usr/local/lib/libpython3.4m.a(pytime.o): in function "_PyTime_ObjectToDenominator": /home/matteo/Scrivania/Python-3.4.3/Python/pytime.c:173: undefined reference to "ceil" ...(and all other maths functions) So I tried to recompile adding -lm but I didn't resolve the problem :/
@MatteoArella Where did you add -lm? Try a few different places - before -lpython3.4m and after, and see which one works. If neither works, try running python-config --ldflags in a terminal and use those as the linker flags.
Note that you may have to change the order of flags in the python-config output - if it doesn't work try moving -lpython3.4m after all the -L flags and before all the -l flags.

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.