0

I am trying to call Python code in C with this code:

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

int main()
{
    PyObject* pInt;

    Py_Initialize();

    PyRun_SimpleString("print('This is Python in C')");

    Py_Finalize();

    printf("\n");
    return 0;
} 

and have tried compiling it with this command:

gcc python_test_in_c.c 

However it returns an error returns saying:

undefined referance to `__imp __Py_Initialise`
undefined referance to `__imp__PyRun_SimpleSringFlags`
undefined referance to `__imp__Py_Finalise`
collect2.exe:  error: ld returned 1 exit status

What is going wrong? How can I fix this?

Any help would be appreciated

P.S I am not sure, but could this be something to do with the fact I copied the Python 'include' file (containing Python.h) in the include file for MinGW located at C:/MinGW

UPDATE: I have now learned this is ok to do but considered bad practice.

6
  • 1
    You did not link the library. Commented Jul 26, 2017 at 19:50
  • Please edit the title! It does not make any sense and is just missleading. You don't "embed Python code in C". You call simply functions from the Python C API. That's not different from any other library. Commented Jul 26, 2017 at 19:52
  • @Olaf technically this looks like embedding to me, see PyRun_SimpleString("print('This is Python in C')");. It is embedding via an library API. Commented Jul 27, 2017 at 5:47
  • @AjayBrahmakshatriya: The title is completely different. And this is not really embedding, but simply passing a string to a library function. It is not different from e.g. fopen Where no one would say the file contents is embedded into the C code. In fact the question is not even related to Python or possibly C, but linking and there is no information given by the user to really solve it (jut rough guesses). Commented Jul 27, 2017 at 10:51
  • @Olaf The python 2.7.13 documentation refers to this as Very High Level Embedding. See this webpage Commented Jul 29, 2017 at 19:36

1 Answer 1

2

You are not linking with the python library...

try:

gcc python_test_in_c.c -lpython3.6m

change 3.6 to your version of choice...

Sign up to request clarification or add additional context in comments.

3 Comments

I have tried this but it returns an error saying it cannot find lpython3.6m the path on my computer for python is C:\Users\Simon\AppData\Local\Programs\Python\Python36-32
try to add -L C:\Users\Simon\AppData\Local\Programs\Python\Python36-32\libs
Solved it ! Compiled it with gcc python_test_in_c.c -lpython36 added the python36 dll along with the exe and it works. The . (dot) and m in python3.6m generates an error, remove these and it works.Thanks for the help everyone.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.