簡體   English   中英

無法運行 C 中的 Python 文件

[英]Can't run Python file in C

我對 c 中的 python api 有問題。 我正在嘗試使用 PyRun_SimpleFile 運行 python 腳本,但它失敗了

我收到此錯誤: 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

編碼:

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

對 __imp_PyRun_SimpleFileExFlags 的未定義引用

is declared (possibly in file Python.h), but not defined.這意味着聲明了 function (可能在文件 Python.h 中),但未定義。 該定義存在於編譯的 python 庫中。 庫的名稱可以類似於 libpython.so(用於動態庫)或 libpython.a(用於 static 庫)。 您需要將您的程序與 python 庫鏈接。 在 gcc 中,您可以使用-l標志。 就像是

gcc -lpython3 prog.c

名稱“python3”可能會有所不同,如果庫名稱以“lib”開頭,則不需要在 -l 標志中寫入 lib。 但是,如果這不起作用,您可能需要顯式傳遞庫的位置。 您可以使用-L標志傳遞位置。

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

只有正確鏈接后,您才能使用 Python API 的功能。

已解決(至少對我而言)添加-Wl, 您的 python 安裝路徑\Python\Python version libs\python version .lib

例如

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

-Wl 之后的逗號非常重要

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM