0

I have a problem with python api in c. I am trying to run a python script with PyRun_SimpleFile but it fails

I get this error: d:/gcc/bin/../lib/gcc/x86_64-w64-mingw32/11.1.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\aggel\AppData\Local\Temp\ccRzYgwa.o:pyboot.c:(.text+0x47): undefined reference to __imp_PyRun_SimpleFileExFlags' collect2.exe: error: ld returned 1 exit status

The code:

define PY_SSIZE_T_CLEAN
#include <stdio.h>
#include <conio.h>
#include "Python.h"
#include "fileapi.h"
#include "fileobject.h"
int main(){

    PyObject* pInt;
    FILE *file = fopen( "test.py", "r+" );
    PyRun_SimpleFile(file, "test.py");
    return 0;
}
  • This error means that you need to link the library defining `PyRun_SimpleFile` (eg. `-lyourlibrary`). If you want more help, then you need to specify where this function is defined. – Jérôme Richard Mar 19 '22 at 16:01

2 Answers2

0

undefined reference to __imp_PyRun_SimpleFileExFlags

This means that the function PyRun_SimpleFileExFlags is declared (possibly in file Python.h), but not defined. The definition exists in the compiled python library. The name of the library can be something like libpython.so (for dynamic libraries) or libpython.a (for static libraries). You need to link your program with the python library. In gcc, you can use the -l flag. Something like

gcc -lpython3 prog.c

The name "python3" may vary, if the library name starts with "lib" you need not write lib in -l flag. However, you might need to pass the location of the library explicitly if this does not work. You can pass the location with the -L flag.

gcc -lpython3 -L/location/to/libpython.a prog.c

Only after proper linking will you be able to use the functionalities of Python API.

  • Nope. Still does the same :/ – SecurityRaven Mar 20 '22 at 21:47
  • f you are using linux, go to the top level directry (cd ~) and run this command: `find . -name *python.*` This *should* give you a list of files with python in it. If you see a libpython.so, copy the directory where it is and link it with -L flag, otherwise if you see a static library(libpython.a) you can simply directly link it with your program. `gcc -o test test.c /path/to/libpython.a`. – Shrehan Raj Singh Mar 24 '22 at 04:39
  • Oh, I am using Windows 'tho. I am Gonna try it with Linux. – SecurityRaven Mar 25 '22 at 10:14
0

SOLVED (at least for me) Add -Wl,path to your python installation\Python\Pythonversionlibs\pythonversion.lib

E.G.

-Wl,C:\Users\Developer\AppData\Local\Programs\Python\Python310\libs
python310.lib

That comma after -Wl is really important

michaeld
  • 1
  • 1