'Can't run Python file in C

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;
}


Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Shrehan Raj Singh