简体   繁体   English

无法运行 C 中的 Python 文件

[英]Can't run Python file in C

I have a problem with python api in c.我对 c 中的 python api 有问题。 I am trying to run a python script with PyRun_SimpleFile but it fails我正在尝试使用 PyRun_SimpleFile 运行 python 脚本,但它失败了

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我收到此错误: 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;
}

undefined reference to __imp_PyRun_SimpleFileExFlags对 __imp_PyRun_SimpleFileExFlags 的未定义引用

This means that the function PyRun_SimpleFileExFlags is declared (possibly in file Python.h), but not defined.这意味着声明了 function PyRun_SimpleFileExFlags (可能在文件 Python.h 中),但未定义。 The definition exists in the compiled python library.该定义存在于编译的 python 库中。 The name of the library can be something like libpython.so (for dynamic libraries) or libpython.a (for static libraries).库的名称可以类似于 libpython.so(用于动态库)或 libpython.a(用于 static 库)。 You need to link your program with the python library.您需要将您的程序与 python 库链接。 In gcc, you can use the -l flag.在 gcc 中,您可以使用-l标志。 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.名称“python3”可能会有所不同,如果库名称以“lib”开头,则不需要在 -l 标志中写入 lib。 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.您可以使用-L标志传递位置。

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

Only after proper linking will you be able to use the functionalities of Python API.只有正确链接后,您才能使用 Python API 的功能。

SOLVED (at least for me) Add -Wl, path to your python installation \Python\Python version libs\python version .lib已解决(至少对我而言)添加-Wl, 您的 python 安装路径\Python\Python version libs\python version .lib

EG例如

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

That comma after -Wl is really important -Wl 之后的逗号非常重要

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM